let crypto = globalThis.crypto; let { subtle } = crypto; import { IbGib_V1 } from 'ts-gib/dist/V1/types.mjs'; /** * Test helper functions. */ import * as h from './helper.mjs'; describe(`foo clone`, () => { it(`should foo Clone yo (testing node/browser isomorphic packages)`, () => { let obj = 1; let clone = h.fooClone(obj); expect(clone).withContext('clone foo yo').toEqual(obj); // expect(1).withContext('expected fail test case').toBe(2); }); it(`should foo getibAndGib yo (testing node/browser isomorphic packages)`, () => { let result = h.fooGetIbAndGib(); expect(result.ib).withContext('ib').toEqual('ib'); }); it(`should foo factory yo (testing node/browser isomorphic packages)`, async () => { let result = await h.fooFactory(); expect(result).withContext('result').toBeTruthy(); expect(result.ib).withContext('result.ib').toBeTruthy(); }); }); async function hash({ s, }: { s: string, }): Promise { if (!s) { return ''; } let algorithm = 'SHA-256'; try { const msgUint8 = new TextEncoder().encode(s); const buffer = await subtle.digest(algorithm, msgUint8); const asArray = Array.from(new Uint8Array(buffer)); return asArray.map(b => b.toString(16).padStart(2, '0')).join(''); } catch (e) { console.error(e.message ?? e); throw e; } } describe(`non-ts-gib isomorphic crypto hashing`, () => { it(`should digest simple string consistently using crypto.subtle directly `, async () => { let h = await hash({ s: '42' }); expect(h).withContext('42').toBe('73475cb40a568e8da8a045ced110137e159f890ac4da883b6b17dc651b3a8049'); }); it(`should digest simple stringified ibgib consistently using crypto.subtle directly `, async () => { let ibgib: IbGib_V1 = { ib: 'ib', gib: 'gib' }; let h = await hash({ s: JSON.stringify(ibgib) }); // doesn't use ts-gib but consistent stringifying json is important expect(h).withContext('ib^gib').toBe('cbad0694a257358c044611ea1fa88ace71a01a9b8409d2354d0387d8043f7671'); }); });