@avalix/chroma 0.0.9 → 0.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,9 +4,10 @@ import path from "node:path";
4
4
  import process from "node:process";
5
5
 
6
6
  //#region src/wallets/polkadot-js.ts
7
+ const VERSION$1 = "0.62.6";
7
8
  const POLKADOT_JS_CONFIG = {
8
- downloadUrl: "https://github.com/polkadot-js/extension/releases/download/v0.61.7/master-chrome-build.zip",
9
- extensionName: "polkadot-extension-0.61.7"
9
+ downloadUrl: `https://github.com/polkadot-js/extension/releases/download/v${VERSION$1}/master-chrome-build.zip`,
10
+ extensionName: `polkadot-extension-${VERSION$1}`
10
11
  };
11
12
  async function findExtensionPopup$1(context, extensionId) {
12
13
  const maxAttempts = 10;
@@ -25,7 +26,6 @@ async function getPolkadotJSExtensionPath() {
25
26
  const extensionsDir = path.resolve(process.cwd(), ".chroma");
26
27
  const extensionDir = path.join(extensionsDir, POLKADOT_JS_CONFIG.extensionName);
27
28
  if (!fs.existsSync(extensionDir) || fs.readdirSync(extensionDir).length === 0) throw new Error(`Polkadot-JS extension not found at: ${extensionDir}\n\nPlease download the extension first by running:\n npx @avalix/chroma download-extensions\n`);
28
- console.log(`✅ Found Polkadot-JS extension at: ${extensionDir}`);
29
29
  return extensionDir;
30
30
  }
31
31
  async function importPolkadotJSAccount(page, { seed, name = "Test Account", password = "h3llop0lkadot!" }) {
@@ -39,6 +39,7 @@ async function importPolkadotJSAccount(page, { seed, name = "Test Account", pass
39
39
  await understoodButton.click();
40
40
  await extensionPage.waitForTimeout(100);
41
41
  }
42
+ if (await extensionPage.getByRole("button", { name: "I Understand" }).isVisible()) await extensionPage.getByRole("button", { name: "I Understand" }).click();
42
43
  await extensionPage.goto(`${extensionPopupUrl}#/account/import-seed`);
43
44
  await extensionPage.locator("textarea").fill(seed);
44
45
  await extensionPage.locator("button:has-text(\"Next\")").click();
@@ -46,7 +47,6 @@ async function importPolkadotJSAccount(page, { seed, name = "Test Account", pass
46
47
  await extensionPage.locator("input[type=\"password\"]").fill(password);
47
48
  await extensionPage.locator("div").filter({ hasText: /^Repeat password for verification$/ }).getByRole("textbox").fill(password);
48
49
  await extensionPage.getByRole("button", { name: "Add the account with the supplied seed" }).click();
49
- console.log(`✅ Created Polkadot-JS wallet account: ${name}`);
50
50
  } finally {
51
51
  await extensionPage.close();
52
52
  }
@@ -55,9 +55,9 @@ async function authorizePolkadotJS(page) {
55
55
  const context = page.__extensionContext;
56
56
  const extensionId = page.__extensionId;
57
57
  const extensionPopup = await findExtensionPopup$1(context, extensionId);
58
- await extensionPopup.getByText("Select all").click();
58
+ if (await extensionPopup.getByRole("button", { name: "I Understand" }).isVisible()) await extensionPopup.getByRole("button", { name: "I Understand" }).click();
59
+ if (!await extensionPopup.getByText("Select all").locator("..").locator("input[type=\"checkbox\"]").isChecked().catch(() => false)) await extensionPopup.getByText("Select all").click();
59
60
  await extensionPopup.getByRole("button", { name: /Connect \d+ account\(s\)/ }).click();
60
- console.log("✅ Polkadot-JS wallet connected successfully");
61
61
  }
62
62
  async function approvePolkadotJSTx(page, options = {}) {
63
63
  const { password = "h3llop0lkadot!" } = options;
@@ -66,20 +66,19 @@ async function approvePolkadotJSTx(page, options = {}) {
66
66
  const extensionPopup = await findExtensionPopup$1(context, extensionId);
67
67
  await extensionPopup.getByRole("textbox").fill(password);
68
68
  await extensionPopup.getByRole("button", { name: "Sign the transaction" }).click();
69
- console.log("✅ Polkadot-JS transaction signed successfully");
70
69
  }
71
70
  async function rejectPolkadotJSTx(page) {
72
71
  const context = page.__extensionContext;
73
72
  const extensionId = page.__extensionId;
74
73
  await (await findExtensionPopup$1(context, extensionId)).getByRole("link", { name: "Cancel" }).click();
75
- console.log("✅ Polkadot-JS transaction rejected successfully");
76
74
  }
77
75
 
78
76
  //#endregion
79
77
  //#region src/wallets/talisman.ts
78
+ const VERSION = "3.1.13";
80
79
  const TALISMAN_CONFIG = {
81
- downloadUrl: "https://github.com/avalix-labs/polkadot-wallets/raw/refs/heads/main/talisman/talisman-3.0.5.zip",
82
- extensionName: "talisman-extension-3.0.5"
80
+ downloadUrl: `https://github.com/avalix-labs/polkadot-wallets/raw/refs/heads/main/talisman/talisman-${VERSION}.zip`,
81
+ extensionName: `talisman-extension-${VERSION}`
83
82
  };
84
83
  async function findExtensionPopup(context, extensionId) {
85
84
  const maxAttempts = 10;
@@ -102,7 +101,6 @@ async function getTalismanExtensionPath() {
102
101
  const extensionsDir = path.resolve(process.cwd(), ".chroma");
103
102
  const extensionDir = path.join(extensionsDir, TALISMAN_CONFIG.extensionName);
104
103
  if (!fs.existsSync(extensionDir) || fs.readdirSync(extensionDir).length === 0) throw new Error(`Talisman extension not found at: ${extensionDir}\n\nPlease download the extension first by running:\n npx @avalix/chroma download-extensions\n`);
105
- console.log(`✅ Found Talisman extension at: ${extensionDir}`);
106
104
  return extensionDir;
107
105
  }
108
106
  async function importEthPrivateKey(page, { seed, name = "Test Account", password = "h3llop0lkadot!" }) {
@@ -115,18 +113,13 @@ async function importEthPrivateKey(page, { seed, name = "Test Account", password
115
113
  const pages = context.pages();
116
114
  for (const p of pages) {
117
115
  const url = p.url();
118
- console.log(`📄 Found page: ${url}`);
119
116
  if (url.includes("onboarding.html") || url.includes(`chrome-extension://${extensionId}/`)) {
120
117
  extensionPage = p;
121
- console.log(`✅ Found Talisman onboarding page: ${url}`);
122
118
  break;
123
119
  }
124
120
  }
125
121
  if (extensionPage) break;
126
- if (attempt < maxAttempts - 1) {
127
- console.log(`⏳ Attempt ${attempt + 1}/${maxAttempts}: Waiting for onboarding page...`);
128
- await new Promise((resolve) => setTimeout(resolve, retryDelay));
129
- }
122
+ if (attempt < maxAttempts - 1) await new Promise((resolve) => setTimeout(resolve, retryDelay));
130
123
  }
131
124
  if (!extensionPage) throw new Error(`Talisman onboarding page not found after ${maxAttempts} attempts`);
132
125
  try {
@@ -147,7 +140,6 @@ async function importEthPrivateKey(page, { seed, name = "Test Account", password
147
140
  await extensionPage.getByRole("textbox", { name: "Enter your private key" }).fill(seed);
148
141
  await extensionPage.getByRole("button", { name: "Save" }).click();
149
142
  await extensionPage.close();
150
- console.log("✅ Talisman account import completed");
151
143
  } catch (error) {
152
144
  console.error("❌ Error during Talisman account import:", error);
153
145
  throw error;
@@ -162,14 +154,18 @@ async function authorizeTalisman(page, options = {}) {
162
154
  await extensionPopup.getByTestId("connection-connect-button").click();
163
155
  try {
164
156
  await (await findExtensionPopup(context, extensionId)).getByRole("button", { name: "Approve" }).click();
165
- } catch {
166
- console.log("No another popup found, skipping");
167
- }
157
+ } catch {}
168
158
  }
169
159
  async function approveTalismanTx(page) {
170
160
  const context = page.__extensionContext;
171
161
  const extensionId = page.__extensionId;
172
- await (await findExtensionPopup(context, extensionId)).getByRole("button", { name: "Approve" }).click();
162
+ const extensionPopup = await findExtensionPopup(context, extensionId);
163
+ try {
164
+ await extensionPopup.getByRole("button", { name: "Yes" }).click();
165
+ } catch {
166
+ console.log("No another popup found, skipping");
167
+ }
168
+ await extensionPopup.getByRole("button", { name: "Approve" }).click();
173
169
  }
174
170
  async function rejectTalismanTx(page) {
175
171
  const context = page.__extensionContext;
@@ -194,8 +190,7 @@ function createWalletInstance(walletType, extensionId, context) {
194
190
  const baseInstance = {
195
191
  extensionId,
196
192
  importMnemonic: async (options) => {
197
- const page = context.pages()[0] || await context.newPage();
198
- const extPage = createExtendedPage(page, context, extensionId);
193
+ const extPage = createExtendedPage(context.pages()[0] || await context.newPage(), context, extensionId);
199
194
  importedAccountName = options.name || "Test Account";
200
195
  switch (walletType) {
201
196
  case "polkadot-js":
@@ -206,8 +201,7 @@ function createWalletInstance(walletType, extensionId, context) {
206
201
  }
207
202
  },
208
203
  authorize: async (options = {}) => {
209
- const page = context.pages()[0] || await context.newPage();
210
- const extPage = createExtendedPage(page, context, extensionId);
204
+ const extPage = createExtendedPage(context.pages()[0] || await context.newPage(), context, extensionId);
211
205
  const accountName = options.accountName || importedAccountName;
212
206
  switch (walletType) {
213
207
  case "polkadot-js":
@@ -220,8 +214,7 @@ function createWalletInstance(walletType, extensionId, context) {
220
214
  }
221
215
  },
222
216
  approveTx: async (options = {}) => {
223
- const page = context.pages()[0] || await context.newPage();
224
- const extPage = createExtendedPage(page, context, extensionId);
217
+ const extPage = createExtendedPage(context.pages()[0] || await context.newPage(), context, extensionId);
225
218
  switch (walletType) {
226
219
  case "polkadot-js":
227
220
  await approvePolkadotJSTx(extPage, options);
@@ -233,8 +226,7 @@ function createWalletInstance(walletType, extensionId, context) {
233
226
  }
234
227
  },
235
228
  rejectTx: async () => {
236
- const page = context.pages()[0] || await context.newPage();
237
- const extPage = createExtendedPage(page, context, extensionId);
229
+ const extPage = createExtendedPage(context.pages()[0] || await context.newPage(), context, extensionId);
238
230
  switch (walletType) {
239
231
  case "polkadot-js":
240
232
  await rejectPolkadotJSTx(extPage);
@@ -255,8 +247,7 @@ function createWalletInstance(walletType, extensionId, context) {
255
247
  ...baseInstance,
256
248
  type: "talisman",
257
249
  importEthPrivateKey: async (options) => {
258
- const page = context.pages()[0] || await context.newPage();
259
- const extPage = createExtendedPage(page, context, extensionId);
250
+ const extPage = createExtendedPage(context.pages()[0] || await context.newPage(), context, extensionId);
260
251
  importedAccountName = options.name || "Test Account";
261
252
  await importEthPrivateKey(extPage, {
262
253
  seed: options.privateKey,
@@ -304,7 +295,6 @@ function createWalletTest(options = {}) {
304
295
  const extensionId = allServiceWorkers[i].url().split("/")[2];
305
296
  const walletType = walletConfigs[i].type;
306
297
  extensionIds.set(walletType, extensionId);
307
- console.log(`✅ Loaded ${walletType} extension with ID: ${extensionId}`);
308
298
  }
309
299
  await use(extensionIds);
310
300
  }, { scope: "worker" }],
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@avalix/chroma",
3
3
  "type": "module",
4
- "version": "0.0.9",
4
+ "version": "0.0.11",
5
5
  "description": "End-to-end testing library for Polkadot wallet interactions",
6
6
  "author": "Avalix Labs",
7
7
  "license": "MIT",
@@ -24,12 +24,12 @@
24
24
  "blockchain"
25
25
  ],
26
26
  "exports": {
27
- ".": "./dist/index.js",
27
+ ".": "./dist/index.mjs",
28
28
  "./package.json": "./package.json"
29
29
  },
30
- "main": "./dist/index.js",
31
- "module": "./dist/index.js",
32
- "types": "./dist/index.d.ts",
30
+ "main": "./dist/index.mjs",
31
+ "module": "./dist/index.mjs",
32
+ "types": "./dist/index.d.mts",
33
33
  "bin": {
34
34
  "chroma": "./scripts/cli.js"
35
35
  },
@@ -43,22 +43,27 @@
43
43
  "dev": "tsdown --watch",
44
44
  "lint": "eslint --fix .",
45
45
  "prepublishOnly": "npm run build",
46
- "download-extensions": "rm -rf .chroma && tsx scripts/download-extensions.ts"
46
+ "download-extensions": "rm -rf .chroma && tsx scripts/download-extensions.ts",
47
+ "test": "playwright test --ui",
48
+ "test:unit": "vitest",
49
+ "test:unit:run": "vitest run",
50
+ "test:unit:coverage": "vitest run --coverage"
47
51
  },
48
52
  "peerDependencies": {
49
- "@playwright/test": "^1.55.0"
53
+ "@playwright/test": "^1.57.0"
50
54
  },
51
55
  "dependencies": {
52
- "unzipper": "^0.12.3"
56
+ "adm-zip": "^0.5.16"
53
57
  },
54
58
  "devDependencies": {
55
- "@antfu/eslint-config": "^5.3.0",
56
- "@playwright/test": "^1.55.0",
57
- "@types/node": "^24.3.3",
58
- "@types/unzipper": "^0.10.10",
59
- "eslint": "^9.35.0",
60
- "tsdown": "latest",
61
- "tsx": "^4.20.6"
59
+ "@antfu/eslint-config": "^6.5.1",
60
+ "@playwright/test": "^1.57.0",
61
+ "@types/node": "^24.10.2",
62
+ "@types/unzipper": "^0.10.11",
63
+ "eslint": "^9.39.1",
64
+ "tsdown": "^0.20.1",
65
+ "tsx": "^4.21.0",
66
+ "vitest": "^4.0.18"
62
67
  },
63
68
  "publishConfig": {
64
69
  "access": "public"
@@ -1,13 +1,38 @@
1
1
  #!/usr/bin/env node
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
2
4
  import process from 'node:process'
5
+ import { fileURLToPath } from 'node:url'
3
6
  import { downloadAndExtractExtension } from '../src/utils/download-extension.js'
4
7
  import { POLKADOT_JS_CONFIG } from '../src/wallets/polkadot-js.js'
5
8
  import { TALISMAN_CONFIG } from '../src/wallets/talisman.js'
6
9
 
10
+ const __dirname = path.dirname(fileURLToPath(import.meta.url))
11
+
12
+ async function getVersion(): Promise<string> {
13
+ const packageJsonPath = path.resolve(__dirname, '../package.json')
14
+ const packageJson = JSON.parse(await fs.promises.readFile(packageJsonPath, 'utf-8'))
15
+ return packageJson.version
16
+ }
17
+
18
+ async function clearChromaDir(): Promise<void> {
19
+ const chromaDir = path.resolve(process.cwd(), '.chroma')
20
+
21
+ if (fs.existsSync(chromaDir)) {
22
+ console.log('🗑️ Clearing existing .chroma directory...')
23
+ await fs.promises.rm(chromaDir, { recursive: true, force: true })
24
+ }
25
+ }
26
+
7
27
  async function main() {
8
- console.log('🚀 Downloading Chroma wallet extensions...\n')
28
+ const version = await getVersion()
29
+ console.log(`🎨 Chroma v${version}\n`)
30
+ console.log('🚀 Downloading wallet extensions...\n')
9
31
 
10
32
  try {
33
+ // Clear existing .chroma directory
34
+ await clearChromaDir()
35
+
11
36
  // Download Polkadot-JS extension
12
37
  await downloadAndExtractExtension({
13
38
  downloadUrl: POLKADOT_JS_CONFIG.downloadUrl,
@@ -97,7 +97,6 @@ export function createWalletTest<const T extends readonly WalletConfig[]>(
97
97
  const extensionId = allServiceWorkers[i].url().split('/')[2]
98
98
  const walletType = walletConfigs[i].type
99
99
  extensionIds.set(walletType, extensionId)
100
- console.log(`✅ Loaded ${walletType} extension with ID: ${extensionId}`)
101
100
  }
102
101
 
103
102
  await use(extensionIds)
@@ -0,0 +1,95 @@
1
+ import type { DownloadExtensionOptions } from './download-extension.js'
2
+ import fs from 'node:fs'
3
+ import os from 'node:os'
4
+ import path from 'node:path'
5
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest'
6
+ import { downloadAndExtractExtension } from './download-extension.js'
7
+
8
+ /**
9
+ * Integration Tests (real download) - Requires network
10
+ * Tests actual download and extraction with real extension files
11
+ *
12
+ * Important test cases:
13
+ * - Nested zip extraction (Talisman has a zip inside a zip)
14
+ * - Standard zip extraction (Polkadot-JS)
15
+ * - Skip download if already exists
16
+ * - Error handling for invalid URLs
17
+ */
18
+ describe('downloadAndExtractExtension (integration tests)', () => {
19
+ let tempDir: string
20
+
21
+ beforeEach(async () => {
22
+ tempDir = path.join(os.tmpdir(), `chroma-test-${Date.now()}-${Math.random().toString(36).slice(2)}`)
23
+ await fs.promises.mkdir(tempDir, { recursive: true })
24
+ })
25
+
26
+ afterEach(async () => {
27
+ if (tempDir && fs.existsSync(tempDir)) {
28
+ await fs.promises.rm(tempDir, { recursive: true, force: true })
29
+ }
30
+ })
31
+
32
+ it('should handle nested zip extraction (Talisman)', async () => {
33
+ // Talisman extension has a nested zip structure
34
+ const VERSION = '3.1.13'
35
+ const options: DownloadExtensionOptions = {
36
+ downloadUrl: `https://github.com/avalix-labs/polkadot-wallets/raw/refs/heads/main/talisman/talisman-${VERSION}.zip`,
37
+ extensionName: `talisman-extension-${VERSION}`,
38
+ targetDir: tempDir,
39
+ }
40
+
41
+ const result = await downloadAndExtractExtension(options)
42
+
43
+ expect(result).toBe(path.join(tempDir, `talisman-extension-${VERSION}`))
44
+ expect(fs.existsSync(result)).toBe(true)
45
+
46
+ // Talisman should have manifest.json after nested extraction
47
+ const files = await fs.promises.readdir(result)
48
+ expect(files).toContain('manifest.json')
49
+ }, 60000)
50
+
51
+ it('should handle standard zip extraction (Polkadot-JS)', async () => {
52
+ const VERSION = '0.62.6'
53
+ const options: DownloadExtensionOptions = {
54
+ downloadUrl: `https://github.com/polkadot-js/extension/releases/download/v${VERSION}/master-chrome-build.zip`,
55
+ extensionName: `polkadot-extension-${VERSION}`,
56
+ targetDir: tempDir,
57
+ }
58
+
59
+ const result = await downloadAndExtractExtension(options)
60
+
61
+ expect(result).toBe(path.join(tempDir, `polkadot-extension-${VERSION}`))
62
+ expect(fs.existsSync(result)).toBe(true)
63
+
64
+ const files = await fs.promises.readdir(result)
65
+ expect(files).toContain('manifest.json')
66
+ }, 60000)
67
+
68
+ it('should skip download if extension already exists', async () => {
69
+ const extensionDir = path.join(tempDir, 'existing-extension')
70
+ await fs.promises.mkdir(extensionDir, { recursive: true })
71
+ await fs.promises.writeFile(path.join(extensionDir, 'manifest.json'), '{"name": "test"}')
72
+
73
+ const options: DownloadExtensionOptions = {
74
+ downloadUrl: 'https://example.com/should-not-be-called.zip',
75
+ extensionName: 'existing-extension',
76
+ targetDir: tempDir,
77
+ }
78
+
79
+ const result = await downloadAndExtractExtension(options)
80
+
81
+ expect(result).toBe(extensionDir)
82
+ })
83
+
84
+ it('should throw error for invalid URL', async () => {
85
+ const options: DownloadExtensionOptions = {
86
+ downloadUrl: 'https://github.com/invalid-user-12345/nonexistent-repo/releases/download/v0.0.0/nonexistent.zip',
87
+ extensionName: 'invalid-extension',
88
+ targetDir: tempDir,
89
+ }
90
+
91
+ await expect(downloadAndExtractExtension(options)).rejects.toThrow(
92
+ /Failed to download\/extract invalid-extension/,
93
+ )
94
+ }, 15000)
95
+ })
@@ -0,0 +1,173 @@
1
+ import type { DownloadExtensionOptions } from './download-extension.js'
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
5
+ import { downloadAndExtractExtension } from './download-extension.js'
6
+
7
+ /**
8
+ * Unit Tests (with mocks) - Fast, no network required
9
+ * Tests error handling, cleanup logic, and path resolution
10
+ */
11
+
12
+ // Mock adm-zip
13
+ const mockExtractAllTo = vi.fn()
14
+ vi.mock('adm-zip', () => {
15
+ return {
16
+ default: vi.fn().mockImplementation(() => ({
17
+ extractAllTo: mockExtractAllTo,
18
+ })),
19
+ }
20
+ })
21
+
22
+ // Mock fetch
23
+ const mockFetch = vi.fn()
24
+ vi.stubGlobal('fetch', mockFetch)
25
+
26
+ // Mock stream/promises pipeline
27
+ vi.mock('node:stream/promises', () => ({
28
+ pipeline: vi.fn().mockResolvedValue(undefined),
29
+ }))
30
+
31
+ // Mock fs module
32
+ vi.mock('node:fs', async () => {
33
+ const actual = await vi.importActual<typeof import('node:fs')>('node:fs')
34
+ return {
35
+ ...actual,
36
+ default: {
37
+ ...actual,
38
+ existsSync: vi.fn(),
39
+ readdirSync: vi.fn(),
40
+ promises: {
41
+ mkdir: vi.fn().mockResolvedValue(undefined),
42
+ rm: vi.fn().mockResolvedValue(undefined),
43
+ rename: vi.fn().mockResolvedValue(undefined),
44
+ unlink: vi.fn().mockResolvedValue(undefined),
45
+ readdir: vi.fn().mockResolvedValue([]),
46
+ },
47
+ createWriteStream: vi.fn().mockReturnValue({
48
+ on: vi.fn(),
49
+ write: vi.fn(),
50
+ end: vi.fn(),
51
+ }),
52
+ },
53
+ existsSync: vi.fn(),
54
+ readdirSync: vi.fn(),
55
+ createWriteStream: vi.fn().mockReturnValue({
56
+ on: vi.fn(),
57
+ write: vi.fn(),
58
+ end: vi.fn(),
59
+ }),
60
+ }
61
+ })
62
+
63
+ describe('downloadAndExtractExtension (unit tests)', () => {
64
+ const mockOptions: DownloadExtensionOptions = {
65
+ downloadUrl: 'https://example.com/extension.zip',
66
+ extensionName: 'test-extension',
67
+ }
68
+
69
+ beforeEach(() => {
70
+ vi.clearAllMocks()
71
+ vi.spyOn(console, 'log').mockImplementation(() => {})
72
+ })
73
+
74
+ afterEach(() => {
75
+ vi.restoreAllMocks()
76
+ })
77
+
78
+ describe('when extension already exists', () => {
79
+ it('should skip download and return existing path', async () => {
80
+ const mockedFs = vi.mocked(fs)
81
+ mockedFs.existsSync.mockReturnValue(true)
82
+ mockedFs.readdirSync.mockReturnValue(['manifest.json'] as any)
83
+
84
+ const result = await downloadAndExtractExtension(mockOptions)
85
+
86
+ expect(result).toContain('test-extension')
87
+ expect(mockFetch).not.toHaveBeenCalled()
88
+ expect(console.log).toHaveBeenCalledWith(
89
+ expect.stringContaining('already exists'),
90
+ expect.any(String),
91
+ )
92
+ })
93
+ })
94
+
95
+ describe('when extension does not exist', () => {
96
+ beforeEach(() => {
97
+ const mockedFs = vi.mocked(fs)
98
+ mockedFs.existsSync.mockReturnValue(false)
99
+ mockedFs.readdirSync.mockReturnValue([])
100
+ })
101
+
102
+ it('should throw error when download fails with bad status', async () => {
103
+ mockFetch.mockResolvedValue({
104
+ ok: false,
105
+ status: 404,
106
+ statusText: 'Not Found',
107
+ })
108
+
109
+ await expect(downloadAndExtractExtension(mockOptions)).rejects.toThrow(
110
+ 'Failed to download/extract test-extension',
111
+ )
112
+ })
113
+
114
+ it('should throw error when fetch throws network error', async () => {
115
+ mockFetch.mockRejectedValue(new Error('Network error'))
116
+
117
+ await expect(downloadAndExtractExtension(mockOptions)).rejects.toThrow(
118
+ 'Failed to download/extract test-extension: Network error',
119
+ )
120
+ })
121
+
122
+ it('should cleanup files on error', async () => {
123
+ const mockedFs = vi.mocked(fs)
124
+
125
+ mockFetch.mockResolvedValue({
126
+ ok: false,
127
+ status: 500,
128
+ statusText: 'Internal Server Error',
129
+ })
130
+
131
+ mockedFs.existsSync.mockImplementation((p: fs.PathLike) => {
132
+ const pathStr = p.toString()
133
+ if (pathStr.endsWith('test-extension') && !pathStr.includes('.zip')) {
134
+ return false
135
+ }
136
+ return true
137
+ })
138
+
139
+ await expect(downloadAndExtractExtension(mockOptions)).rejects.toThrow()
140
+
141
+ expect(mockedFs.promises.unlink).toHaveBeenCalled()
142
+ expect(mockedFs.promises.rm).toHaveBeenCalled()
143
+ })
144
+ })
145
+
146
+ describe('targetDir option', () => {
147
+ it('should use custom targetDir when provided', async () => {
148
+ const mockedFs = vi.mocked(fs)
149
+ mockedFs.existsSync.mockReturnValue(true)
150
+ mockedFs.readdirSync.mockReturnValue(['manifest.json'] as any)
151
+
152
+ const customOptions: DownloadExtensionOptions = {
153
+ ...mockOptions,
154
+ targetDir: '/custom/path',
155
+ }
156
+
157
+ const result = await downloadAndExtractExtension(customOptions)
158
+
159
+ expect(result).toBe(path.join('/custom/path', 'test-extension'))
160
+ })
161
+
162
+ it('should use default .chroma directory when targetDir not provided', async () => {
163
+ const mockedFs = vi.mocked(fs)
164
+ mockedFs.existsSync.mockReturnValue(true)
165
+ mockedFs.readdirSync.mockReturnValue(['manifest.json'] as any)
166
+
167
+ const result = await downloadAndExtractExtension(mockOptions)
168
+
169
+ expect(result).toContain('.chroma')
170
+ expect(result).toContain('test-extension')
171
+ })
172
+ })
173
+ })
@@ -2,7 +2,7 @@ import fs, { createWriteStream } from 'node:fs'
2
2
  import path from 'node:path'
3
3
  import process from 'node:process'
4
4
  import { pipeline } from 'node:stream/promises'
5
- import { Extract } from 'unzipper'
5
+ import AdmZip from 'adm-zip'
6
6
 
7
7
  export interface DownloadExtensionOptions {
8
8
  downloadUrl: string
@@ -10,6 +10,11 @@ export interface DownloadExtensionOptions {
10
10
  targetDir?: string
11
11
  }
12
12
 
13
+ function unzipFile(zipPath: string, destDir: string): void {
14
+ const zip = new AdmZip(zipPath)
15
+ zip.extractAllTo(destDir, true)
16
+ }
17
+
13
18
  export async function downloadAndExtractExtension(options: DownloadExtensionOptions): Promise<string> {
14
19
  const { downloadUrl, extensionName, targetDir } = options
15
20
 
@@ -17,6 +22,7 @@ export async function downloadAndExtractExtension(options: DownloadExtensionOpti
17
22
  const extensionsDir = targetDir || path.resolve(process.cwd(), '.chroma')
18
23
  const extensionDir = path.join(extensionsDir, extensionName)
19
24
  const zipPath = path.join(extensionsDir, `${extensionName}.zip`)
25
+ const tempExtractDir = path.join(extensionsDir, `${extensionName}-temp`)
20
26
 
21
27
  // Create extensions directory if it doesn't exist
22
28
  await fs.promises.mkdir(extensionsDir, { recursive: true })
@@ -42,11 +48,29 @@ export async function downloadAndExtractExtension(options: DownloadExtensionOpti
42
48
 
43
49
  console.log('📦 Extracting extension...')
44
50
 
45
- // Standard zip extraction
46
- await pipeline(
47
- fs.createReadStream(zipPath),
48
- Extract({ path: extensionDir }),
49
- )
51
+ // Extract to temp directory first
52
+ await fs.promises.mkdir(tempExtractDir, { recursive: true })
53
+ unzipFile(zipPath, tempExtractDir)
54
+
55
+ // Check if it's a nested zip (contains another .zip file)
56
+ const files = await fs.promises.readdir(tempExtractDir)
57
+ const nestedZip = files.find(f => f.endsWith('.zip'))
58
+
59
+ if (nestedZip) {
60
+ console.log(`📦 Found nested zip: ${nestedZip}, extracting...`)
61
+ const nestedZipPath = path.join(tempExtractDir, nestedZip)
62
+
63
+ // Extract the nested zip to final location
64
+ await fs.promises.mkdir(extensionDir, { recursive: true })
65
+ unzipFile(nestedZipPath, extensionDir)
66
+
67
+ // Clean up temp directory
68
+ await fs.promises.rm(tempExtractDir, { recursive: true, force: true })
69
+ }
70
+ else {
71
+ // No nested zip, just rename temp to final
72
+ await fs.promises.rename(tempExtractDir, extensionDir)
73
+ }
50
74
 
51
75
  // Clean up ZIP file
52
76
  await fs.promises.unlink(zipPath)
@@ -62,6 +86,9 @@ export async function downloadAndExtractExtension(options: DownloadExtensionOpti
62
86
  if (fs.existsSync(extensionDir)) {
63
87
  await fs.promises.rm(extensionDir, { recursive: true, force: true }).catch(() => {})
64
88
  }
89
+ if (fs.existsSync(tempExtractDir)) {
90
+ await fs.promises.rm(tempExtractDir, { recursive: true, force: true }).catch(() => {})
91
+ }
65
92
 
66
93
  throw new Error(`Failed to download/extract ${extensionName}: ${error instanceof Error ? error.message : String(error)}`)
67
94
  }