74 lines
2.5 KiB
TypeScript
74 lines
2.5 KiB
TypeScript
/**
|
|
* Uploads the SVG assets of a generated sheet seed into the Storage bucket
|
|
* anatomical-sheet-assets, content-addressed (<sha256>.svg).
|
|
*
|
|
* Operator tool: needs the service key, which never ships to the browser.
|
|
* Reads SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY from the environment
|
|
* (local stack: `pnpm supabase status` prints them). Idempotent: an object
|
|
* whose sha256 already exists is skipped, a mismatching upload is refused.
|
|
*
|
|
* pnpm assets:upload supabase/seed/anatomical-sheets/equine/v1
|
|
*/
|
|
import { createHash } from 'node:crypto'
|
|
import { readFile } from 'node:fs/promises'
|
|
import { join, resolve } from 'node:path'
|
|
import { createClient } from '@supabase/supabase-js'
|
|
|
|
const BUCKET = 'anatomical-sheet-assets'
|
|
|
|
interface AssetEntry {
|
|
file: string
|
|
sha256: string
|
|
byte_size: number
|
|
}
|
|
|
|
function requireEnv(name: string): string {
|
|
const value = process.env[name]
|
|
if (!value) throw new Error(`${name} is required`)
|
|
return value
|
|
}
|
|
|
|
async function readManifest(dir: string): Promise<AssetEntry[]> {
|
|
const raw = await readFile(join(dir, 'assets.json'), 'utf8')
|
|
return JSON.parse(raw) as AssetEntry[]
|
|
}
|
|
|
|
/** The bytes on disk must still match what the seed recorded. */
|
|
async function readVerified(dir: string, entry: AssetEntry): Promise<Buffer> {
|
|
const bytes = await readFile(join(dir, 'assets', entry.file))
|
|
const sha256 = createHash('sha256').update(bytes).digest('hex')
|
|
if (sha256 !== entry.sha256 || bytes.length !== entry.byte_size) {
|
|
throw new Error(`${entry.file}: bytes differ from assets.json`)
|
|
}
|
|
return bytes
|
|
}
|
|
|
|
async function main(): Promise<void> {
|
|
// pnpm runs package scripts inside the package: resolve from the caller's directory.
|
|
const dir = resolve(
|
|
process.env.INIT_CWD ?? process.cwd(),
|
|
process.argv[2] ?? '.',
|
|
)
|
|
const client = createClient(
|
|
requireEnv('SUPABASE_URL'),
|
|
requireEnv('SUPABASE_SERVICE_ROLE_KEY'),
|
|
{ auth: { persistSession: false } },
|
|
)
|
|
for (const entry of await readManifest(dir)) {
|
|
const key = `${entry.sha256}.svg`
|
|
const bytes = await readVerified(dir, entry)
|
|
const { error } = await client.storage
|
|
.from(BUCKET)
|
|
.upload(key, bytes, { contentType: 'image/svg+xml', upsert: false })
|
|
if (error && !/already exists/i.test(error.message)) {
|
|
throw new Error(`${key}: ${error.message}`)
|
|
}
|
|
console.log(`${error ? 'kept' : 'uploaded'} ${key} (${entry.file})`)
|
|
}
|
|
}
|
|
|
|
main().catch((error: unknown) => {
|
|
console.error(error instanceof Error ? error.message : error)
|
|
process.exit(1)
|
|
})
|