diff --git a/sdk/package.json b/sdk/package.json index 1b61167..86057d7 100644 --- a/sdk/package.json +++ b/sdk/package.json @@ -6,7 +6,8 @@ "scripts": { "build": "node build.mjs", "test": "vitest run", - "checksize": "node build.mjs && gzip -c dist/v1.js | wc -c" + "typecheck": "tsc --noEmit", + "checksize": "node build.mjs && node -e \"const z=require('zlib'),f=require('fs');console.log('gzip bytes:',z.gzipSync(f.readFileSync('dist/v1.js')).length)\"" }, "devDependencies": { "esbuild": "^0.24.0", diff --git a/sdk/src/util.ts b/sdk/src/util.ts index 5bcc114..157c5e6 100644 --- a/sdk/src/util.ts +++ b/sdk/src/util.ts @@ -1,5 +1,6 @@ export function uuid(): string { - if (globalThis.crypto?.randomUUID) return crypto.randomUUID(); + const c = globalThis.crypto as Crypto | undefined; + if (c?.randomUUID) return c.randomUUID(); return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { const r = (Math.random() * 16) | 0; return (c === "x" ? r : (r & 0x3) | 0x8).toString(16); diff --git a/sdk/test/util.test.ts b/sdk/test/util.test.ts index 7cf9507..aceefb3 100644 --- a/sdk/test/util.test.ts +++ b/sdk/test/util.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect } from "vitest"; +import { describe, it, expect, vi } from "vitest"; import { uuid } from "../src/util"; describe("uuid", () => { it("生成 36 位且不重复", () => { @@ -6,4 +6,11 @@ describe("uuid", () => { expect(a).toMatch(/^[0-9a-f-]{36}$/); expect(a).not.toBe(b); }); + it("Math.random 降级分支:格式正确且唯一", () => { + vi.stubGlobal("crypto", {}); + const a = uuid(), b = uuid(); + expect(a).toMatch(/^[0-9a-f-]{36}$/); + expect(a).not.toBe(b); + vi.unstubAllGlobals(); + }); }); diff --git a/sdk/tsconfig.json b/sdk/tsconfig.json index 05ebb33..77f6b7a 100644 --- a/sdk/tsconfig.json +++ b/sdk/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "target": "ES2018", + "lib": ["ES2018", "DOM"], "module": "ESNext", "moduleResolution": "bundler", "strict": true,