make TextEncoder/Decoder creation lazy for polyfill to work

This commit is contained in:
Florian Dold 2021-07-13 14:10:38 +02:00
parent 50bbaa40db
commit e2287d6d5b
No known key found for this signature in database
GPG Key ID: D2E4F00F29D02A4B
2 changed files with 15 additions and 13 deletions

View File

@ -19,7 +19,6 @@
*/ */
import os from "os"; import os from "os";
import fs from "fs"; import fs from "fs";
import * as clk from "./clk.js";
import { deepStrictEqual } from "assert"; import { deepStrictEqual } from "assert";
// Polyfill for encoding which isn't present globally in older nodejs versions // Polyfill for encoding which isn't present globally in older nodejs versions
import { TextEncoder, TextDecoder } from "util"; import { TextEncoder, TextDecoder } from "util";
@ -27,6 +26,7 @@ import { TextEncoder, TextDecoder } from "util";
global.TextEncoder = TextEncoder; global.TextEncoder = TextEncoder;
// @ts-ignore // @ts-ignore
global.TextDecoder = TextDecoder; global.TextDecoder = TextDecoder;
import * as clk from "./clk.js";
import { getTestInfo, runTests } from "./integrationtests/testrunner.js"; import { getTestInfo, runTests } from "./integrationtests/testrunner.js";
import { import {
PreparePayResultType, PreparePayResultType,

View File

@ -18,22 +18,13 @@
* Native implementation of GNU Taler crypto. * Native implementation of GNU Taler crypto.
*/ */
/**
* Imports.
*/
import * as nacl from "./primitives/nacl-fast.js"; import * as nacl from "./primitives/nacl-fast.js";
import bigint from "big-integer"; import bigint from "big-integer";
import { kdf } from "./primitives/kdf.js"; import { kdf } from "./primitives/kdf.js";
// @ts-ignore
const decoder = new TextDecoder();
if (typeof decoder !== "object") {
throw Error("FATAL: TextDecoder not available");
}
// @ts-ignore
const encoder = new TextEncoder();
if (typeof encoder !== "object") {
throw Error("FATAL: TextEncoder not available");
}
export function getRandomBytes(n: number): Uint8Array { export function getRandomBytes(n: number): Uint8Array {
return nacl.randomBytes(n); return nacl.randomBytes(n);
} }
@ -203,11 +194,22 @@ function kdfMod(
} }
} }
let encoder: any;
let decoder: any;
export function stringToBytes(s: string): Uint8Array { export function stringToBytes(s: string): Uint8Array {
if (!encoder) {
// @ts-ignore
encoder = new TextEncoder();
}
return encoder.encode(s); return encoder.encode(s);
} }
export function bytesToString(b: Uint8Array): string { export function bytesToString(b: Uint8Array): string {
if (!decoder) {
// @ts-ignore
decoder = new TextDecoder();
}
return decoder.decode(b); return decoder.decode(b);
} }