Skip to content
Source
Sign inSign up
samwillis/neon-realtime-electric
Open History to see the last commit

import-electric-client.mjs

78 lines2.5 KB

1import { createHash } from 'node:crypto'
2import { readFile, mkdir, writeFile, access } from 'node:fs/promises'
3import path from 'node:path'
4import { fileURLToPath } from 'node:url'
5​
6const root = fileURLToPath(new URL('../', import.meta.url))
7const manifestPath = path.join(root, 'upstream/electric-client.json')
8const manifest = JSON.parse(await readFile(manifestPath, 'utf8'))
9const args = process.argv.slice(2)
10const checking = args.includes('--check')
11const destinationIndex = args.indexOf('--destination')
12const destination = path.resolve(
13 root,
14 destinationIndex === -1 ? 'packages/client' : args[destinationIndex + 1]
16if (!checking) {
17 try {
18 await access(destination)
19 throw new Error(
20 `Refusing to overwrite ${destination}; use a fresh destination`
21 )
22 } catch (error) {
23 if (error.code !== 'ENOENT') throw error
24 }
26​
27let next = 0
28let checked = 0
29await Promise.all(
30 Array.from({ length: 8 }, async () => {
31 while (next < manifest.files.length) {
32 const entry = manifest.files[next++]
33 const target = path.join(destination, entry.path)
34 if (
35 checking &&
36 [
37 ...manifest.workspaceAdaptations,
38 ...(manifest.localModifications ?? []),
39 ].includes(entry.path)
40 )
41 continue
42 const bytes = checking
43 ? await readFile(target)
44 : await download(entry.upstreamPath)
45 const actual = createHash('sha1')
46 .update(`blob ${bytes.length}\0`)
47 .update(bytes)
48 .digest('hex')
49 if (actual !== entry.gitBlob) {
50 throw new Error(`Upstream content mismatch: ${entry.path}`)
51 }
52 if (!checking) {
53 await mkdir(path.dirname(target), { recursive: true })
54 await writeFile(target, bytes)
55 }
56 checked++
57 }
58 })
60console.log(
61 `${checking ? 'Verified' : 'Imported'} ${checked} upstream files at ${manifest.revision}`
63if (checking && manifest.localModifications?.length) {
64 console.log(
65 `Reviewed local source changes (not checked as pristine): ${manifest.localModifications.join(', ')}`
66 )
68​
69async function download(upstreamPath) {
70 const url = `https://raw.githubusercontent.com/electric-sql/electric/${manifest.revision}/${upstreamPath}`
71 for (let attempt = 0; attempt < 3; attempt++) {
72 const response = await fetch(url, { signal: AbortSignal.timeout(30_000) })
73 if (response.ok) return Buffer.from(await response.arrayBuffer())
74 if (response.status < 500 || attempt === 2) {
75 throw new Error(`Import ${upstreamPath}: HTTP ${response.status}`)
76 }
77 }