feat: export compat types from /compat export (#2478)

This commit is contained in:
Luca Casonato
2024-06-03 14:32:38 +00:00
committed by GitHub
parent 2fb8606e9e
commit aa19b393e7
10 changed files with 186 additions and 143 deletions
+1
View File
@@ -4,3 +4,4 @@ vendor/
node_modules/ node_modules/
.docs/ .docs/
.DS_Store .DS_Store
tmp-*
+4 -1
View File
@@ -4,7 +4,8 @@
"exports": { "exports": {
".": "./src/mod.ts", ".": "./src/mod.ts",
"./runtime": "./src/runtime/shared.ts", "./runtime": "./src/runtime/shared.ts",
"./dev": "./src/dev/mod.ts" "./dev": "./src/dev/mod.ts",
"./compat": "./src/compat/mod.ts"
}, },
"lock": false, "lock": false,
"tasks": { "tasks": {
@@ -39,6 +40,7 @@
"@fresh/core": "./src/mod.ts", "@fresh/core": "./src/mod.ts",
"@fresh/core/dev": "./src/dev/mod.ts", "@fresh/core/dev": "./src/dev/mod.ts",
"@fresh/core/runtime": "./src/runtime/shared.ts", "@fresh/core/runtime": "./src/runtime/shared.ts",
"@fresh/core/compat": "./src/compat/mod.ts",
"@fresh/plugin-tailwind": "./plugin-tailwindcss/src/mod.ts", "@fresh/plugin-tailwind": "./plugin-tailwindcss/src/mod.ts",
"@luca/esbuild-deno-loader": "jsr:@luca/esbuild-deno-loader@^0.10.3", "@luca/esbuild-deno-loader": "jsr:@luca/esbuild-deno-loader@^0.10.3",
"@preact/signals": "npm:@preact/signals@^1.2.3", "@preact/signals": "npm:@preact/signals@^1.2.3",
@@ -71,6 +73,7 @@
"twind/": "https://esm.sh/twind@0.16.19/" "twind/": "https://esm.sh/twind@0.16.19/"
}, },
"compilerOptions": { "compilerOptions": {
"lib": ["dom", "dom.asynciterable", "deno.ns"],
"jsx": "precompile", "jsx": "precompile",
"jsxImportSource": "preact", "jsxImportSource": "preact",
"jsxPrecompileSkipElements": ["a", "img", "source", "body", "html", "head"] "jsxPrecompileSkipElements": ["a", "img", "source", "body", "html", "head"]
+1
View File
@@ -503,6 +503,7 @@ if (Deno.args.includes("build")) {
"@preact/signals": "npm:@preact/signals@^1.2.3", "@preact/signals": "npm:@preact/signals@^1.2.3",
} as Record<string, string>, } as Record<string, string>,
compilerOptions: { compilerOptions: {
lib: ["dom", "dom.asynciterable", "deno.ns"],
jsx: "react-jsx", jsx: "react-jsx",
jsxImportSource: "preact", jsxImportSource: "preact",
}, },
+13
View File
@@ -0,0 +1,13 @@
// Compat with older Fresh versions
export {
type AppProps,
defineApp,
defineLayout,
defineRoute,
type ErrorPageProps,
type Handler,
type Handlers,
type LayoutProps,
type RouteContext,
type UnknownPageProps,
} from "./server.ts";
+25 -11
View File
@@ -1,33 +1,47 @@
import type { VNode } from "preact"; import type { VNode } from "preact";
import type { FreshContext } from "../context.ts"; import type { FreshContext } from "../context.ts";
import type { HandlerByMethod } from "../handlers.ts"; import type { HandlerFn, RouteHandler } from "../handlers.ts";
/** /**
* @deprecated Use {@link FreshContext} instead * @deprecated Use {@link PageProps} instead.
*/ */
export type AppProps<_Data = unknown, T = unknown> = FreshContext<T>; export type AppProps<_Data = unknown, T = unknown> = FreshContext<T>;
/** /**
* @deprecated Use {@link FreshContext} instead * @deprecated Use {@link PageProps} instead.
*/ */
export type LayoutProps<_Data = unknown, T = unknown> = FreshContext<T>; export type LayoutProps<_Data = unknown, T = unknown> = FreshContext<T>;
/** /**
* @deprecated Use {@link FreshContext} instead * @deprecated Use {@link PageProps} instead.
*/ */
export type UnknownPageProps<_Data = unknown, T = unknown> = FreshContext<T>; export type UnknownPageProps<_Data = unknown, T = unknown> = FreshContext<T>;
/** /**
* @deprecated Use {@link FreshContext} instead * @deprecated Use {@link PageProps} instead.
*/ */
export type ErrorPageProps<_Data = unknown, T = unknown> = FreshContext<T>; export type ErrorPageProps<_Data = unknown, T = unknown> = FreshContext<T>;
/** /**
* @deprecated Use {@link FreshContext} instead * @deprecated Use {@link FreshContext} instead.
*/ */
export type RouteContext<_T = never, S = Record<string, unknown>> = export type RouteContext<_T = never, S = Record<string, unknown>> =
FreshContext<S>; FreshContext<S>;
/**
* @deprecated Use {@link RouteHandler} instead.
*/
// deno-lint-ignore no-explicit-any // deno-lint-ignore no-explicit-any
export type Handlers<T = any, State = Record<string, unknown>> = export type Handlers<T = any, State = Record<string, unknown>> = RouteHandler<
HandlerByMethod<T, State>; T,
State
>;
/**
* @deprecated Use {@link HandlerFn} instead.
*/
// deno-lint-ignore no-explicit-any
export type Handler<T = any, State = Record<string, unknown>> = HandlerFn<
T,
State
>;
function defineFn<State>( function defineFn<State>(
fn: ( fn: (
@@ -40,14 +54,14 @@ function defineFn<State>(
} }
/** /**
* @deprecated Use {@link definePage} instead * @deprecated Use {@link [../mod.ts].Define.page|define.page} instead.
*/ */
export const defineApp = defineFn; export const defineApp = defineFn;
/** /**
* @deprecated Use {@link definePage} instead * @deprecated Use {@link [../mod.ts].Define.page|define.page} instead.
*/ */
export const defineRoute = defineFn; export const defineRoute = defineFn;
/** /**
* @deprecated Use {@link definePage} instead * @deprecated Use {@link [../mod.ts].Define.page|define.page} instead.
*/ */
export const defineLayout = defineFn; export const defineLayout = defineFn;
-14
View File
@@ -18,17 +18,3 @@ export type { FreshContext, Island, PageProps } from "./context.ts";
export { createDefine, type Define } from "./define.ts"; export { createDefine, type Define } from "./define.ts";
export type { Method } from "./router.ts"; export type { Method } from "./router.ts";
export { HttpError } from "./error.ts"; export { HttpError } from "./error.ts";
// Compat with older Fresh versions
export {
type AppProps,
defineApp,
defineLayout,
defineRoute,
type ErrorPageProps,
type Handlers,
type Handlers as Handler,
type LayoutProps,
type RouteContext,
type UnknownPageProps,
} from "./compat/server.ts";
+127 -107
View File
@@ -58,8 +58,22 @@ async function updateDenoJson(
interface ImportState { interface ImportState {
core: Set<string>; core: Set<string>;
runtime: Set<string>; runtime: Set<string>;
compat: Set<string>;
} }
const compat = new Set([
"defineApp",
"defineLayout",
"defineRoute",
"AppProps",
"ErrorPageProps",
"Handler",
"Handlers",
"LayoutProps",
"RouteContext",
"UnknownPageProps",
]);
export async function updateProject(dir: string) { export async function updateProject(dir: string) {
// Update config // Update config
await updateDenoJson(dir, (config) => { await updateDenoJson(dir, (config) => {
@@ -72,30 +86,30 @@ export async function updateProject(dir: string) {
config.imports["@preact/signals"] = config.imports["@preact/signals"] =
`npm:@preact/signals@^${PREACT_SIGNALS_VERSION}`; `npm:@preact/signals@^${PREACT_SIGNALS_VERSION}`;
delete config.imports["$fresh/"]; delete config.imports["$fresh/"];
delete config.imports["@preact/signals-core"];
delete config.imports["preact-render-to-string"];
}); });
// Update routes folder // Update routes folder
const routesDir = path.join(dir, "routes"); const project = new tsmorph.Project();
if (await dirExists(routesDir)) { const sfs = project.addSourceFilesAtPaths(
const project = new tsmorph.Project(); path.join(dir, "**", "*.{js,jsx,ts,tsx}"),
const sfs = project.addSourceFilesAtPaths( );
path.join(routesDir, "**", "*.{js,jsx,ts,tsx}"), await Promise.all(sfs.map(async (sourceFile) => {
); try {
await Promise.all(sfs.map(async (sourceFile) => { return await updateFile(sourceFile);
try { } catch (err) {
return await updateFile(sourceFile); console.error(`Could not process ${sourceFile.getFilePath()}`);
} catch (err) { throw err;
console.error(`Could not process ${sourceFile.getFilePath()}`); }
throw err; }));
}
}));
}
} }
async function updateFile(sourceFile: tsmorph.SourceFile): Promise<void> { async function updateFile(sourceFile: tsmorph.SourceFile): Promise<void> {
const newImports: ImportState = { const newImports: ImportState = {
core: new Set(), core: new Set(),
runtime: new Set(), runtime: new Set(),
compat: new Set(),
}; };
const text = sourceFile.getFullText() const text = sourceFile.getFullText()
@@ -108,92 +122,98 @@ async function updateFile(sourceFile: tsmorph.SourceFile): Promise<void> {
.replaceAll('/// <reference lib="deno.ns" />\n', ""); .replaceAll('/// <reference lib="deno.ns" />\n', "");
sourceFile.replaceWithText(text); sourceFile.replaceWithText(text);
for (const [name, decl] of sourceFile.getExportedDeclarations()) { if (
if (name === "handler") { sourceFile.getFilePath().includes("/routes/") &&
const node = decl[0]; !sourceFile.getDirectoryPath().includes("/(_")
if (node.isKind(SyntaxKind.VariableDeclaration)) { ) {
const init = node.getInitializer(); for (const [name, decl] of sourceFile.getExportedDeclarations()) {
if ( if (name === "handler") {
init !== undefined && init.isKind(SyntaxKind.ObjectLiteralExpression) const node = decl[0];
) { if (node.isKind(SyntaxKind.VariableDeclaration)) {
for (const property of init.getProperties()) { const init = node.getInitializer();
if (property.isKind(SyntaxKind.MethodDeclaration)) {
const name = property.getName();
if (
name === "GET" || name === "POST" || name === "PATCH" ||
name === "PUT" || name === "DELETE"
) {
const body = property.getBody();
if (body !== undefined) {
const stmts = body.getDescendantStatements();
rewriteCtxMethods(stmts);
}
maybePrependReqVar(property, newImports, true);
}
} else if (property.isKind(SyntaxKind.PropertyAssignment)) {
const init = property.getInitializer();
if (
init !== undefined &&
(init.isKind(SyntaxKind.ArrowFunction) ||
init.isKind(SyntaxKind.FunctionExpression))
) {
const body = init.getBody();
if (body !== undefined) {
const stmts = body.getDescendantStatements();
rewriteCtxMethods(stmts);
}
maybePrependReqVar(init, newImports, true);
}
}
}
}
} else if (node.isKind(SyntaxKind.FunctionDeclaration)) {
const body = node.getBody();
if (body !== undefined) {
const stmts = body.getDescendantStatements();
rewriteCtxMethods(stmts);
}
maybePrependReqVar(node, newImports, false);
}
} else if (name === "default" && decl.length > 0) {
const caller = decl[0];
if (caller.isKind(SyntaxKind.CallExpression)) {
const expr = caller.getExpression();
if (expr.isKind(SyntaxKind.Identifier)) {
const text = expr.getText();
if ( if (
text === "defineApp" || text === "defineLayout" || init !== undefined &&
text === "defineRoute" init.isKind(SyntaxKind.ObjectLiteralExpression)
) { ) {
const args = caller.getArguments(); for (const property of init.getProperties()) {
if (args.length > 0) { if (property.isKind(SyntaxKind.MethodDeclaration)) {
const first = args[0]; const name = property.getName();
if ( if (
first.isKind(SyntaxKind.ArrowFunction) || name === "GET" || name === "POST" || name === "PATCH" ||
first.isKind(SyntaxKind.FunctionExpression) name === "PUT" || name === "DELETE"
) { ) {
const body = first.getBody(); const body = property.getBody();
if (body !== undefined) { if (body !== undefined) {
const stmts = body.getDescendantStatements(); const stmts = body.getDescendantStatements();
rewriteCtxMethods(stmts); rewriteCtxMethods(stmts);
} }
maybePrependReqVar(first, newImports, false); maybePrependReqVar(property, newImports, true);
}
} else if (property.isKind(SyntaxKind.PropertyAssignment)) {
const init = property.getInitializer();
if (
init !== undefined &&
(init.isKind(SyntaxKind.ArrowFunction) ||
init.isKind(SyntaxKind.FunctionExpression))
) {
const body = init.getBody();
if (body !== undefined) {
const stmts = body.getDescendantStatements();
rewriteCtxMethods(stmts);
}
maybePrependReqVar(init, newImports, true);
}
} }
} }
} }
} } else if (node.isKind(SyntaxKind.FunctionDeclaration)) {
} else if (caller.isKind(SyntaxKind.FunctionDeclaration)) { const body = node.getBody();
const body = caller.getBody(); if (body !== undefined) {
if (body !== undefined) { const stmts = body.getDescendantStatements();
const stmts = body.getDescendantStatements(); rewriteCtxMethods(stmts);
rewriteCtxMethods(stmts); }
}
maybePrependReqVar(caller, newImports, false); maybePrependReqVar(node, newImports, false);
}
} else if (name === "default" && decl.length > 0) {
const caller = decl[0];
if (caller.isKind(SyntaxKind.CallExpression)) {
const expr = caller.getExpression();
if (expr.isKind(SyntaxKind.Identifier)) {
const text = expr.getText();
if (
text === "defineApp" || text === "defineLayout" ||
text === "defineRoute"
) {
const args = caller.getArguments();
if (args.length > 0) {
const first = args[0];
if (
first.isKind(SyntaxKind.ArrowFunction) ||
first.isKind(SyntaxKind.FunctionExpression)
) {
const body = first.getBody();
if (body !== undefined) {
const stmts = body.getDescendantStatements();
rewriteCtxMethods(stmts);
}
maybePrependReqVar(first, newImports, false);
}
}
}
}
} else if (caller.isKind(SyntaxKind.FunctionDeclaration)) {
const body = caller.getBody();
if (body !== undefined) {
const stmts = body.getDescendantStatements();
rewriteCtxMethods(stmts);
}
maybePrependReqVar(caller, newImports, false);
}
} }
} }
} }
@@ -215,8 +235,10 @@ async function updateFile(sourceFile: tsmorph.SourceFile): Promise<void> {
for (const n of d.getNamedImports()) { for (const n of d.getNamedImports()) {
const name = n.getName(); const name = n.getName();
if (newImports.core.has(name)) { newImports.core.delete(name);
newImports.core.delete(name); if (compat.has(name)) {
n.remove();
newImports.compat.add(name);
} }
} }
if (newImports.core.size > 0) { if (newImports.core.size > 0) {
@@ -224,15 +246,15 @@ async function updateFile(sourceFile: tsmorph.SourceFile): Promise<void> {
d.addNamedImport(name); d.addNamedImport(name);
}); });
} }
removeEmptyImport(d);
} else if (specifier === "$fresh/runtime.ts") { } else if (specifier === "$fresh/runtime.ts") {
hasRuntimeImport = true; hasRuntimeImport = true;
d.setModuleSpecifier("@fresh/core/runtime"); d.setModuleSpecifier("@fresh/core/runtime");
for (const n of d.getNamedImports()) { for (const n of d.getNamedImports()) {
const name = n.getName(); const name = n.getName();
if (newImports.runtime.has(name)) { newImports.runtime.delete(name);
newImports.runtime.delete(name);
}
} }
if (newImports.runtime.size > 0) { if (newImports.runtime.size > 0) {
newImports.runtime.forEach((name) => { newImports.runtime.forEach((name) => {
@@ -256,6 +278,12 @@ async function updateFile(sourceFile: tsmorph.SourceFile): Promise<void> {
namedImports: Array.from(newImports.core), namedImports: Array.from(newImports.core),
}); });
} }
if (newImports.compat.size > 0) {
sourceFile.addImportDeclaration({
moduleSpecifier: "@fresh/core/compat",
namedImports: Array.from(newImports.compat),
});
}
await sourceFile.save(); await sourceFile.save();
await format(sourceFile.getFilePath()); await format(sourceFile.getFilePath());
@@ -436,11 +464,3 @@ function rewriteCtxMemberName(
rewriteCtxMemberName(children[0]); rewriteCtxMemberName(children[0]);
} }
} }
async function dirExists(dir: string): Promise<boolean> {
try {
return (await Deno.stat(dir)).isDirectory;
} catch (_) {
return false;
}
}
+11 -8
View File
@@ -254,7 +254,7 @@ export const handler: Handlers = {
const files = await readFiles(dir); const files = await readFiles(dir);
expect(files["/routes/index.tsx"]) expect(files["/routes/index.tsx"])
.toEqual(`import { Handlers } from "@fresh/core"; .toEqual(`import { Handlers } from "@fresh/core/compat";
export const handler: Handlers = { export const handler: Handlers = {
async GET(ctx) { async GET(ctx) {
@@ -274,7 +274,7 @@ export const handler: Handlers = {
}, },
};`); };`);
expect(files["/routes/foo.tsx"]) expect(files["/routes/foo.tsx"])
.toEqual(`import { Handlers } from "@fresh/core"; .toEqual(`import { Handlers } from "@fresh/core/compat";
export const handler: Handlers = { export const handler: Handlers = {
async GET(ctx) {}, async GET(ctx) {},
@@ -285,7 +285,7 @@ export const handler: Handlers = {
};`); };`);
expect(files["/routes/name.tsx"]) expect(files["/routes/name.tsx"])
.toEqual(`import { Handlers } from "@fresh/core"; .toEqual(`import { Handlers } from "@fresh/core/compat";
export const handler: Handlers = { export const handler: Handlers = {
async GET(ctx) { async GET(ctx) {
@@ -305,7 +305,7 @@ export const handler: Handlers = {
}, },
};`); };`);
expect(files["/routes/name-unused.tsx"]) expect(files["/routes/name-unused.tsx"])
.toEqual(`import { Handlers } from "@fresh/core"; .toEqual(`import { Handlers } from "@fresh/core/compat";
export const handler: Handlers = { export const handler: Handlers = {
async GET(ctx) {}, async GET(ctx) {},
@@ -425,7 +425,7 @@ export const handler: Handlers = {
await updateProject(dir); await updateProject(dir);
const files = await readFiles(dir); const files = await readFiles(dir);
expect(files["/routes/index.tsx"]) expect(files["/routes/index.tsx"])
.toEqual(`import { Handlers } from "@fresh/core"; .toEqual(`import { Handlers } from "@fresh/core/compat";
export const handler: Handlers = { export const handler: Handlers = {
async GET({ params, render, info, req }) { async GET({ params, render, info, req }) {
@@ -470,21 +470,24 @@ export default defineRoute(async (req, ctx) => {
const files = await readFiles(dir); const files = await readFiles(dir);
expect(files["/routes/_app.tsx"]) expect(files["/routes/_app.tsx"])
.toEqual(`import { defineApp } from "@fresh/core"; .toEqual(`import { defineApp } from "@fresh/core/compat";
export default defineApp(async (ctx) => { export default defineApp(async (ctx) => {
const req = ctx.req; const req = ctx.req;
return null; return null;
});`); });`);
expect(files["/routes/_layout.tsx"]) expect(files["/routes/_layout.tsx"])
.toEqual(`import { defineLayout } from "@fresh/core"; .toEqual(`import { defineLayout } from "@fresh/core/compat";
export default defineLayout(async (ctx) => { export default defineLayout(async (ctx) => {
const req = ctx.req; const req = ctx.req;
return null; return null;
});`); });`);
expect(files["/routes/foo.tsx"]) expect(files["/routes/foo.tsx"])
.toEqual(`import { defineRoute } from "@fresh/core"; .toEqual(`import { defineRoute } from "@fresh/core/compat";
export default defineRoute(async (ctx) => { export default defineRoute(async (ctx) => {
const req = ctx.req; const req = ctx.req;
+2
View File
@@ -13,6 +13,7 @@
"@fresh/core": "../src/mod.ts", "@fresh/core": "../src/mod.ts",
"@fresh/core/dev": "../src/dev/mod.ts", "@fresh/core/dev": "../src/dev/mod.ts",
"@fresh/core/runtime": "../src/runtime/shared.ts", "@fresh/core/runtime": "../src/runtime/shared.ts",
"@fresh/core/compat": "../src/compat/mod.ts",
"@fresh/plugin-tailwind": "../plugin-tailwindcss/src/mod.ts", "@fresh/plugin-tailwind": "../plugin-tailwindcss/src/mod.ts",
"@luca/esbuild-deno-loader": "jsr:@luca/esbuild-deno-loader@^0.10.3", "@luca/esbuild-deno-loader": "jsr:@luca/esbuild-deno-loader@^0.10.3",
"@preact/signals": "npm:@preact/signals@^1.2.3", "@preact/signals": "npm:@preact/signals@^1.2.3",
@@ -37,6 +38,7 @@
"tailwindcss/plugin": "npm:/tailwindcss@3.4.1/plugin.js" "tailwindcss/plugin": "npm:/tailwindcss@3.4.1/plugin.js"
}, },
"compilerOptions": { "compilerOptions": {
"lib": ["dom", "dom.asynciterable", "deno.ns"],
"jsx": "precompile", "jsx": "precompile",
"jsxImportSource": "preact", "jsxImportSource": "preact",
"jsxPrecompileSkipElements": ["a", "img", "source", "body", "html", "head"] "jsxPrecompileSkipElements": ["a", "img", "source", "body", "html", "head"]
+2 -2
View File
@@ -1,6 +1,6 @@
import type { Handler } from "@fresh/core"; import type { Handlers } from "@fresh/core/compat";
export const handler: Handler<void> = { export const handler: Handlers<void> = {
GET(ctx) { GET(ctx) {
const slug = ctx.params.slug; const slug = ctx.params.slug;