0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2025-04-07 23:41:43 -05:00

add better token error logging

This commit is contained in:
Fred K. Schott 2024-02-07 19:59:56 -08:00
parent 39e29426aa
commit 4c4ae2f470
7 changed files with 32 additions and 31 deletions

View file

@ -4,12 +4,13 @@ import prompts from 'prompts';
import type { Arguments } from 'yargs-parser';
import { PROJECT_ID_FILE, getSessionIdFromFile } from '../../../tokens.js';
import { getAstroStudioUrl } from '../../../utils.js';
import { MISSING_SESSION_ID_ERROR } from '../../../errors.js';
export async function cmd({ flags }: { config: AstroConfig; flags: Arguments }) {
export async function cmd({ }: { config: AstroConfig; flags: Arguments }) {
const linkUrl = new URL(getAstroStudioUrl() + '/auth/cli/link');
const sessionToken = await getSessionIdFromFile();
if (!sessionToken) {
console.error('You must be logged in to link a project.');
console.error(MISSING_SESSION_ID_ERROR);
process.exit(1);
}

View file

@ -5,9 +5,8 @@ import { drizzle } from 'drizzle-orm/sqlite-proxy';
import { red } from 'kleur/colors';
import prompts from 'prompts';
import type { Arguments } from 'yargs-parser';
import { APP_TOKEN_ERROR } from '../../../errors.js';
import { setupDbTables } from '../../../queries.js';
import { getManagedAppToken } from '../../../tokens.js';
import { getManagedAppTokenOrExit } from '../../../tokens.js';
import type { AstroConfigWithDB, DBSnapshot } from '../../../types.js';
import { getRemoteDatabaseUrl } from '../../../utils.js';
import { getMigrationQueries } from '../../migration-queries.js';
@ -25,6 +24,7 @@ const { diff } = deepDiff;
export async function cmd({ config, flags }: { config: AstroConfig; flags: Arguments }) {
const isSeedData = flags.seed;
const isDryRun = flags.dryRun;
const appToken = await getManagedAppTokenOrExit(flags.token);
const currentSnapshot = createCurrentSnapshot(config);
const allMigrationFiles = await getMigrations();
if (allMigrationFiles.length === 0) {
@ -40,12 +40,6 @@ export async function cmd({ config, flags }: { config: AstroConfig; flags: Argum
process.exit(1);
}
const appToken = await getManagedAppToken(flags.token);
if (!appToken) {
console.error(APP_TOKEN_ERROR);
process.exit(1);
}
// get all migrations from the filesystem
const allLocalMigrations = await getMigrations();
const { data: missingMigrations } = await prepareMigrateQuery({

View file

@ -2,17 +2,12 @@ import type { AstroConfig } from 'astro';
import { sql } from 'drizzle-orm';
import type { Arguments } from 'yargs-parser';
import { createRemoteDatabaseClient } from '../../../../runtime/db-client.js';
import { APP_TOKEN_ERROR } from '../../../errors.js';
import { getManagedAppToken } from '../../../tokens.js';
import { getManagedAppTokenOrExit } from '../../../tokens.js';
import { getRemoteDatabaseUrl } from '../../../utils.js';
export async function cmd({ flags }: { config: AstroConfig; flags: Arguments }) {
const query = flags.query;
const appToken = await getManagedAppToken(flags.token);
if (!appToken) {
console.error(APP_TOKEN_ERROR);
process.exit(1);
}
const appToken = await getManagedAppTokenOrExit(flags.token);
const db = createRemoteDatabaseClient(appToken.token, getRemoteDatabaseUrl());
// Temporary: create the migration table just in case it doesn't exist
const result = await db.run(sql.raw(query));

View file

@ -60,7 +60,7 @@ Usage:
astro db login Authenticate your machine with Astro Studio
astro db logout End your authenticated session with Astro Studio
astro db link Link an Astro Studio project to this directory
astro db link Link this directory to an Astro Studio project
astro db sync Creates snapshot based on your schema
astro db push Pushes migrations to Astro Studio

View file

@ -1,8 +1,12 @@
import { cyan, bold, red } from 'kleur/colors';
export const APP_TOKEN_ERROR = `${red(
'⚠️ App token invalid or expired.'
)} Please generate a new one from your the Studio dashboard under project settings.`;
export const MISSING_SESSION_ID_ERROR = `${red(
'⚠️ Login required.'
)} Run ${bold('astro db login')} to authenticate with Astro Studio.`;
export const MISSING_PROJECT_ID_ERROR = `${red(
'⚠️ Directory not linked.'
)} Run ${bold('astro db link')} to link this directory to an Astro Studio project.`;
export const STUDIO_CONFIG_MISSING_WRITABLE_COLLECTIONS_ERROR = (collectionName: string) =>
red(`⚠️ Writable collection ${bold(collectionName)} requires Astro Studio.`) +

View file

@ -7,8 +7,8 @@ import { mkdir, rm, writeFile } from 'fs/promises';
import { DB_PATH } from '../consts.js';
import { createLocalDatabaseClient } from '../../runtime/db-client.js';
import { astroConfigWithDbSchema } from '../types.js';
import { getAstroStudioEnv, type VitePlugin } from '../utils.js';
import { APP_TOKEN_ERROR, STUDIO_CONFIG_MISSING_WRITABLE_COLLECTIONS_ERROR } from '../errors.js';
import { type VitePlugin } from '../utils.js';
import { STUDIO_CONFIG_MISSING_WRITABLE_COLLECTIONS_ERROR } from '../errors.js';
import { errorMap } from './error-map.js';
import { dirname } from 'path';
import { fileURLToPath } from 'url';
@ -16,9 +16,11 @@ import { blue, yellow } from 'kleur/colors';
import { fileURLIntegration } from './file-url.js';
import { setupDbTables } from '../queries.js';
import { collectionToTable } from '../../runtime/index.js';
import { getManagedAppTokenOrExit, type ManagedAppToken } from '../tokens.js';
function astroDBIntegration(): AstroIntegration {
let connectedToRemote = false;
let appToken: ManagedAppToken | undefined;
return {
name: 'astro:db',
hooks: {
@ -42,16 +44,12 @@ function astroDBIntegration(): AstroIntegration {
let dbPlugin: VitePlugin;
if (studio && command === 'build') {
const appToken = getAstroStudioEnv().ASTRO_STUDIO_APP_TOKEN;
if (!appToken) {
logger.error(APP_TOKEN_ERROR);
process.exit(1);
}
appToken = await getManagedAppTokenOrExit();
connectedToRemote = true;
dbPlugin = vitePluginDb({
connectToStudio: true,
collections,
appToken,
appToken: appToken.token,
root: config.root,
});
} else {
@ -118,6 +116,9 @@ function astroDBIntegration(): AstroIntegration {
'astro:build:start': async ({ logger }) => {
logger.info('database: ' + (connectedToRemote ? yellow('remote') : blue('local database.')));
},
'astro:build:done': async ({ }) => {
await appToken?.destroy();
},
},
};
}

View file

@ -3,6 +3,7 @@ import { homedir } from 'node:os';
import { join } from 'node:path';
import { pathToFileURL } from 'node:url';
import { getAstroStudioEnv, getAstroStudioUrl } from './utils.js';
import { MISSING_PROJECT_ID_ERROR, MISSING_SESSION_ID_ERROR } from './errors.js';
export const SESSION_LOGIN_FILE = pathToFileURL(join(homedir(), '.astro', 'session-token'));
export const PROJECT_ID_FILE = pathToFileURL(join(process.cwd(), '.astro', 'link'));
@ -117,7 +118,7 @@ export async function getSessionIdFromFile() {
}
}
export async function getManagedAppToken(token?: string): Promise<ManagedAppToken | undefined> {
export async function getManagedAppTokenOrExit(token?: string): Promise<ManagedAppToken> {
if (token) {
return new ManagedLocalAppToken(token);
}
@ -126,9 +127,14 @@ export async function getManagedAppToken(token?: string): Promise<ManagedAppToke
return new ManagedLocalAppToken(ASTRO_STUDIO_APP_TOKEN);
}
const sessionToken = await getSessionIdFromFile();
if (!sessionToken) {
console.error(MISSING_SESSION_ID_ERROR);
process.exit(1);
}
const projectId = await getProjectIdFromFile();
if (!sessionToken || !projectId) {
return undefined;
console.error(MISSING_PROJECT_ID_ERROR);
process.exit(1);
}
return ManagedRemoteAppToken.create(sessionToken, projectId);
}