8000 chore: rework `content` updates by AdrianGonz97 · Pull Request #75 · sveltejs/cli · GitHub
[go: up one dir, main page]

Skip to content

chore: rework content updates #75

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 20 commits into from
Oct 11, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
update script adders
  • Loading branch information
benmccann committed Oct 10, 2024
commit 56d57f44f12d0a9c05621bc8c501ebebbd5f9aff
11 changes: 8 additions & 3 deletions packages/adders/common.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { imports, exports, common, variables, functions } from '@svelte-cli/core/js';
import { Walker, type AstKinds, type AstTypes, type ScriptFileEditor } from '@svelte-cli/core';
import { Walker, type AstKinds, type AstTypes, type TextFileEditor } from '@svelte-cli/core';
import type { Question } from '@svelte-cli/core/internal';
import { parseScript } from '@svelte-cli/core/parsers';

export function createPrinter(...conditions: boolean[]) {
const printers = conditions.map((condition) => {
Expand All @@ -9,7 +10,9 @@ export function createPrinter(...conditions: boolean[]) {
return printers;
}

export function addEslintConfigPrettier({ ast }: ScriptFileEditor<Record<string, Question>>) {
export function addEslintConfigPrettier({ content }: TextFileEditor<Record<string, Question>>) {
const { ast, generateCode } = parseScript(content);

// if a default import for `eslint-plugin-svelte` already exists, then we'll use their specifier's name instead
const importNodes = ast.body.filter((n) => n.type === 'ImportDeclaration');
const sveltePluginImport = importNodes.find(
Expand All @@ -33,7 +36,7 @@ export function addEslintConfigPrettier({ ast }: ScriptFileEditor<Record<string,
const fallbackConfig = common.expressionFromString('[]');
const defaultExport = exports.defaultExport(ast, fallbackConfig);
const eslintConfig = defaultExport.value;
if (eslintConfig.type !== 'ArrayExpression' && eslintConfig.type !== 'CallExpression') return;
if (eslintConfig.type !== 'ArrayExpression' && eslintConfig.type !== 'CallExpression') return content;

const prettier = common.expressionFromString('prettier');
const sveltePrettierConfig = common.expressionFromString(
Expand Down Expand Up @@ -65,6 +68,8 @@ export function addEslintConfigPrettier({ ast }: ScriptFileEditor<Record<string,
// append to the end as a fallback
elements.push(...nodesToInsert);
}

return generateCode();
}

export function addGlobalAppInterface(
Expand Down
26 changes: 18 additions & 8 deletions packages/adders/drizzle/config/adder.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { options as availableOptions } from './options.ts';
import { common, exports, functions, imports, object, variables } from '@svelte-cli/core/js';
import { defineAdderConfig, dedent, type TextFileEditor } from '@svelte-cli/core';
import { parseScript } from '@svelte-cli/core/parsers';

const PORTS = {
mysql: '3306',
Expand Down Expand Up @@ -150,8 +151,9 @@ export const adder = defineAdderConfig({
},
{
name: ({ typescript }) => `drizzle.config.${typescript ? 'ts' : 'js'}`,
contentType: 'script',
content: ({ options, ast, typescript }) => {
content: ({ options, content, typescript }) => {
const { ast, generateCode } = parseScript(content);

imports.addNamed(ast, 'drizzle-kit', { defineConfig: 'defineConfig' });

const envCheckStatement = common.statementFromString(
Expand All @@ -161,10 +163,10 @@ export const adder = defineAdderConfig({

const fallback = common.expressionFromString('defineConfig({})');
const { value: exportDefault } = exports.defaultExport(ast, fallback);
if (exportDefault.type !== 'CallExpression') return;
if (exportDefault.type !== 'CallExpression') return content;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

there were some places like this where I had to do return content, but I wonder if it wouldn't be better to allow undefined in the return type so that we could do a simple return; to skip editing the file

Copy link
Member Author
@AdrianGonz97 AdrianGonz97 Oct 11, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sure, i think we can do that. i believe we (currently) could accomplish the same effect by returning an empty string as well

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

on second thought, is this really all that bad? i feel like allowing undefined to be returned could lead to a lot of fuckups (i.e. people forgetting to return the content after manipulation)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

true. it did save me from that a few times. I suppose we can always make that change in the future. Once we have tests it should provide some more protection


const objExpression = exportDefault.arguments?.[0];
if (!objExpression || objExpression.type !== 'ObjectExpression') return;
if (!objExpression || objExpression.type !== 'ObjectExpression') return content;

const driver = options.sqlite === 'turso' ? common.createLiteral('turso') : undefined;
const authToken =
Expand All @@ -190,13 +192,16 @@ export const adder = defineAdderConfig({
// The `driver` property is only required for _some_ sqlite DBs.
// We'll need to remove it if it's anything but sqlite
if (options.database !== 'sqlite') object.removeProperty(objExpression, 'driver');

return generateCode();
}
},
{
name: ({ kit, typescript }) =>
`${kit?.libDirectory}/server/db/schema.${typescript ? 'ts' : 'js'}`,
contentType: 'script',
content: ({ ast, options }) => {
content: ({ content, options }) => {
const { ast, generateCode } = parseScript(content);

let userSchemaExpression;
if (options.database === 'sqlite') {
imports.addNamed(ast, 'drizzle-orm/sqlite-core', {
Expand Down Expand Up @@ -240,13 +245,16 @@ export const adder = defineAdderConfig({
if (!userSchemaExpression) throw new Error('unreachable state...');
const userIdentifier = variables.declaration(ast, 'const', 'user', userSchemaExpression);
exports.namedExport(ast, 'user', userIdentifier);

return generateCode();
}
},
{
name: ({ kit, typescript }) =>
`${kit?.libDirectory}/server/db/index.${typescript ? 'ts' : 'js'}`,
contentType: 'script',
content: ({ ast, options }) => {
content: ({ content, options }) => {
const { ast, generateCode } = parseScript(content);

imports.addNamed(ast, '$env/dynamic/private', { env: 'env' });

// env var checks
Expand Down Expand Up @@ -320,6 +328,8 @@ export const adder = defineAdderConfig({
const drizzleCall = functions.callByIdentifier('drizzle', ['client']);
const db = variables.declaration(ast, 'const', 'db', drizzleCall);
exports.namedExport(ast, 'db', db);

return generateCode();
}
}
],
Expand Down
11 changes: 7 additions & 4 deletions packages/adders/eslint/config/adder.ts
< F438 tr data-hunk="c1a7c3b5d4cc6126dc3fbb9c522088e8fe78d7cfae60bbd53ec809ed51819459" class="show-top-border">
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { options } from './options.ts';
import { addEslintConfigPrettier } from '../../common.ts';
import { defineAdderConfig, log, type AstKinds, type AstTypes } from '@svelte-cli/core';
import { array, common, exports, functions, imports, object } from '@svelte-cli/core/js';
import { parseScript } from '@svelte-cli/core/parsers';

export const adder = defineAdderConfig({
metadata: {
Expand Down Expand Up @@ -62,8 +63,9 @@ export const adder = defineAdderConfig({
},
{
name: () => 'eslint.config.js',
contentType: 'script',
content: ({ ast, typescript }) => {
content: ({ content, typescript }) => {
const { ast, generateCode } = parseScript(content);

const eslintConfigs: Array<
AstKinds.ExpressionKind | AstTypes.SpreadElement | AstTypes.ObjectExpression
> = [];
Expand Down Expand Up @@ -124,7 +126,7 @@ export const adder = defineAdderConfig({
// if it's not the config we created, then we'll leave it alone and exit out
if (defaultExport.value !== exportExpression) {
log.warn('An eslint config is already defined. Skipping initialization.');
return;
return content;
}

// type annotate config
Expand All @@ -136,11 +138,12 @@ export const adder = defineAdderConfig({
imports.addDefault(ast, 'globals', 'globals');
imports.addDefault(ast, 'eslint-plugin-svelte', 'svelte');
imports.addDefault(ast, '@eslint/js', 'js');

return generateCode();
}
},
{
name: () => 'eslint.config.js',
contentType: 'script',
condition: ({ prettier }) => prettier,
content: addEslintConfigPrettier
}
Expand Down
31 changes: 18 additions & 13 deletions packages/adders/lucia/config/adder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { common, exports, imports, variables, object, functions } from '@svelte-
// eslint-disable-next-line no-duplicate-imports
import type { AstTypes } from '@svelte-cli/core/js';
import { addHooksHandle, addGlobalAppInterface, hasTypeProp } from '../../common.ts';
import { parseScript } from '@svelte-cli/core/parsers';

const LUCIA_ADAPTER = {
mysql: 'DrizzleMySQLAdapter',
Expand Down Expand Up @@ -51,8 +52,8 @@ export const adder = defineAdderConfig({
files: [
{
name: ({ typescript }) => `drizzle.config.${typescript ? 'ts' : 'js'}`,
contentType: 'script',
content: ({ ast }) => {
content: ({ content }) => {
const { ast, generateCode } = parseScript(content);
const isProp = (name: string, node: AstTypes.ObjectProperty) =>
node.key.type === 'Identifier' && node.key.name === name;

Expand All @@ -74,12 +75,13 @@ export const adder = defineAdderConfig({
if (!schemaPath) {
throw new Error('Failed to find schema path in your `drizzle.config.[js|ts]` file');
}
return generateCode();
}
},
{
name: () => schemaPath,
contentType: 'script',
content: ({ ast, options }) => {
content: ({ content, options }) => {
const { ast, generateCode } = parseScript(content);
const createTable = (name: string) => functions.call(TABLE_TYPE[drizzleDialect], [name]);

const userDecl = variables.declaration(ast, 'const', 'user', createTable('user'));
Expand Down Expand Up @@ -186,12 +188,13 @@ export const adder = defineAdderConfig({
)
});
}
return generateCode();
}
},
{
name: ({ kit, typescript }) => `${kit?.libDirectory}/server/auth.${typescript ? 'ts' : 'js'}`,
contentType: 'script',
content: ({ ast, source, typescript, options }) => {
content: ({ content, typescript, options }) => {
const { ast, generateCode } = parseScript(content);
const adapter = LUCIA_ADAPTER[drizzleDialect];

imports.addNamed(ast, '$lib/server/db/schema.js', { user: 'user', session: 'session' });
Expand Down Expand Up @@ -220,7 +223,7 @@ export const adder = defineAdderConfig({
exports.namedExport(ast, 'lucia', luciaDecl);

// module declaration
if (typescript && !/declare module ["']lucia["']/.test(source)) {
if (typescript && !/declare module ["']lucia["']/.test(content)) {
const moduleDecl = common.statementFromString(`
declare module 'lucia' {
interface Register {
Expand All @@ -232,15 +235,16 @@ export const adder = defineAdderConfig({
}`);
common.addStatement(ast, moduleDecl);
}
return generateCode();
}
},
{
name: () => 'src/app.d.ts',
condition: ({ typescript }) => typescript,
contentType: 'script',
content: ({ ast }) => {
const locals = addGlobalAppInterface(ast, 'Locals');
content: ({ content }) => {
const { ast, generateCode } = parseScript(content);

const locals = addGlobalAppInterface(ast, 'Locals');
if (!locals) {
throw new Error('Failed detecting `locals` interface in `src/app.d.ts`');
}
Expand All @@ -254,15 +258,16 @@ export const adder = defineAdderConfig({
if (!session) {
locals.body.body.push(createLuciaType('session'));
}
return generateCode();
}
},
{
name: ({ typescript }) => `src/hooks.server.${typescript ? 'ts' : 'js'}`,
contentType: 'script',
content: ({ ast, typescript }) => {
content: ({ content, typescript }) => {
const { ast, generateCode } = parseScript(content);
imports.addNamed(ast, '$lib/server/auth.js', { lucia: 'lucia' });

addHooksHandle(ast, typescript, 'auth', getAuthHandleContent());
return generateCode();
}
},
// DEMO
Expand Down
8 changes: 6 additions & 2 deletions packages/adders/mdsvex/config/adder.ts
10000
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { options } from './options.ts';
import { defineAdderConfig } from '@svelte-cli/core';
import { array, exports, functions, imports, object } from '@svelte-cli/core/js';
import { parseScript } from '@svelte-cli/core/parsers';

export const adder = defineAdderConfig({
metadata: {
Expand All @@ -19,8 +20,9 @@ export const adder = defineAdderConfig({
files: [
{
name: () => 'svelte.config.js',
contentType: 'script',
content: ({ ast }) => {
content: ({ content }) => {
const { ast, generateCode } = parseScript(content);

imports.addNamed(ast, 'mdsvex', { mdsvex: 'mdsvex' });

const { value: exportDefault } = exports.defaultExport(ast, object.createEmpty());
Expand All @@ -43,6 +45,8 @@ export const adder = defineAdderConfig({
const extensionsArray = object.property(exportDefault, 'extensions', array.createEmpty());
array.push(extensionsArray, '.svelte');
array.push(extensionsArray, '.svx');

return generateCode();
}
}
]
Expand Down
6 changes: 4 additions & 2 deletions packages/adders/playwright/config/adder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { join } from 'node:path';
import { options } from './options.ts';
import { dedent, defineAdderConfig, log } from '@svelte-cli/core';
import { common, exports, imports, object } from '@svelte-cli/core/js';
import { parseScript } from '@svelte-cli/core/parsers';

export const adder = defineAdderConfig({
metadata: {
Expand Down Expand Up @@ -57,8 +58,8 @@ export const adder = defineAdderConfig({
},
{
name: ({ typescript }) => `playwright.config.${typescript ? 'ts' : 'js'}`,
contentType: 'script',
content: ({ ast }) => {
content: ({ content }) => {
const { ast, generateCode } = parseScript(content);
const defineConfig = common.expressionFromString('defineConfig({})');
const defaultExport = exports.defaultExport(ast, defineConfig);

Expand All @@ -84,6 +85,7 @@ export const adder = defineAdderConfig({
// unexpected config shape
log.warn('Unexpected playwright config for playwright adder. Could not update.');
}
return generateCode();
}
}
]
Expand Down
1 change: 0 additions & 1 deletion packages/adders/prettier/config/adder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,6 @@ export const adder = defineAdderConfig({
},
{
name: () => 'eslint.config.js',
contentType: 'script',
condition: ({ dependencies: deps }) => {
// We only want this to execute when it's `false`, not falsy

Expand Down
6 changes: 4 additions & 2 deletions packages/adders/routify/config/adder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { defineAdderConfig } from '@svelte-cli/core';
import { options } from './options.ts';
import { array, exports, functions, imports, object, variables } from '@svelte-cli/core/js';
import * as html from '@svelte-cli/core/html';
import { parseScript } from '@svelte-cli/core/parsers';

export const adder = defineAdderConfig({
metadata: {
Expand All @@ -20,8 +21,8 @@ export const adder = defineAdderConfig({
files: [
{
name: ({ typescript }) => `vite.config.${typescript ? 'ts' : 'js'}`,
contentType: 'script',
content: ({ ast }) => {
content: ({ content }) => {
const { ast, generateCode } = parseScript(content);
const vitePluginName = 'routify';
imports.addDefault(ast, '@roxi/routify/vite-plugin', vitePluginName);

Expand All @@ -37,6 +38,7 @@ export const adder = defineAdderConfig({
functions.argumentByIndex(pluginFunctionCall, 0, pluginConfig);

array.push(pluginsArray, pluginFunctionCall);
return generateCode();
}
},
{
Expand Down
8 changes: 6 additions & 2 deletions packages/adders/vitest/config/adder.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { options } from './options.ts';
import { dedent, defineAdderConfig, log } from '@svelte-cli/core';
import { common, exports, imports, object } from '@svelte-cli/core/js';
import { parseScript } from '@svelte-cli/core/parsers';

export const adder = defineAdderConfig({
metadata: {
Expand Down Expand Up @@ -49,8 +50,9 @@ export const adder = defineAdderConfig({
},
{
name: ({ typescript }) => `vite.config.${typescript ? 'ts' : 'js'}`,
contentType: 'script',
content: ({ ast }) => {
content: ({ content }) => {
const { ast, generateCode } = parseScript(content);

// find `defineConfig` import declaration for "vite"
const importDecls = ast.body.filter((n) => n.type === 'ImportDeclaration');
const defineConfigImportDecl = importDecls.find(
Expand Down Expand Up @@ -103,6 +105,8 @@ export const adder = defineAdderConfig({
// unexpected config shape
log.warn('Unexpected vite config for vitest adder. Could not update.');
}

return generateCode();
}
}
]
Expand Down
0