From b19c4bb0415b4b2741a59e9b33bdfb3bed3519aa Mon Sep 17 00:00:00 2001 From: Luca Casonato Date: Wed, 7 Sep 2022 11:36:23 +0200 Subject: [PATCH] feat: add update.ts script (#706) This commit adds an update.ts tool that makes it easy to upgrade existing Fresh projects to the latest version of Fresh. This tool updates dependency versions in the import map, and includes some code mods: 1. update projects from classic JSX to automatic JSX 2. update projects from legacy twind integration to twind plugin Both of these code mods get you about 95% of the way there most of the time. Users might still need to do some manual work to get their projects fully updated. --- init.ts | 17 +-- src/dev/deps.ts | 3 + src/dev/imports.ts | 16 +++ update.ts | 180 ++++++++++++++++++++++++++ www/routes/update.tsx | 288 ++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 491 insertions(+), 13 deletions(-) create mode 100644 src/dev/imports.ts create mode 100644 update.ts create mode 100644 www/routes/update.tsx diff --git a/init.ts b/init.ts index fdd66ece..90174f40 100644 --- a/init.ts +++ b/init.ts @@ -1,6 +1,7 @@ import { join, parse, resolve } from "./src/dev/deps.ts"; import { error } from "./src/dev/error.ts"; import { collect, ensureMinDenoVersion, generate } from "./src/dev/mod.ts"; +import { freshImports, twindImports } from "./src/dev/imports.ts"; ensureMinDenoVersion(); @@ -76,19 +77,9 @@ if (useVSCode) { await Deno.mkdir(join(resolvedDirectory, ".vscode"), { recursive: true }); } -const importMap = { - "imports": { - "$fresh/": new URL("./", import.meta.url).href, - "preact": "https://esm.sh/preact@10.10.6", - "preact/": "https://esm.sh/preact@10.10.6/", - "preact-render-to-string": - "https://esm.sh/preact-render-to-string@5.2.2?external=preact", - } as Record, -}; -if (useTwind) { - importMap.imports["twind"] = "https://esm.sh/twind@0.16.17"; - importMap.imports["twind/"] = "https://esm.sh/twind@0.16.17/"; -} +const importMap = { imports: {} as Record }; +freshImports(importMap.imports); +if (useTwind) twindImports(importMap.imports); const IMPORT_MAP_JSON = JSON.stringify(importMap, null, 2) + "\n"; await Deno.writeTextFile( join(resolvedDirectory, "import_map.json"), diff --git a/src/dev/deps.ts b/src/dev/deps.ts index a22f95ea..d3dc884b 100644 --- a/src/dev/deps.ts +++ b/src/dev/deps.ts @@ -10,3 +10,6 @@ export { export { walk } from "https://deno.land/std@0.150.0/fs/walk.ts"; export { parse } from "https://deno.land/std@0.150.0/flags/mod.ts"; export { gte } from "https://deno.land/std@0.150.0/semver/mod.ts"; + +// ts-morph +export { Node, Project } from "https://deno.land/x/ts_morph@16.0.0/mod.ts"; diff --git a/src/dev/imports.ts b/src/dev/imports.ts new file mode 100644 index 00000000..98769c1e --- /dev/null +++ b/src/dev/imports.ts @@ -0,0 +1,16 @@ +export const RECOMMENDED_PREACT_VERSION = "10.10.6"; +export const RECOMMENDED_PREACT_RTS_VERSION = "5.2.2"; +export const RECOMMENDED_TWIND_VERSION = "0.16.17"; + +export function freshImports(imports: Record) { + imports["$fresh/"] = new URL("../../", import.meta.url).href; + imports["preact"] = `https://esm.sh/preact@${RECOMMENDED_PREACT_VERSION}`; + imports["preact/"] = `https://esm.sh/preact@${RECOMMENDED_PREACT_VERSION}/`; + imports["preact-render-to-string"] = + `https://esm.sh/*preact-render-to-string@${RECOMMENDED_PREACT_RTS_VERSION}/`; +} + +export function twindImports(imports: Record) { + imports["twind"] = `https://esm.sh/twind@${RECOMMENDED_TWIND_VERSION}`; + imports["twind/"] = `https://esm.sh/twind@${RECOMMENDED_TWIND_VERSION}/`; +} diff --git a/update.ts b/update.ts new file mode 100644 index 00000000..52df9800 --- /dev/null +++ b/update.ts @@ -0,0 +1,180 @@ +import { join, Node, parse, Project, resolve } from "./src/dev/deps.ts"; +import { error } from "./src/dev/error.ts"; +import { freshImports, twindImports } from "./src/dev/imports.ts"; +import { collect, ensureMinDenoVersion, generate } from "./src/dev/mod.ts"; + +ensureMinDenoVersion(); + +const help = `fresh-update + +Update a Fresh project. This updates dependencies and optionally performs code +mods to update a project's source code to the latest recommended patterns. + +To upgrade a projecct in the current directory, run: + fresh-update . + +USAGE: + fresh-update +`; + +const flags = parse(Deno.args, {}); + +if (flags._.length !== 1) { + error(help); +} + +const unresolvedDirectory = Deno.args[0]; +const resolvedDirectory = resolve(unresolvedDirectory); + +// Update dependencies in the import map. +const IMPORT_MAP_PATH = join(resolvedDirectory, "import_map.json"); +let importMapText = await Deno.readTextFile(IMPORT_MAP_PATH); +const importMap = JSON.parse(importMapText); +freshImports(importMap.imports); +if (importMap.imports["twind"]) { + twindImports(importMap.imports); +} +importMapText = JSON.stringify(importMap, null, 2); +await Deno.writeTextFile(IMPORT_MAP_PATH, importMapText); + +// Code mod for classic JSX -> automatic JSX. +const JSX_CODEMOD = + `This project is using the classic JSX transform. Would you like to update to the +automatic JSX transform? This will remove the /** @jsx h */ pragma from your +source code and add the jsx: "react-jsx" compiler option to your deno.json file.`; +const DENO_JSON_PATH = join(resolvedDirectory, "deno.json"); +let denoJsonText = await Deno.readTextFile(DENO_JSON_PATH); +const denoJson = JSON.parse(denoJsonText); +if (denoJson.compilerOptions?.jsx !== "react-jsx" && confirm(JSX_CODEMOD)) { + console.log("Updating config file..."); + denoJson.compilerOptions = denoJson.compilerOptions || {}; + denoJson.compilerOptions.jsx = "react-jsx"; + denoJson.compilerOptions.jsxImportSource = "preact"; + denoJsonText = JSON.stringify(denoJson, null, 2); + await Deno.writeTextFile(DENO_JSON_PATH, denoJsonText); + + const project = new Project(); + const sfs = project.addSourceFilesAtPaths( + join(resolvedDirectory, "**", "*.{js,jsx,ts,tsx}"), + ); + + for (const sf of sfs) { + for (const d of sf.getImportDeclarations()) { + if (d.getModuleSpecifierValue() !== "preact") continue; + for (const n of d.getNamedImports()) { + const name = n.getName(); + if (name === "h" || name === "Fragment") n.remove(); + } + if ( + d.getNamedImports().length === 0 && + d.getNamespaceImport() === undefined && + d.getDefaultImport() === undefined + ) { + d.remove(); + } + } + + let text = sf.getFullText(); + text = text.replaceAll("/** @jsx h */\n", ""); + text = text.replaceAll("/** @jsxFrag Fragment */\n", ""); + sf.replaceWithText(text); + + await sf.save(); + } +} + +// Code mod for class={tw`border`} to class="border". +const TWIND_CODEMOD = + `This project is using an old version of the twind integration. Would you like to +update to the new twind plugin? This will remove the 'class={tw\`border\`}' +boilerplate from your source code replace it with the simpler 'class="border"'.`; +if (importMap.imports["@twind"] && confirm(TWIND_CODEMOD)) { + await Deno.remove(join(resolvedDirectory, importMap.imports["@twind"])); + + delete importMap.imports["@twind"]; + importMapText = JSON.stringify(importMap, null, 2); + await Deno.writeTextFile(IMPORT_MAP_PATH, importMapText); + + const MAIN_TS = `/// +/// +/// +/// +/// + +import { start } from "$fresh/server.ts"; +import manifest from "./fresh.gen.ts"; + +import twindPlugin from "$fresh/plugins/twind.ts"; +import twindConfig from "./twind.config.ts"; + +await start(manifest, { plugins: [twindPlugin(twindConfig)] });\n`; + const MAIN_TS_PATH = join(resolvedDirectory, "main.ts"); + await Deno.writeTextFile(MAIN_TS_PATH, MAIN_TS); + + const TWIND_CONFIG_TS = `import { Options } from "$fresh/plugins/twind.ts"; + + export default { + selfURL: import.meta.url, + } as Options; + `; + await Deno.writeTextFile( + join(resolvedDirectory, "twind.config.ts"), + TWIND_CONFIG_TS, + ); + + const project = new Project(); + const sfs = project.addSourceFilesAtPaths( + join(resolvedDirectory, "**", "*.{js,jsx,ts,tsx}"), + ); + + for (const sf of sfs) { + const nodes = sf.forEachDescendantAsArray(); + for (const n of nodes) { + if (!n.wasForgotten() && Node.isJsxAttribute(n)) { + const init = n.getInitializer(); + const name = n.getName(); + if ( + Node.isJsxExpression(init) && + (name === "class" || name === "className") + ) { + const expr = init.getExpression(); + if (Node.isTaggedTemplateExpression(expr)) { + const tag = expr.getTag(); + if (Node.isIdentifier(tag) && tag.getText() === "tw") { + const template = expr.getTemplate(); + if (Node.isNoSubstitutionTemplateLiteral(template)) { + n.setInitializer(`"${template.getLiteralValue()}"`); + } + } + } else if (expr?.getFullText() === `tw(props.class ?? "")`) { + n.setInitializer(`{props.class}`); + } + } + } + } + + const text = sf.getFullText(); + const removeTw = [...text.matchAll(/tw[,\s`(]/g)].length === 1; + + for (const d of sf.getImportDeclarations()) { + if (d.getModuleSpecifierValue() !== "@twind") continue; + for (const n of d.getNamedImports()) { + const name = n.getName(); + if (name === "tw" && removeTw) n.remove(); + } + d.setModuleSpecifier("twind"); + if ( + d.getNamedImports().length === 0 && + d.getNamespaceImport() === undefined && + d.getDefaultImport() === undefined + ) { + d.remove(); + } + } + + await sf.save(); + } +} + +const manifest = await collect(resolvedDirectory); +await generate(resolvedDirectory, manifest); diff --git a/www/routes/update.tsx b/www/routes/update.tsx new file mode 100644 index 00000000..c138083f --- /dev/null +++ b/www/routes/update.tsx @@ -0,0 +1,288 @@ +import { asset, Head } from "$fresh/runtime.ts"; +import { Handlers, PageProps } from "$fresh/server.ts"; +import Counter from "../islands/Counter.tsx"; +import LemonDrop from "../islands/LemonDrop.tsx"; +import Footer from "../components/Footer.tsx"; +import VERSIONS from "../../versions.json" assert { type: "json" }; +import * as FeatureIcons from "../components/FeatureIcons.tsx"; +import CopyArea from "../islands/CopyArea.tsx"; +import * as Icons from "../components/Icons.tsx"; +import Projects from "../components/Projects.tsx"; +import projects from "../data/showcase.json" assert { type: "json" }; + +export const handler: Handlers = { + GET(req) { + const accept = req.headers.get("accept"); + let path = "/docs/concepts/updating"; + if (accept && !accept.includes("text/html")) { + path = `https://deno.land/x/fresh@${VERSIONS[0]}/update.ts`; + } + return new Response(`Redirecting to ${path}`, { + headers: { "Location": path }, + status: 307, + }); + }, +}; + +const TITLE = "fresh - The next-gen web framework."; +const DESCRIPTION = + "Just in time edge rendering, island based interactivity, and no configuration TypeScript support using Deno."; + +export default function MainPage(props: PageProps) { + const ogImageUrl = new URL(asset("/home-og.png"), props.url).href; + const origin = `${props.url.protocol}//${props.url.host}`; + + return ( + <> + + {TITLE} + + + + + + + +
+ +
+ + + + +
+
+
+ + ); +} + +function Hero() { + return ( + <> + +
+ +
+ + ); +} + +function Features() { + const item = "flex md:flex-col items-center gap-5"; + const desc = "flex-1 md:text-center"; + + return ( +
+
+ +
+ Just-in-time rendering on the edge. +
+
+ +
+ +
+ Island based client hydration for maximum interactivity. +
+
+ +
+ +
+ Zero runtime overhead: no JS is shipped to the client by + default. +
+
+ +
+ +
+ No build step. +
+
+ +
+ +
+ No configuration necessary. +
+
+ +
+ +
+ TypeScript support out of the box. +
+
+
+ ); +} + +function Intro() { + return ( +
+
+
+

+ The next-gen web framework. +

+ +

+ Built for speed, reliability, and simplicity. +

+
+ + + deno is drinking fresh lemon squash + +
+ + + +

+ Fresh embraces the tried and true design of server side rendering and + progressive enhancement on the client side. +

+
+ ); +} + +function GettingStarted(props: { origin: string }) { + return ( +
+

+ + Getting Started + +

+
+
+ +
+

+ + Deno CLI + {" "} + version 1.23.0 or higher is required.{" "} + + Install + {" "} + or{" "} + + update + . +

+
+

+ To bootstrap a new project: +

+ + + {`deno run -A -r ${props.origin} my-project`} + + +

+ Enter the newly created project directory and run the following command + to start the development server: +

+ + {`deno task start`} + +

+ You can now open{" "} + + http://localhost:8000 + {" "} + in your browser to view the page. +

+

+ A more in-depth{" "} + + Getting Started + {" "} + guide is available in{" "} + the docs. +

+
+ ); +} + +const timeFmt = new Intl.DateTimeFormat("en-US", { + timeStyle: "long", + hour12: false, +}); + +function Example() { + return ( +
+

+ + Example + +

+

+ This text is being server side rendered on the fly. It was rendered at + {" "} + {timeFmt.format(new Date())}. +

+

+ The counter below was rendered on the server with a starting value of 3, + and was then hydrated on the client to provide interactivity. Try out + the buttons! +

+ +

+ Only the JS required to render that counter is sent to the client. +

+
+ ); +} + +function Showcase() { + return ( +
+

+ + Showcase + +

+

+ Below is a selection of projects that have been built with Fresh. +

+ + +
+ ); +}