* Generates runtime code for this runtime module. * @returns {string | null} runtime code
()
| 21 | * @returns {string | null} runtime code |
| 22 | */ |
| 23 | generate() { |
| 24 | const compilation = /** @type {Compilation} */ (this.compilation); |
| 25 | const fn = RuntimeGlobals.toBinary; |
| 26 | const { runtimeTemplate } = compilation; |
| 27 | |
| 28 | // Inspired by esbuild |
| 29 | |
| 30 | const isNodePlatform = compilation.compiler.platform.node; |
| 31 | const isWebPlatform = compilation.compiler.platform.web; |
| 32 | const isNeutralPlatform = runtimeTemplate.isNeutralPlatform(); |
| 33 | const toImmutableBytes = runtimeTemplate.basicFunction("value", [ |
| 34 | runtimeTemplate.destructureObject(["buffer"], "value"), |
| 35 | `${runtimeTemplate.renderConst()} throwErr = ${runtimeTemplate.basicFunction("", ["throw new TypeError('ArrayBuffer is immutable');"])};`, |
| 36 | "Object.defineProperties(buffer, { immutable: { value: true }, resize: { value: throwErr }, transfer: { value: throwErr }, transferToFixedLength: { value: throwErr } });", |
| 37 | "Object.freeze(buffer);", |
| 38 | "return value;" |
| 39 | ]); |
| 40 | |
| 41 | return Template.asString([ |
| 42 | "// define to binary helper", |
| 43 | `${runtimeTemplate.renderConst()} toImmutableBytes = ${toImmutableBytes}`, |
| 44 | `${fn} = ${isNeutralPlatform ? "typeof Buffer !== 'undefined' ? " : ""}${ |
| 45 | isNodePlatform || isNeutralPlatform |
| 46 | ? `${runtimeTemplate.returningFunction("toImmutableBytes(new Uint8Array(Buffer.from(base64, 'base64')))", "base64")}` |
| 47 | : "" |
| 48 | } ${isNeutralPlatform ? ": " : ""}${ |
| 49 | isWebPlatform || isNeutralPlatform |
| 50 | ? `(${runtimeTemplate.basicFunction("", [ |
| 51 | `${runtimeTemplate.renderConst()} table = new Uint8Array(128);`, |
| 52 | "for (var i = 0; i < 64; i++) table[i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i * 4 - 205] = i;", |
| 53 | `return ${runtimeTemplate.basicFunction("base64", [ |
| 54 | `${runtimeTemplate.renderConst()} n = base64.length, bytes = new Uint8Array((n - (base64[n - 1] == '=') - (base64[n - 2] == '=')) * 3 / 4 | 0);`, |
| 55 | "for (var i = 0, j = 0; i < n;) {", |
| 56 | Template.indent([ |
| 57 | `${runtimeTemplate.renderConst()} c0 = table[base64.charCodeAt(i++)], c1 = table[base64.charCodeAt(i++)];`, |
| 58 | `${runtimeTemplate.renderConst()} c2 = table[base64.charCodeAt(i++)], c3 = table[base64.charCodeAt(i++)];`, |
| 59 | "bytes[j++] = (c0 << 2) | (c1 >> 4);", |
| 60 | "bytes[j++] = (c1 << 4) | (c2 >> 2);", |
| 61 | "bytes[j++] = (c2 << 6) | c3;" |
| 62 | ]), |
| 63 | "}", |
| 64 | "return toImmutableBytes(bytes)" |
| 65 | ])}` |
| 66 | ])})();` |
| 67 | : "" |
| 68 | }` |
| 69 | ]); |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | module.exports = ToBinaryRuntimeModule; |
nothing calls this directly
no test coverage detected