1import * as DenoCrypto from "@effect/platform-deno/DenoCrypto"
2import { assert, describe, it } from "@effect/vitest"
3import * as Crypto from "effect/Crypto"
4import * as Effect from "effect/Effect"
5
6const uuidV4Regex = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
7const uuidV7Regex = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
8
9const hex = (bytes: Uint8Array): string => Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("")
10
11describe("DenoCrypto", () => {
12 it.effect("computes SHA-256 digests", () =>
13 Effect.gen(function*() {
14 const crypto = yield* Crypto.Crypto
15 const digest = yield* crypto.digest("SHA-256", new TextEncoder().encode("hello"))
16 assert.strictEqual(hex(digest), "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824")
17 }).pipe(Effect.provide(DenoCrypto.layer)))
18
19 it.effect("generates random bytes larger than the Web Crypto quota", () =>
20 Effect.gen(function*() {
21 const crypto = yield* Crypto.Crypto
22 const bytes = yield* crypto.randomBytes(70_000)
23 assert.strictEqual(bytes.length, 70_000)
24 }).pipe(Effect.provide(DenoCrypto.layer)))
25
26 it.effect("generates UUIDv4 values", () =>
27 Effect.gen(function*() {
28 const crypto = yield* Crypto.Crypto
29 assert.match(yield* crypto.randomUUIDv4, uuidV4Regex)
30 }).pipe(Effect.provide(DenoCrypto.layer)))
31
32 it.effect("generates UUIDv7 values", () =>
33 Effect.gen(function*() {
34 const crypto = yield* Crypto.Crypto
35 assert.match(yield* crypto.randomUUIDv7, uuidV7Regex)
36 }).pipe(Effect.provide(DenoCrypto.layer)))
37})