Skip to content

Commit

Permalink
Fix: Add crypto-js for the case of missing crypto.subtle in the browser
Browse files Browse the repository at this point in the history
crypto.subtle is avaiable if the browser open the browser example in
localhost or 127.0.0.1. But it is not available if the browser open the
browser example in other ip address. So we need to add crypto-js for the
case of missing crypto.subtle in the browser.
  • Loading branch information
sparkleholic committed Dec 9, 2024
1 parent fbaa666 commit c181a23
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 1 deletion.
14 changes: 13 additions & 1 deletion clients/js/examples/browser/app.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React, { useCallback, useEffect, useState } from "react";
import { ChromaClient } from "../../src/ChromaClient";
import { Collection } from "../../src/types";
import CryptoJS from "crypto-js";

const SAMPLE_DOCUMENTS = [
"apple",
Expand All @@ -14,7 +15,18 @@ const SAMPLE_DOCUMENTS = [
const hashString = async (message: string) => {
const encoder = new TextEncoder();
const data = encoder.encode(message);
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
let hashBuffer;
if (crypto.subtle) {
hashBuffer = await crypto.subtle.digest("SHA-256", data);
} else {
const hash = CryptoJS.SHA256(CryptoJS.enc.Utf8.parse(message));
hashBuffer = new Uint8Array(hash.words.map(word => [
(word >> 24) & 0xff,
(word >> 16) & 0xff,
(word >> 8) & 0xff,
word & 0xff
]).flat());
}
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
};
Expand Down
1 change: 1 addition & 0 deletions clients/js/examples/browser/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
},
"dependencies": {
"chromadb": "link:../..",
"crypto-js": "^4.2.0",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
Expand Down
1 change: 1 addition & 0 deletions clients/js/examples/browser/vite.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
server: {
host: "0.0.0.0",
port: 3000,
},
// This manual remapping is only needed because we're loading a locally linked version of the JS client
Expand Down

0 comments on commit c181a23

Please sign in to comment.