Skip to content

Commit

Permalink
Updates for Astro 5 (#106)
Browse files Browse the repository at this point in the history
* test with latest versions

* adjust test: adds-to-head

* adjust test: dynamic-import

* fix script command

* adjust tests: prerender-patterns

* adjust tests: scope

* fix(typed-api): declaration file generation

* update test script for emotion

* update dependencies

* update dev dependency to avoid type error

* astro 5 replaces hybrid option with static

* new fields in APIContext

* updated lockfile

* remain on typescript 5.6

* fix getting scope from compiler

* adjust test: adds-to-head

* workaround for astro bug

* remove console.log

* fix(emotion): css on server components since vite 6

* chore(global): directly augment types

* fix(scope): use final astro config for the compiler

* chore(scope): directly augment types

* chore(dynamic import): directly augment types

* chore(emotion): directly augment types

* chore(typed-api): rework type generation

* update astro to 5.0.3

* switch workaround for withastro/astro#12612 with workaround for withastro/astro#12652

* feat(emotion): caching

* chore(client-interaction): minor bump

* chore(dynamic-import): major bump

* chore(typed-api): minor bump

* chore(astro-emotion): major bump

* chore(astro-global): major bump

* chore(astro-scope): major bump

* update lockfile

* remove console.log
  • Loading branch information
lilnasy authored Dec 9, 2024
1 parent baf2b03 commit 55d85cc
Show file tree
Hide file tree
Showing 52 changed files with 1,114 additions and 930 deletions.
5 changes: 5 additions & 0 deletions .changeset/astro-emotion-cache.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"astro-emotion": minor
---

Optimizes the extraction of styles by using a cache. Parsing of the source code of the modules importing `astro-emotiion`, and replacement of styles with generated class names is now skipped if the exact source code was previously processed. This prevents unnecessary work caused by the fact that most files are processed twice, once for SSR and once for the client.
8 changes: 8 additions & 0 deletions .changeset/astro-emotion.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"astro-emotion": major
---

Updates the package to support changes in how Astro 5 handles generated types. Changes to `env.d.ts` are no longer performed, and the types are automatically added to your project when you import the integration to the Astro configuration file.

References to `astro-dynamic-import/client` for types can now safely be removed from your project.

7 changes: 7 additions & 0 deletions .changeset/astro-global.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"astro-global": major
---

Updates the package to support changes in how Astro 5 handles generated types. Changes to `env.d.ts` are no longer performed, and the types are automatically added to your project when you import the integration to the Astro configuration file.

References to `astro-global/client` for types can now safely be removed from your project.
8 changes: 8 additions & 0 deletions .changeset/astro-scope.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"astro-scope": major
---

Updates the package to support changes in how Astro 5 handles generated types. Changes to `env.d.ts` are no longer performed, and the types are automatically added to your project when you import the integration to the Astro configuration file.

References to `astro-scope/client` for types can now safely be removed from your project.

5 changes: 5 additions & 0 deletions .changeset/client-interaction.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"astro-client-interaction": minor
---

Updates the package fields to allow installation alongside Astro 5. This is a clerical change, and the behavior of the integration itself is unchanged.
7 changes: 7 additions & 0 deletions .changeset/dynamic-import.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"astro-dynamic-import": major
---

Updates the package to support changes in how Astro 5 handles generated types. Changes to `env.d.ts` are no longer performed, and the types are automatically added to your project when you import the integration to the Astro configuration file.

References to `astro-dynamic-import/client` for types can now safely be removed from your project.
5 changes: 5 additions & 0 deletions .changeset/global fields.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"astro-global": minor
---

The package has been updated to allow access to more properties: `Astro.routePattern`, `Astro.originPathname`, and `Astro.isPrerendered`.
5 changes: 5 additions & 0 deletions .changeset/scope-generation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"astro-scope": patch
---

Improves reliability of using the Astro compiler to retrieve the scope.
5 changes: 5 additions & 0 deletions .changeset/scope-peer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"astro-scope": major
---

Updates the package fields to allow installation alongside Astro 5.
5 changes: 5 additions & 0 deletions .changeset/typed-api.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"astro-typed-api": minor
---

Updates the package to support changes in how Astro 5 handles generated types. Changes to `env.d.ts` are no longer performed, and the generated types are written to `<root>/.astro/astro-typed-api/types.d.ts`.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
],
"packageManager": "pnpm@9.12.2",
"devDependencies": {
"astro": "4",
"astro": "5",
"@changesets/changelog-github": "0.5",
"@changesets/cli": "2",
"typescript": "5.6"
Expand Down
2 changes: 1 addition & 1 deletion packages/adds-to-head/integration.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { AstroIntegration, AstroConfig } from "astro"
import type { AstroIntegration } from "astro"
import url from "node:url"

interface Options {}
Expand Down
4 changes: 2 additions & 2 deletions packages/adds-to-head/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@
".": "./integration.ts"
},
"scripts": {
"test": "pnpm -w test tests/adds-to-head.test.ts"
"test": "pnpm -w test adds-to-head.test.ts"
},
"type": "module",
"devDependencies": {
"@types/node": "20",
"astro": "4"
"astro": "5"
}
}
2 changes: 1 addition & 1 deletion packages/client-interaction/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
},
"type": "module",
"peerDependencies": {
"astro": "4"
"astro": "4 || 5"
},
"devDependencies": {
"@types/node": "20"
Expand Down
1 change: 1 addition & 0 deletions packages/dynamic-import/integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import path from "node:path"
import fs from "node:fs"
import type { AstroConfig, AstroIntegration, AstroIntegrationLogger } from "astro"
import { PROPAGATED_ASSET_FLAG } from "./node_modules/astro/dist/content/consts.js"
import "./types.d.ts"

interface Options {}

Expand Down
9 changes: 3 additions & 6 deletions packages/dynamic-import/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,18 @@
"files": [
"integration.ts",
"runtime",
"client.d.ts"
"types.d.ts"
],
"exports": {
".": "./integration.ts",
"./runtime/*": "./runtime/*",
"./client": {
"types": "./client.d.ts"
}
"./runtime/*": "./runtime/*"
},
"scripts": {
"test": "pnpm -w test dynamic-import.test.ts"
},
"type": "module",
"peerDependencies": {
"astro": "4"
"astro": "4 || 5"
},
"devDependencies": {
"@types/node": "20"
Expand Down
File renamed without changes.
174 changes: 95 additions & 79 deletions packages/emotion/integration.ts
Original file line number Diff line number Diff line change
@@ -1,101 +1,117 @@
import fs from "node:fs"
import url from "node:url"
import path from "node:path"
import crypto from "node:crypto"
import { simple as walk } from "acorn-walk"
import createEmotion, { type Options as EmotionOptions } from "@emotion/css/create-instance"
import MagicString from "magic-string"
import { visitors, type State } from "./ast-scanner.ts"
import type { AstroConfig, AstroIntegration, AstroIntegrationLogger } from "astro"
import type { ModuleGraph, Plugin, TransformResult } from "vite"
import type { AstroIntegration } from "astro"
import "./types.d.ts"

interface Options extends EmotionOptions {}

export default function (options: Partial<Options> = {}): AstroIntegration {
return {
name: "astro-emotion",
hooks: {
"astro:config:setup": ({ updateConfig, config, logger }) => {
const stylesheets = new Map<string, string>
const { css, cache, flush, injectGlobal } = createEmotion({ key: "e", ...options })
let moduleGraph: import("vite").ModuleGraph
updateConfig({ vite: { plugins: [{
name: "astro-emotion/vite",
configureServer(server) {
moduleGraph = server.moduleGraph
},
handleHotUpdate({ modules }) {
for (const mod of modules) {
for (const imported of mod.clientImportedModules.values()) {
if (stylesheets.has(imported.id ?? "")) modules.push(imported)
}
}
},
transform(code, id) {
if (code.includes("astro:emotion") === false) return
const ast = this.parse(code)
const magicString = new MagicString(code, { filename: id })
const state: State = { id, css, injectGlobal, magicString }
walk(ast, visitors, undefined, state)
const stylesheet = Object.values(cache.inserted).join('\n')
flush()
const hash = crypto.hash("md5", id, "hex").slice(0, 8)
const cssId = `/astro_emotion_internal_${hash}.css`
const update = stylesheets.has(cssId)
stylesheets.set(cssId, stylesheet)
if (update) {
const module = moduleGraph.getModuleById(cssId)
if (module) moduleGraph.invalidateModule(module)
}
magicString.prepend(`import ${JSON.stringify(cssId)}\n`)
const newCode = magicString.toString()
const map = magicString.generateMap({ hires: true })
return { code: newCode, map }
},
resolveId(source) {
if (stylesheets.has(source)) return source
// HACK: prevent warnings from vite when it scans a file before letting it be transformed
if (source === "astro:emotion") return source
},
load(id) {
return stylesheets.get(id)
}
}, {
name: "astro-emotion/vite/types",
enforce: "post",
config() {
injectEnvDTS(config, logger, "astro-emotion/client")
}
}] } })
"astro:config:setup"({ updateConfig }) {
updateConfig({ vite: { plugins: createVitePlugins(options) } })
}
}
}
}

function injectEnvDTS(config: AstroConfig, logger: AstroIntegrationLogger, specifier: URL | string) {
const envDTsPath = url.fileURLToPath(new URL("env.d.ts", config.srcDir))
function createVitePlugins(options: Partial<Options>): [ Plugin, Plugin ] {

if (specifier instanceof URL) {
specifier = url.fileURLToPath(specifier)
specifier = path.relative(url.fileURLToPath(config.srcDir), specifier)
specifier = specifier.replaceAll("\\", "/")
}

let envDTsContents = fs.readFileSync(envDTsPath, "utf-8")
/**
* A cache of the js/ts files that have had their css extracted.
*
* **key**: the source code of the js/ts file
*
* **value**: the generated css code + js with styles replaced with class names
*/
const transformCache = new Map<string, [ stylesheet: string, TransformResult]>

if (envDTsContents.includes(`/// <reference types='${specifier}' />`)) { return }
if (envDTsContents.includes(`/// <reference types="${specifier}" />`)) { return }
/**
* The up-to-date versions of the generated css files.
*
* **key**: the virtual id of the css file (`/astro_emotion_internal_${hash}.css`)
*
* **value**: the generated css code
*/
const stylesheets = new Map<string, string>

const newEnvDTsContents = envDTsContents.replace(
`/// <reference types='astro/client' />`,
`/// <reference types='astro/client' />\n/// <reference types='${specifier}' />\n`
).replace(
`/// <reference types="astro/client" />`,
`/// <reference types="astro/client" />\n/// <reference types="${specifier}" />\n`
)
const { css, cache, flush, injectGlobal } = createEmotion({ key: "e", ...options })

// the odd case where the user changed the reference to astro/client
if (newEnvDTsContents === envDTsContents) { return }

fs.writeFileSync(envDTsPath, newEnvDTsContents)
logger.info("Updated env.d.ts types")
let moduleGraph: ModuleGraph

return [{
name: "astro-emotion/vite",
configureServer(server) {
moduleGraph = server.moduleGraph
},
transform(code, id) {
if (code.includes("astro:emotion") === false) return
const hash = crypto.hash("md5", id, "hex").slice(0, 8)
const cssId = `/astro_emotion_internal_${hash}.css`
const seen = transformCache.get(code)
if (seen) {
const [ stylesheet, transformResult ] = seen
revalidate(moduleGraph, stylesheets, cssId, stylesheet)
return transformResult
}
if (transformCache.size > 100) {
transformCache.delete(transformCache.keys().next().value!)
}
const ast = this.parse(code)
const magicString = new MagicString(code, { filename: id })
const state: State = { id, css, injectGlobal, magicString }
walk(ast, visitors, undefined, state)
const stylesheet = Object.values(cache.inserted).join('\n')
flush()
revalidate(moduleGraph, stylesheets, cssId, stylesheet)
magicString.prepend(`import ${JSON.stringify(cssId)}\n`)
const transformResult: TransformResult = {
code: magicString.toString(),
map: magicString.generateMap({ hires: true })
}
transformCache.set(code, [ stylesheet, transformResult ])
return transformResult
},
resolveId(source) {
if (stylesheets.has(source)) return source
// HACK: prevent warnings from vite when it scans a file before letting it be transformed
if (source === "astro:emotion") return source
},
load(id) {
return stylesheets.get(id)
}
}, {
name: "astro-emotion/vite/server",
enforce: "post",
apply: "serve",
applyToEnvironment(environment) {
return environment.config.consumer === "server"
},
transform(_, id) {
const css = stylesheets.get(id)
if (css) return `export default ${JSON.stringify(css)}`
}
}]
}

function revalidate(
moduleGraph: ModuleGraph,
stylesheets: Map<string, string>,
cssId: string,
stylesheet: string,
) {
const existing = stylesheets.get(cssId)
if (existing !== stylesheet) {
stylesheets.set(cssId, stylesheet)
const module = moduleGraph.getModuleById(cssId)
if (module) {
moduleGraph.invalidateModule(module)
module.lastHMRTimestamp = Date.now()
}
}
}
13 changes: 5 additions & 8 deletions packages/emotion/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,13 @@
"files": [
"integration.ts",
"ast-scanner.ts",
"client.d.ts"
"types.d.ts"
],
"exports": {
".": "./integration.ts",
"./client": {
"types": "./client.d.ts"
}
".": "./integration.ts"
},
"scripts": {
"test": "pnpm -w test tests/emotion.dev.test.ts tests/emotion.build.test.ts"
"test": "pnpm -w test emotion.dev.test.ts emotion.build.test.ts"
},
"type": "module",
"dependencies": {
Expand All @@ -36,7 +33,7 @@
},
"devDependencies": {
"@types/node": "20",
"astro": "4",
"vite": "5"
"astro": "5",
"vite": "6"
}
}
File renamed without changes.
Loading

0 comments on commit 55d85cc

Please sign in to comment.