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

transfer-projects.ts

47 lines3.6 KB

1import { readFile, writeFile } from 'node:fs/promises';
2import { parse } from 'dotenv';
3import { execFileSync } from 'node:child_process';
4import { homedir } from 'node:os';
5import { join } from 'node:path';
6​
7// Moves every Glow project (named glow-* or neon-glow-*) from one Neon org to another, keeping
8// their data, hostnames and Functions. Uses your own Neon CLI login (`neon auth`), because
9// transfers need a person who belongs to both orgs; org API keys only see their own org.
10// Then it creates an API key in the new org and points .env.local, .neon and .local/setup.json
11// at it, so the next `pnpm run deploy` uses the new org. The key is written only to ignored files.
12// Usage: pnpm exec tsx scripts/transfer-projects.ts <from-org-id> <to-org-id> [--yes]
13const [from, to] = process.argv.slice(2).filter(value => !value.startsWith('--'));
14if (!from || !to) throw new Error('Usage: scripts/transfer-projects.ts <from-org-id> <to-org-id> [--yes]');
15// Running the CLI once refreshes its login if it has expired.
16execFileSync(join(import.meta.dirname, '../node_modules/.bin/neon'), ['me', '--output', 'json'], { stdio: 'ignore' });
17const credentials = await readFile(join(homedir(), '.config/neon/credentials.json'), 'utf8').catch(() => readFile(join(homedir(), '.config/neonctl/credentials.json'), 'utf8'));
18const token = JSON.parse(credentials).access_token as string;
19const neon = async (path: string, init: RequestInit = {}) => {
20 const response = await fetch(`https://console.neon.tech/api/v2/${path}`, { ...init, headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' } });
21 const body = await response.json().catch(() => ({}));
22 if (!response.ok) throw new Error(`${path} returned ${response.status}: ${JSON.stringify(body).slice(0, 400)}`);
23 return body;
24};
25const projects: Array<{ id: string; name: string }> = [];
26for (let cursor: string | undefined; ;) {
27 const page = await neon(`projects?org_id=${from}&limit=400${cursor ? `&cursor=${cursor}` : ''}`);
28 projects.push(...page.projects); cursor = page.pagination?.cursor;
29 if (!cursor || !page.projects.length) break;
31const glow = projects.filter(project => /^(neon-)?glow-/.test(project.name));
32console.log(`${glow.length} Glow projects in ${from}:\n${glow.map(project => ` ${project.id} ${project.name}`).join('\n')}`);
33console.log(`Left in place: ${projects.filter(project => !glow.includes(project)).map(project => project.name).join(', ') || 'nothing'}`);
34if (!process.argv.includes('--yes')) { console.log(`\nRe-run with --yes to move them to ${to}.`); process.exit(0); }
35if (glow.length) await neon(`organizations/${from}/projects/transfer`, { method: 'POST', body: JSON.stringify({ destination_org_id: to, project_ids: glow.map(project => project.id) }) });
36console.log(`Moved ${glow.length} projects to ${to}.`);
37const key = await neon(`organizations/${to}/api_keys`, { method: 'POST', body: JSON.stringify({ key_name: 'Neon Glow development fleet' }) });
38if (typeof key.key !== 'string') throw new Error('The new org API key response needs review');
39const env = parse(await readFile('.env.local'));
40env.NEON_ORG_ID = to; env.NEON_API_KEY = key.key;
41await writeFile('.env.local', Object.entries(env).map(([name, value]) => `${name}=${JSON.stringify(value)}`).join('\n') + '\n', { mode: 0o600 });
42for (const file of ['.neon', '.local/setup.json']) {
43 const state = JSON.parse(await readFile(file, 'utf8'));
44 state.orgId = to; if (file === '.local/setup.json') state.apiKey = key;
45 await writeFile(file, JSON.stringify(state, null, file === '.neon' ? 2 : 0), { mode: 0o600 });
47console.log('Created an API key in the new org and saved it to .env.local. Ask Claude to redeploy.');