Extracted from the private caelum0x/scribase monorepo's packages/scribase-js with a fresh, single-commit history (no core history leaks). The npx scribase CLI and the typed /v1 API client, unchanged except: prepublishOnly simplified (the monorepo-only tarball gitleaks gate dropped), repository/homepage/bugs fields added, and one test that cross-checked embedded template strings against the monorepo's templates/ directory removed (nothing it tested changed; that directory isn't shipped here).
256 lines
11 KiB
TypeScript
256 lines
11 KiB
TypeScript
/**
|
|
* Tests for the zero-config Vercel push in `npx scribase init`: link
|
|
* detection, the request (token via fetch, signed-in CLI via spawn with the
|
|
* body on stdin), outcomes that never fail init, and no secret in output.
|
|
*/
|
|
|
|
import { describe, it } from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
|
|
import { parseInitArgs, runInit } from '../src/cli/init.js';
|
|
import type { InitIo } from '../src/cli/init.js';
|
|
import { requestPath, resolveLink, syncVercel, vercelEnvVars, vercelLine } from '../src/cli/vercel.js';
|
|
import type { SpawnOutcome, VercelIo } from '../src/cli/vercel.js';
|
|
|
|
const ROOT = '/work/app';
|
|
const LINK = JSON.stringify({ projectId: 'prj_abc123', orgId: 'team_xyz' });
|
|
const INPUT = {
|
|
organization: 'acme',
|
|
project: 'shop',
|
|
environment: 'production',
|
|
apiUrl: 'https://shop-production.scribase.app/',
|
|
anonKey: 'eyJanon',
|
|
serviceRoleKey: 'eyJservice',
|
|
};
|
|
|
|
interface FetchCall {
|
|
url: string;
|
|
method: string;
|
|
auth: string | null;
|
|
body: unknown;
|
|
}
|
|
|
|
interface SpawnCall {
|
|
command: string;
|
|
args: string[];
|
|
input?: string;
|
|
}
|
|
|
|
function vercelIo(options: {
|
|
files?: Record<string, string>;
|
|
env?: Record<string, string>;
|
|
respond?: (call: FetchCall) => { status: number; body: unknown };
|
|
spawn?: (call: SpawnCall) => SpawnOutcome;
|
|
}) {
|
|
const fetches: FetchCall[] = [];
|
|
const spawns: SpawnCall[] = [];
|
|
const files = options.files ?? {};
|
|
const io: VercelIo = {
|
|
cwd: ROOT,
|
|
env: options.env ?? {},
|
|
fetch: (async (url: string | URL | Request, init?: RequestInit) => {
|
|
const call: FetchCall = {
|
|
url: String(url),
|
|
method: init?.method ?? 'GET',
|
|
auth: new Headers(init?.headers).get('authorization'),
|
|
body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,
|
|
};
|
|
fetches.push(call);
|
|
const answer = options.respond?.(call) ?? { status: 201, body: { created: [], failed: [] } };
|
|
return new Response(JSON.stringify(answer.body), { status: answer.status });
|
|
}) as typeof fetch,
|
|
readFile: (path) => files[path] ?? null,
|
|
spawn: async (command, args, spawnOptions) => {
|
|
const call: SpawnCall = { command, args, ...(spawnOptions.input !== undefined ? { input: spawnOptions.input } : {}) };
|
|
spawns.push(call);
|
|
return options.spawn?.(call) ?? { code: 1, stdout: '', stderr: 'not signed in' };
|
|
},
|
|
};
|
|
return { io, fetches, spawns };
|
|
}
|
|
|
|
describe('Vercel link detection', () => {
|
|
it('reads .vercel/project.json, prefers VERCEL_PROJECT_ID, and is null when unlinked', () => {
|
|
const readFile = (path: string) => (path === `${ROOT}/.vercel/project.json` ? LINK : null);
|
|
assert.deepEqual(resolveLink({ cwd: ROOT, env: {}, readFile }), { projectId: 'prj_abc123', orgId: 'team_xyz' });
|
|
assert.deepEqual(resolveLink({ cwd: ROOT, env: { VERCEL_PROJECT_ID: 'prj_env' }, readFile }), { projectId: 'prj_env' });
|
|
assert.equal(resolveLink({ cwd: ROOT, env: {}, readFile: () => null }), null);
|
|
assert.throws(() => resolveLink({ cwd: ROOT, env: {}, readFile: () => '{"projectId":"a b"}' }), /projectId/);
|
|
assert.throws(() => resolveLink({ cwd: ROOT, env: { VERCEL_PROJECT_ID: '../x' }, readFile }), /VERCEL_PROJECT_ID/);
|
|
});
|
|
|
|
it('sends teamId only for team projects', () => {
|
|
assert.equal(requestPath({ projectId: 'prj_1', orgId: 'team_2' }), '/v10/projects/prj_1/env?upsert=true&teamId=team_2');
|
|
assert.equal(requestPath({ projectId: 'prj_1', orgId: 'user_2' }), '/v10/projects/prj_1/env?upsert=true');
|
|
});
|
|
});
|
|
|
|
describe('Vercel variables', () => {
|
|
it('matches the console names; the service key is sensitive, server-only and not on development', () => {
|
|
const vars = vercelEnvVars(INPUT);
|
|
assert.deepEqual(
|
|
vars.map((v) => v.key),
|
|
[
|
|
'NEXT_PUBLIC_SUPABASE_URL',
|
|
'NEXT_PUBLIC_SUPABASE_ANON_KEY',
|
|
'NEXT_PUBLIC_SCRIBASE_URL',
|
|
'NEXT_PUBLIC_SCRIBASE_ANON_KEY',
|
|
'SCRIBASE_ORG',
|
|
'SCRIBASE_PROJECT',
|
|
'SCRIBASE_ENV',
|
|
'SUPABASE_SERVICE_ROLE_KEY',
|
|
'SCRIBASE_SERVICE_ROLE_KEY',
|
|
],
|
|
);
|
|
assert.equal(vars[0]?.value, 'https://shop-production.scribase.app');
|
|
for (const v of vars.filter((item) => item.value === 'eyJservice')) {
|
|
assert.equal(v.type, 'sensitive');
|
|
assert.ok(!v.key.startsWith('NEXT_PUBLIC_'));
|
|
assert.deepEqual(v.target, ['preview', 'production']);
|
|
}
|
|
assert.equal(vercelEnvVars({ ...INPUT, serviceRoleKey: null }).length, 7);
|
|
});
|
|
});
|
|
|
|
describe('syncVercel', () => {
|
|
it('pushes with VERCEL_TOKEN in one upsert request', async () => {
|
|
const { io, fetches, spawns } = vercelIo({
|
|
files: { [`${ROOT}/.vercel/project.json`]: LINK },
|
|
env: { VERCEL_TOKEN: 'vt_secret' },
|
|
});
|
|
const result = await syncVercel(io, INPUT);
|
|
assert.equal(result.status, 'updated');
|
|
assert.deepEqual(result.targets, ['development', 'preview', 'production']);
|
|
assert.equal(result.via, 'VERCEL_TOKEN');
|
|
assert.equal(fetches.length, 1);
|
|
assert.equal(fetches[0]?.url, 'https://api.vercel.com/v10/projects/prj_abc123/env?upsert=true&teamId=team_xyz');
|
|
assert.equal(fetches[0]?.method, 'POST');
|
|
assert.equal(fetches[0]?.auth, 'Bearer vt_secret');
|
|
assert.equal((fetches[0]?.body as unknown[]).length, 9);
|
|
assert.equal(spawns.length, 0, 'no CLI with a token');
|
|
assert.equal(vercelLine(result), 'Vercel env updated for development, preview, production');
|
|
assert.ok(!JSON.stringify(result).includes('vt_secret'));
|
|
});
|
|
|
|
it('uses the signed-in vercel CLI without a token, body on stdin, never argv', async () => {
|
|
const { io, fetches, spawns } = vercelIo({
|
|
files: { [`${ROOT}/.vercel/project.json`]: LINK },
|
|
spawn: (call) => ({ code: 0, stdout: call.args[0] === 'api' ? '{"created":[],"failed":[]}' : 'me', stderr: '' }),
|
|
});
|
|
const result = await syncVercel(io, INPUT);
|
|
assert.equal(result.status, 'updated');
|
|
assert.equal(result.via, 'vercel CLI');
|
|
assert.equal(fetches.length, 0);
|
|
assert.deepEqual(spawns[0]?.args, ['whoami', '--non-interactive']);
|
|
const api = spawns[1];
|
|
assert.deepEqual(api?.args.slice(0, 7), ['api', '/v10/projects/prj_abc123/env?upsert=true&teamId=team_xyz', '-X', 'POST', '--input', '-', '--raw']);
|
|
assert.ok(!api?.args.some((arg) => arg.includes('eyJ')), 'no key in argv');
|
|
assert.match(api?.input ?? '', /eyJservice/);
|
|
});
|
|
|
|
it('skips when not linked or without credentials, and reports Vercel errors without throwing', async () => {
|
|
const unlinked = await syncVercel(vercelIo({ env: { VERCEL_TOKEN: 'vt' } }).io, INPUT);
|
|
assert.deepEqual(unlinked, { status: 'not_linked', targets: [] });
|
|
assert.equal(vercelLine(unlinked), 'Not linked to Vercel — skipped');
|
|
|
|
const noCreds = await syncVercel(vercelIo({ files: { [`${ROOT}/.vercel/project.json`]: LINK } }).io, INPUT);
|
|
assert.equal(noCreds.status, 'no_credentials');
|
|
assert.equal(vercelLine(noCreds), 'No Vercel credentials — skipped');
|
|
|
|
const refused = await syncVercel(
|
|
vercelIo({
|
|
files: { [`${ROOT}/.vercel/project.json`]: LINK },
|
|
env: { VERCEL_TOKEN: 'vt_secret' },
|
|
respond: () => ({ status: 403, body: { error: { code: 'forbidden', message: 'Not authorized' } } }),
|
|
}).io,
|
|
INPUT,
|
|
);
|
|
assert.equal(refused.status, 'failed');
|
|
assert.match(refused.error ?? '', /HTTP 403: Not authorized/);
|
|
assert.ok(!(refused.error ?? '').includes('vt_secret'));
|
|
|
|
const partial = await syncVercel(
|
|
vercelIo({
|
|
files: { [`${ROOT}/.vercel/project.json`]: LINK },
|
|
env: { VERCEL_TOKEN: 'vt' },
|
|
respond: () => ({ status: 201, body: { created: [], failed: [{ error: { message: 'bad key' } }] } }),
|
|
}).io,
|
|
INPUT,
|
|
);
|
|
assert.equal(partial.status, 'failed');
|
|
assert.match(partial.error ?? '', /bad key/);
|
|
|
|
const broken = await syncVercel(vercelIo({ files: { [`${ROOT}/.vercel/project.json`]: 'nope' }, env: { VERCEL_TOKEN: 'vt' } }).io, INPUT);
|
|
assert.equal(broken.status, 'failed');
|
|
|
|
const badToken = await syncVercel(vercelIo({ files: { [`${ROOT}/.vercel/project.json`]: LINK }, env: { VERCEL_TOKEN: 'a\nb' } }).io, INPUT);
|
|
assert.equal(badToken.status, 'failed');
|
|
});
|
|
});
|
|
|
|
describe('init pushes to a linked Vercel project', () => {
|
|
const KEYS = { api_url: 'https://shop-production.scribase.app', anon_key: 'eyJanon', service_role_key: 'eyJservice' };
|
|
|
|
function initIo(files: Record<string, string>, env: Record<string, string>, vercelStatus = 201) {
|
|
const vercelCalls: string[] = [];
|
|
const io: InitIo = {
|
|
cwd: ROOT,
|
|
env,
|
|
fetch: (async (url: string | URL | Request) => {
|
|
const target = new URL(String(url));
|
|
if (target.hostname === 'api.vercel.com') {
|
|
vercelCalls.push(`${target.pathname}${target.search}`);
|
|
return new Response(JSON.stringify(vercelStatus === 201 ? { failed: [] } : { error: { message: 'nope' } }), { status: vercelStatus });
|
|
}
|
|
const path = target.pathname;
|
|
if (path === '/v1/organizations') return Response.json({ items: [{ organization_id: 'acme' }] });
|
|
if (path.endsWith('/environments/production')) return Response.json({ phase: 'ready' });
|
|
if (path.endsWith('/api-keys')) return Response.json(KEYS);
|
|
return Response.json({}, { status: path === '/v1/environments' ? 202 : 200 });
|
|
}) as typeof fetch,
|
|
readFile: (path) => files[path] ?? null,
|
|
writeFile: (path, contents) => {
|
|
files[path] = contents;
|
|
},
|
|
exists: (path) => path in files,
|
|
run: () => ({ ok: true, output: '' }),
|
|
sleep: async () => {},
|
|
log: () => {},
|
|
credentials: () => ({}),
|
|
};
|
|
return { io, vercelCalls };
|
|
}
|
|
|
|
const PKG = JSON.stringify({ dependencies: { next: '15', '@supabase/supabase-js': '2' } });
|
|
|
|
it('after writing .env, updates Vercel and reports {status, targets}', async () => {
|
|
const files = { [`${ROOT}/package.json`]: PKG, [`${ROOT}/.vercel/project.json`]: LINK };
|
|
const { io, vercelCalls } = initIo(files, { SCRIBASE_ACCESS_TOKEN: 'scb_pat', VERCEL_TOKEN: 'vt_secret' });
|
|
const result = await runInit(parseInitArgs(['--yes', '--json', '--name', 'shop']), io);
|
|
assert.deepEqual(result.vercel, { status: 'updated', targets: ['development', 'preview', 'production'], project_id: 'prj_abc123' });
|
|
assert.deepEqual(vercelCalls, ['/v10/projects/prj_abc123/env?upsert=true&teamId=team_xyz']);
|
|
assert.ok(files[`${ROOT}/.env.local`], 'env file written');
|
|
assert.ok(!JSON.stringify(result).includes('vt_secret'));
|
|
});
|
|
|
|
it('never fails init when Vercel refuses, and --no-vercel skips it', async () => {
|
|
const files = { [`${ROOT}/package.json`]: PKG, [`${ROOT}/.vercel/project.json`]: LINK };
|
|
const refused = initIo({ ...files }, { SCRIBASE_ACCESS_TOKEN: 'scb_pat', VERCEL_TOKEN: 'vt' }, 403);
|
|
const result = await runInit(parseInitArgs(['--yes', '--name', 'shop']), refused.io);
|
|
assert.equal(result.ok, true);
|
|
assert.equal(result.vercel.status, 'failed');
|
|
assert.deepEqual(result.vercel.targets, []);
|
|
|
|
const off = initIo({ ...files }, { SCRIBASE_ACCESS_TOKEN: 'scb_pat', VERCEL_TOKEN: 'vt' });
|
|
const skipped = await runInit(parseInitArgs(['--yes', '--no-vercel', '--name', 'shop']), off.io);
|
|
assert.equal(skipped.vercel.status, 'disabled');
|
|
assert.equal(off.vercelCalls.length, 0);
|
|
});
|
|
|
|
it('reports not_linked for an unlinked folder', async () => {
|
|
const { io } = initIo({ [`${ROOT}/package.json`]: PKG }, { SCRIBASE_ACCESS_TOKEN: 'scb_pat' });
|
|
const result = await runInit(parseInitArgs(['--yes', '--name', 'shop']), io);
|
|
assert.deepEqual(result.vercel, { status: 'not_linked', targets: [] });
|
|
});
|
|
});
|