Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
FredKSchott committed Mar 18, 2022
1 parent 664027b commit 7a710fb
Show file tree
Hide file tree
Showing 138 changed files with 689 additions and 680 deletions.
9 changes: 1 addition & 8 deletions examples/integrations-playground/astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,5 @@ import sitemap from '@astrojs/sitemap';
import partytown from '@astrojs/partytown';

export default defineConfig({
integrations: [
lit(),
react(),
tailwind(),
turbolinks(),
partytown(),
sitemap(),
],
integrations: [lit(), react(), tailwind(), turbolinks(), partytown(), sitemap()],
});
6 changes: 3 additions & 3 deletions examples/integrations-playground/src/components/Button.jsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export default function Link({to, text}) {
return (<a href={to}>{text}</a>);
}
export default function Link({ to, text }) {
return <a href={to}>{text}</a>;
}
8 changes: 1 addition & 7 deletions packages/astro/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
"dev": "astro-scripts dev \"src/**/*.ts\"",
"postbuild": "astro-scripts copy \"src/**/*.astro\"",
"benchmark": "node test/benchmark/dev.bench.js && node test/benchmark/build.bench.js",
"test": "mocha --parallel --timeout 20000 --ignore **/lit-element.test.js && mocha --timeout 20000 **/lit-element.test.js",
"test": "mocha --exit --timeout 20000 --ignore **/lit-element.test.js && mocha --timeout 20000 **/lit-element.test.js",
"test:match": "mocha --timeout 20000 -g"
},
"dependencies": {
Expand Down Expand Up @@ -112,12 +112,6 @@
},
"devDependencies": {
"@astrojs/parser": "^0.22.2",
"@astrojs/preact": "^0.0.1",
"@astrojs/react": "0.0.1",
"@astrojs/svelte": "0.0.1",
"@astrojs/solid-js": "0.0.1",
"@astrojs/tailwind": "0.0.1",
"@astrojs/vue": "0.0.1",
"@babel/types": "^7.17.0",
"@types/babel__core": "^7.1.18",
"@types/babel__traverse": "^7.14.2",
Expand Down
3 changes: 0 additions & 3 deletions packages/astro/src/core/build/static-build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,6 @@ export async function staticBuild(opts: StaticBuildOptions) {

// Build internals needed by the CSS plugin
const internals = createBuildInternals();

for (const [component, pageData] of Object.entries(allPages)) {
const astroModuleURL = new URL('./' + component, astroConfig.projectRoot);
const astroModuleId = prependForwardSlash(component);
Expand Down Expand Up @@ -179,7 +178,6 @@ async function ssrBuild(opts: StaticBuildOptions, internals: BuildInternals, inp
const { astroConfig, viteConfig } = opts;
const ssr = astroConfig.buildOptions.experimentalSsr;
const out = ssr ? getServerRoot(astroConfig) : getOutRoot(astroConfig);

// TODO: use vite.mergeConfig() here?
return await vite.build({
logLevel: 'warn',
Expand Down Expand Up @@ -245,7 +243,6 @@ async function clientBuild(opts: StaticBuildOptions, internals: BuildInternals,
outDir: fileURLToPath(out),
rollupOptions: {
input: Array.from(input),
treeshake: true,
output: {
format: 'esm',
entryFileNames: '[name].[hash].js',
Expand Down
86 changes: 36 additions & 50 deletions packages/astro/src/core/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -284,55 +284,41 @@ export function formatConfigError(err: z.ZodError) {
return `${colors.red('[config]')} Astro found issue(s) with your configuration:\n${errorList.join('\n')}`;
}


function mergeConfigRecursively(
defaults: Record<string, any>,
overrides: Record<string, any>,
rootPath: string
) {
const merged: Record<string, any> = { ...defaults }
function mergeConfigRecursively(defaults: Record<string, any>, overrides: Record<string, any>, rootPath: string) {
const merged: Record<string, any> = { ...defaults };
for (const key in overrides) {
const value = overrides[key]
if (value == null) {
continue
}

const existing = merged[key]

if (existing == null) {
merged[key] = value
continue
}

// fields that require special handling:
if (key === 'vite' && rootPath === '') {
merged[key] = mergeViteConfig(existing, value);
continue
}

if (Array.isArray(existing) || Array.isArray(value)) {
merged[key] = [...arraify(existing ?? []), ...arraify(value ?? [])]
continue
}
if (isObject(existing) && isObject(value)) {
merged[key] = mergeConfigRecursively(
existing,
value,
rootPath ? `${rootPath}.${key}` : key
)
continue
}

merged[key] = value
const value = overrides[key];
if (value == null) {
continue;
}

const existing = merged[key];

if (existing == null) {
merged[key] = value;
continue;
}

// fields that require special handling:
if (key === 'vite' && rootPath === '') {
merged[key] = mergeViteConfig(existing, value);
continue;
}

if (Array.isArray(existing) || Array.isArray(value)) {
merged[key] = [...arraify(existing ?? []), ...arraify(value ?? [])];
continue;
}
if (isObject(existing) && isObject(value)) {
merged[key] = mergeConfigRecursively(existing, value, rootPath ? `${rootPath}.${key}` : key);
continue;
}

merged[key] = value;
}
return merged
}

export function mergeConfig(
defaults: Record<string, any>,
overrides: Record<string, any>,
isRoot = true
): Record<string, any> {
return mergeConfigRecursively(defaults, overrides, isRoot ? '' : '.')
}

return merged;
}

export function mergeConfig(defaults: Record<string, any>, overrides: Record<string, any>, isRoot = true): Record<string, any> {
return mergeConfigRecursively(defaults, overrides, isRoot ? '' : '.');
}
2 changes: 1 addition & 1 deletion packages/astro/src/core/render/dev/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ export async function render(renderers: SSRLoadedRenderer[], mod: ComponentInsta
origin,
pathname,
scripts,
// Resolves specifiers in the inline hydrated scripts, such as "@astrojs/renderer-preact/client.js"
// Resolves specifiers in the inline hydrated scripts, such as "@astrojs/preact/client.js"
// TODO: Can we pass the hydration code more directly through Vite, so that we
// don't need to copy-paste and maintain Vite's import resolution here?
async resolve(s: string) {
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/core/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export function isObject(value: unknown): value is Record<string, any> {

/** Wraps an object in an array. If an array is passed, ignore it. */
export function arraify<T>(target: T | T[]): T[] {
return Array.isArray(target) ? target : [target]
return Array.isArray(target) ? target : [target];
}

/** is a specifier an npm package? */
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/integrations/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { AstroConfig, AstroRenderer } from '../@types/astro.js';
import { mergeConfig } from '../core/config.js';

export async function runHookConfigSetup({ config: _config, command }: { config: AstroConfig; command: 'dev' | 'build' }): Promise<AstroConfig> {
let updatedConfig: AstroConfig = {..._config};
let updatedConfig: AstroConfig = { ..._config };
for (const integration of _config.integrations) {
if (integration.hooks['astro:config:setup']) {
await integration.hooks['astro:config:setup']({
Expand Down
18 changes: 9 additions & 9 deletions packages/astro/src/runtime/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,14 +111,14 @@ function guessRenderers(componentUrl?: string): string[] {
const extname = componentUrl?.split('.').pop();
switch (extname) {
case 'svelte':
return ['@astrojs/renderer-svelte'];
return ['@astrojs/svelte'];
case 'vue':
return ['@astrojs/renderer-vue'];
return ['@astrojs/vue'];
case 'jsx':
case 'tsx':
return ['@astrojs/renderer-react', '@astrojs/renderer-preact'];
return ['@astrojs/react', '@astrojs/preact'];
default:
return ['@astrojs/renderer-react', '@astrojs/renderer-preact', '@astrojs/renderer-vue', '@astrojs/renderer-svelte'];
return ['@astrojs/react', '@astrojs/preact', '@astrojs/vue', '@astrojs/svelte'];
}
}

Expand Down Expand Up @@ -166,8 +166,8 @@ export async function renderComponent(result: SSRResult, displayName: string, Co
if (Array.isArray(renderers) && renderers.length === 0 && typeof Component !== 'string' && !componentIsHTMLElement(Component)) {
const message = `Unable to render ${metadata.displayName}!
There are no \`renderers\` set in your \`astro.config.mjs\` file.
Did you mean to enable ${formatList(probableRendererNames.map((r) => '`' + r + '`'))}?`;
There are no \`integrations\` set in your \`astro.config.mjs\` file.
Did you mean to add ${formatList(probableRendererNames.map((r) => '`' + r + '`'))}?`;
throw new Error(message);
}

Expand All @@ -190,7 +190,7 @@ Did you mean to enable ${formatList(probableRendererNames.map((r) => '`' + r + '
// Attempt: use explicitly passed renderer name
if (metadata.hydrateArgs) {
const rendererName = metadata.hydrateArgs;
renderer = renderers.filter(({ name }) => name === `@astrojs/renderer-${rendererName}` || name === rendererName)[0];
renderer = renderers.filter(({ name }) => name === `@astrojs/${rendererName}` || name === rendererName)[0];
}
// Attempt: user only has a single renderer, default to that
if (!renderer && renderers.length === 1) {
Expand All @@ -199,7 +199,7 @@ Did you mean to enable ${formatList(probableRendererNames.map((r) => '`' + r + '
// Attempt: can we guess the renderer from the export extension?
if (!renderer) {
const extname = metadata.componentUrl?.split('.').pop();
renderer = renderers.filter(({ name }) => name === `@astrojs/renderer-${extname}` || name === extname)[0];
renderer = renderers.filter(({ name }) => name === `@astrojs/${extname}` || name === extname)[0];
}
}

Expand All @@ -210,7 +210,7 @@ Did you mean to enable ${formatList(probableRendererNames.map((r) => '`' + r + '
throw new Error(`Unable to render ${metadata.displayName}!
Using the \`client:only\` hydration strategy, Astro needs a hint to use the correct renderer.
Did you mean to pass <${metadata.displayName} client:only="${probableRendererNames.map((r) => r.replace('@astrojs/renderer-', '')).join('|')}" />
Did you mean to pass <${metadata.displayName} client:only="${probableRendererNames.map((r) => r.replace('@astrojs/', '')).join('|')}" />
`);
} else if (typeof Component !== 'string') {
const matchingRenderers = renderers.filter((r) => probableRendererNames.includes(r.name));
Expand Down
8 changes: 1 addition & 7 deletions packages/astro/src/vite-plugin-astro/compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,13 +122,7 @@ export function invalidateCompilation(config: AstroConfig, filename: string) {
}
}

export async function cachedCompilation(
config: AstroConfig,
filename: string,
source: string,
viteTransform: TransformHook,
opts: { ssr: boolean }
): Promise<CompileResult> {
export async function cachedCompilation(config: AstroConfig, filename: string, source: string, viteTransform: TransformHook, opts: { ssr: boolean }): Promise<CompileResult> {
let cache: CompilationCache;
if (!configCache.has(config)) {
cache = new Map();
Expand Down
9 changes: 4 additions & 5 deletions packages/astro/src/vite-plugin-astro/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,15 +85,15 @@ export default function astro({ config, logging }: AstroPluginOptions): vite.Plu
async load(id, opts) {
const parsedId = parseAstroRequest(id);
const query = parsedId.query;
if (!id.endsWith(".astro") && !query.astro) {
return null;
if (!id.endsWith('.astro') && !query.astro) {
return null;
}

const filename = normalizeFilename(parsedId.filename);
const fileUrl = new URL(`file://${filename}`);
let source = await fs.promises.readFile(fileUrl, "utf-8");
let source = await fs.promises.readFile(fileUrl, 'utf-8');
const isPage = filename.startsWith(config.pages.pathname);
if (isPage && config._ctx.scripts.some(s => s.stage === 'page')) {
if (isPage && config._ctx.scripts.some((s) => s.stage === 'page')) {
source += `\n<script hoist src="astro:scripts/page.js" />`;
}
if (query.astro) {
Expand All @@ -102,7 +102,6 @@ export default function astro({ config, logging }: AstroPluginOptions): vite.Plu
throw new Error(`Requests for Astro CSS must include an index.`);
}


const transformResult = await cachedCompilation(config, filename, source, viteTransform, { ssr: Boolean(opts?.ssr) });

// Track any CSS dependencies so that HMR is triggered when they change.
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/vite-plugin-jsx/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ export default function jsx({ config, logging }: AstroPluginJSXOptions): Plugin
const jsxRenderer = jsxRenderers.get(importSource);
// if renderer not installed for this JSX source, throw error
if (!jsxRenderer) {
error(logging, 'renderer', `${colors.yellow(id)} No renderer installed for ${importSource}. Try adding \`@astrojs/renderer-${importSource}\` to your dependencies.`);
error(logging, 'renderer', `${colors.yellow(id)} No renderer installed for ${importSource}. Try adding \`@astrojs/${importSource}\` to your project.`);
return null;
}
// downlevel any non-standard syntax, but preserve JSX
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/vite-plugin-scripts/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { AstroConfig } from '../@types/astro.js';

// NOTE: We can't use the virtual "\0" ID convention because we need to
// inject these as ESM imports into actual code, where they would not
// resolve correctly.
// resolve correctly.
const SCRIPT_ID_PREFIX = `astro:scripts/`;
const BEFORE_HYDRATION_SCRIPT_ID = `${SCRIPT_ID_PREFIX}before-hydration.js`;
const PAGE_SCRIPT_ID = `${SCRIPT_ID_PREFIX}page.js`;
Expand Down
14 changes: 1 addition & 13 deletions packages/astro/test/0-css.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,11 @@ import { expect } from 'chai';
import cheerio from 'cheerio';
import { loadFixture } from './test-utils.js';

import reactIntegration from '@astrojs/react';
import svelteIntegration from '@astrojs/svelte';
import vueIntegration from '@astrojs/vue';

let fixture;

describe('CSS', function () {
before(async () => {
fixture = await loadFixture({
projectRoot: './fixtures/0-css/',
integrations: [reactIntegration(), svelteIntegration(), vueIntegration()],
vite: {
build: {
assetsInlineLimit: 0,
},
},
});
fixture = await loadFixture({ projectRoot: './fixtures/0-css/' });
});

// test HTML and CSS contents for accuracy
Expand Down
5 changes: 0 additions & 5 deletions packages/astro/test/astro-assets.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,6 @@ describe('Assets', () => {
before(async () => {
fixture = await loadFixture({
projectRoot: './fixtures/astro-assets/',
vite: {
build: {
assetsInlineLimit: 0,
},
},
});
await fixture.build();
});
Expand Down
5 changes: 1 addition & 4 deletions packages/astro/test/astro-children.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,7 @@ describe('Component children', () => {
let fixture;

before(async () => {
fixture = await loadFixture({
projectRoot: './fixtures/astro-children/',
renderers: ['@astrojs/renderer-preact', '@astrojs/renderer-vue', '@astrojs/renderer-svelte'],
});
fixture = await loadFixture({ projectRoot: './fixtures/astro-children/' });
await fixture.build();
});

Expand Down
23 changes: 5 additions & 18 deletions packages/astro/test/astro-dynamic.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,24 +32,11 @@ describe('Dynamic components', () => {
const html = await fixture.readFile('/client-only/index.html');
const $ = cheerio.load(html);

// test 1: <astro-root> is empty
// test 1: <astro-root> is empty.
expect($('<astro-root>').html()).to.equal('');
const script = $('script').text();

// Grab the svelte import
// const exp = /import\("(.+?)"\)/g;
// let match, svelteRenderer;
// while ((match = exp.exec(result.contents))) {
// if (match[1].includes('renderers/renderer-svelte/client.js')) {
// svelteRenderer = match[1];
// }
// }

// test 2: Svelte renderer is on the page
// expect(svelteRenderer).to.be.ok;

// test 3: Can load svelte renderer
// const result = await fixture.fetch(svelteRenderer);
// expect(result.status).to.equal(200);
// test 2: correct script is being loaded.
// because of bundling, we don't have access to the source import,
// only the bundled import.
expect($('script').html()).to.include(`import setup from '../only`);
});
});
1 change: 0 additions & 1 deletion packages/astro/test/astro-expr.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ describe('Expressions', () => {
before(async () => {
fixture = await loadFixture({
projectRoot: './fixtures/astro-expr/',
renderers: ['@astrojs/renderer-preact'],
});
await fixture.build();
});
Expand Down
Loading

0 comments on commit 7a710fb

Please sign in to comment.