feat(dev): reduce manifest merge conflict potential (#2020)
Co-authored-by: Marvin Hagemeister <marvin@deno.com>
This commit is contained in:
co-authored by
Marvin Hagemeister
parent
25470159b1
commit
536463775c
@@ -26,6 +26,7 @@ export {
|
||||
} from "https://deno.land/std@0.205.0/semver/mod.ts";
|
||||
export { emptyDir, existsSync } from "https://deno.land/std@0.205.0/fs/mod.ts";
|
||||
export * as JSONC from "https://deno.land/std@0.205.0/jsonc/mod.ts";
|
||||
export { assertEquals } from "https://deno.land/std@0.205.0/assert/mod.ts";
|
||||
|
||||
// ts-morph
|
||||
export { Node, Project } from "https://deno.land/x/ts_morph@20.0.0/mod.ts";
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
import { extname, join, normalize } from "./deps.ts";
|
||||
|
||||
/**
|
||||
* Import specifiers must have forward slashes
|
||||
*/
|
||||
function toImportSpecifier(file: string) {
|
||||
let specifier = normalize(file).replace(/\\/g, "/");
|
||||
if (!specifier.startsWith(".")) {
|
||||
specifier = "./" + specifier;
|
||||
}
|
||||
return specifier;
|
||||
}
|
||||
|
||||
// Create a valid JS identifier out of the project relative specifier.
|
||||
// Note that we only need to deal with strings that _must_ have been
|
||||
// valid file names in Windows, macOS and Linux and every identifier we
|
||||
// create here will be prefixed with at least one "$". This greatly
|
||||
// simplifies the invalid characters we have to account for.
|
||||
export function specifierToIdentifier(specifier: string, used: Set<string>) {
|
||||
specifier = specifier.replace(/^(?:\.\/routes|\.\/islands)\//, "");
|
||||
const ext = extname(specifier);
|
||||
if (ext) specifier = specifier.slice(0, -ext.length);
|
||||
|
||||
let ident = "";
|
||||
if (/^[\d]/.test(specifier)) {
|
||||
ident += "_";
|
||||
}
|
||||
ident += specifier.replace(/[\/.\(\)\[\]\s@-]/g, "_").replace(/_+/g, "_");
|
||||
|
||||
if (used.has(ident)) {
|
||||
let check = ident;
|
||||
let i = 1;
|
||||
while (used.has(check)) {
|
||||
check = `${ident}_${i++}`;
|
||||
}
|
||||
ident = check;
|
||||
}
|
||||
|
||||
used.add(ident);
|
||||
return ident;
|
||||
}
|
||||
|
||||
export interface Manifest {
|
||||
routes: string[];
|
||||
islands: string[];
|
||||
}
|
||||
|
||||
export async function generate(directory: string, manifest: Manifest) {
|
||||
const { routes, islands } = manifest;
|
||||
|
||||
// Keep track of which identifier we've already used
|
||||
const used = new Set<string>();
|
||||
|
||||
const normalizedRoutes = new Map<string, string>();
|
||||
for (let i = 0; i < routes.length; i++) {
|
||||
const file = routes[i];
|
||||
const specifier = toImportSpecifier(file);
|
||||
const identifier = specifierToIdentifier(specifier, used);
|
||||
normalizedRoutes.set(specifier, identifier);
|
||||
}
|
||||
|
||||
type islandManifest = {
|
||||
specifier: string;
|
||||
identifier: string;
|
||||
importLine: string;
|
||||
};
|
||||
const normalizedIslands: islandManifest[] = [];
|
||||
for (let i = 0; i < islands.length; i++) {
|
||||
const file = islands[i];
|
||||
const specifier = toImportSpecifier(file);
|
||||
const identifier = specifierToIdentifier(specifier, used);
|
||||
const importLine = await islandImportLine(specifier, identifier, directory);
|
||||
normalizedIslands.push({ specifier, identifier, importLine });
|
||||
}
|
||||
|
||||
const output = `// DO NOT EDIT. This file is generated by Fresh.
|
||||
// This file SHOULD be checked into source version control.
|
||||
// This file is automatically updated during development when running \`dev.ts\`.
|
||||
|
||||
${
|
||||
Array.from(normalizedRoutes.entries()).map(([specifier, identifier]) =>
|
||||
`import * as $${identifier} from "${specifier}";`
|
||||
).join(
|
||||
"\n",
|
||||
)
|
||||
}
|
||||
${
|
||||
normalizedIslands.map(({ specifier, identifier }) =>
|
||||
`import * as $$${identifier} from "${specifier}";`
|
||||
)
|
||||
.join("\n")
|
||||
}
|
||||
import { Manifest } from "$fresh/server.ts";
|
||||
|
||||
const manifest = {
|
||||
routes: {
|
||||
${
|
||||
Array.from(normalizedRoutes.entries()).map(([specifier, identifier]) =>
|
||||
`${JSON.stringify(`${specifier}`)}: $${identifier},`
|
||||
)
|
||||
.join("\n ")
|
||||
}
|
||||
},
|
||||
islands: {
|
||||
${
|
||||
normalizedIslands.map(({ specifier, importLine }) =>
|
||||
`${JSON.stringify(`${specifier}`)}: ${importLine},`
|
||||
)
|
||||
.join("\n ")
|
||||
}
|
||||
},
|
||||
baseUrl: import.meta.url,
|
||||
} satisfies Manifest;
|
||||
|
||||
export default manifest;
|
||||
`;
|
||||
|
||||
const proc = new Deno.Command(Deno.execPath(), {
|
||||
args: ["fmt", "-"],
|
||||
stdin: "piped",
|
||||
stdout: "piped",
|
||||
stderr: "null",
|
||||
}).spawn();
|
||||
|
||||
const raw = new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode(output));
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
await raw.pipeTo(proc.stdin);
|
||||
const { stdout } = await proc.output();
|
||||
|
||||
const manifestStr = new TextDecoder().decode(stdout);
|
||||
const manifestPath = join(directory, "./fresh.gen.ts");
|
||||
|
||||
await Deno.writeTextFile(manifestPath, manifestStr);
|
||||
console.log(
|
||||
`%cThe manifest has been generated for ${routes.length} routes and ${islands.length} islands.`,
|
||||
"color: blue; font-weight: bold",
|
||||
);
|
||||
}
|
||||
|
||||
async function islandImportLine(
|
||||
specifier: string,
|
||||
identifier: string,
|
||||
directory: string,
|
||||
): Promise<string> {
|
||||
const moduleURL = new URL(`file://${directory}/${specifier}`);
|
||||
const module = await import(moduleURL.href);
|
||||
const entries = Object.entries(module);
|
||||
|
||||
const allExportsAreComponents = entries.every(
|
||||
([, exportedEntity]) => typeof exportedEntity === "function",
|
||||
);
|
||||
|
||||
// if all exports are components, we can use the simple, existing form
|
||||
if (allExportsAreComponents) {
|
||||
return `$$${identifier}`;
|
||||
}
|
||||
|
||||
// if not all exports are components, list the component exports explicitly
|
||||
const componentExports = entries
|
||||
.filter(([, exportedEntity]) => typeof exportedEntity === "function")
|
||||
.map(([exportName]) => exportName);
|
||||
|
||||
const exportsString = componentExports
|
||||
.map((exp) => `${exp}: $$${identifier}.${exp}`)
|
||||
.join(", ");
|
||||
|
||||
return `{ ${exportsString} }`;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { assertEquals } from "./deps.ts";
|
||||
import { specifierToIdentifier } from "./manifest.ts";
|
||||
|
||||
const run = specifierToIdentifier;
|
||||
|
||||
Deno.test("specifierToIdentifier", () => {
|
||||
const used = new Set<string>();
|
||||
assertEquals(run("foo/bar.ts", used), "foo_bar");
|
||||
assertEquals(run("foo/bar.json.ts", used), "foo_bar_json");
|
||||
assertEquals(run("foo/[id]/bar", used), "foo_id_bar");
|
||||
assertEquals(run("foo/[...all]/bar", used), "foo_all_bar");
|
||||
assertEquals(run("foo/[[optional]]/bar", used), "foo_optional_bar");
|
||||
assertEquals(run("foo/as-df/bar", used), "foo_as_df_bar");
|
||||
assertEquals(run("foo/as@df", used), "foo_as_df");
|
||||
});
|
||||
|
||||
Deno.test("specifierToIdentifier deals with duplicates", () => {
|
||||
const used = new Set<string>();
|
||||
assertEquals(run("foo/bar", used), "foo_bar");
|
||||
assertEquals(run("foo/bar", used), "foo_bar_1");
|
||||
});
|
||||
+3
-126
@@ -1,12 +1,6 @@
|
||||
import {
|
||||
gte,
|
||||
join,
|
||||
normalize,
|
||||
relative,
|
||||
semverParse,
|
||||
walk,
|
||||
WalkEntry,
|
||||
} from "./deps.ts";
|
||||
import { gte, join, relative, semverParse, walk, WalkEntry } from "./deps.ts";
|
||||
export { generate, type Manifest } from "./manifest.ts";
|
||||
import type { Manifest } from "./manifest.ts";
|
||||
import { error } from "./error.ts";
|
||||
const MIN_DENO_VERSION = "1.31.0";
|
||||
const TEST_FILE_PATTERN = /[._]test\.(?:[tj]sx?|[mc][tj]s)$/;
|
||||
@@ -54,11 +48,6 @@ async function collectDir(
|
||||
}
|
||||
}
|
||||
|
||||
export interface Manifest {
|
||||
routes: string[];
|
||||
islands: string[];
|
||||
}
|
||||
|
||||
const GROUP_REG = /[/\\\\]\((_[^/\\\\]+)\)[/\\\\]/;
|
||||
export async function collect(
|
||||
directory: string,
|
||||
@@ -103,115 +92,3 @@ export async function collect(
|
||||
|
||||
return { routes, islands };
|
||||
}
|
||||
|
||||
/**
|
||||
* Import specifiers must have forward slashes
|
||||
*/
|
||||
function toImportSpecifier(file: string) {
|
||||
let specifier = normalize(file).replace(/\\/g, "/");
|
||||
if (!specifier.startsWith(".")) {
|
||||
specifier = "./" + specifier;
|
||||
}
|
||||
return specifier;
|
||||
}
|
||||
|
||||
async function islandImportLine(
|
||||
file: string,
|
||||
i: number,
|
||||
directory: string,
|
||||
): Promise<string> {
|
||||
const specifier = toImportSpecifier(file);
|
||||
const moduleURL = new URL(`file://${directory}/${specifier}`);
|
||||
const module = await import(moduleURL.href);
|
||||
const entries = Object.entries(module);
|
||||
|
||||
const allExportsAreComponents = entries.every(
|
||||
([, exportedEntity]) => typeof exportedEntity === "function",
|
||||
);
|
||||
|
||||
// if all exports are components, we can use the simple, existing form
|
||||
if (allExportsAreComponents) {
|
||||
return `${JSON.stringify(specifier)}: $$${i},`;
|
||||
}
|
||||
|
||||
// if not all exports are components, list the component exports explicitly
|
||||
const componentExports = entries
|
||||
.filter(([, exportedEntity]) => typeof exportedEntity === "function")
|
||||
.map(([exportName]) => exportName);
|
||||
|
||||
const exportsString = componentExports
|
||||
.map((exp) => `${exp}: $$${i}.${exp}`)
|
||||
.join(", ");
|
||||
|
||||
return `"${specifier}": { ${exportsString} },`;
|
||||
}
|
||||
|
||||
export async function generate(directory: string, manifest: Manifest) {
|
||||
const { routes, islands } = manifest;
|
||||
|
||||
const islandImports = await Promise.all(
|
||||
islands.map((file, i) => islandImportLine(file, i, directory)),
|
||||
);
|
||||
|
||||
const output = `// DO NOT EDIT. This file is generated by Fresh.
|
||||
// This file SHOULD be checked into source version control.
|
||||
// This file is automatically updated during development when running \`dev.ts\`.
|
||||
|
||||
${
|
||||
routes.map((file, i) =>
|
||||
`import * as $${i} from "${toImportSpecifier(file)}";`
|
||||
).join(
|
||||
"\n",
|
||||
)
|
||||
}
|
||||
${
|
||||
islands.map((file, i) =>
|
||||
`import * as $$${i} from "${toImportSpecifier(file)}";`
|
||||
)
|
||||
.join("\n")
|
||||
}
|
||||
import { Manifest } from "$fresh/server.ts";
|
||||
|
||||
const manifest = {
|
||||
routes: {
|
||||
${
|
||||
routes.map((file, i) =>
|
||||
`${JSON.stringify(`${toImportSpecifier(file)}`)}: $${i},`
|
||||
)
|
||||
.join("\n ")
|
||||
}
|
||||
},
|
||||
islands: {
|
||||
${islandImports.join("\n ")}
|
||||
},
|
||||
baseUrl: import.meta.url,
|
||||
} satisfies Manifest;
|
||||
|
||||
export default manifest;
|
||||
`;
|
||||
|
||||
const proc = new Deno.Command(Deno.execPath(), {
|
||||
args: ["fmt", "-"],
|
||||
stdin: "piped",
|
||||
stdout: "piped",
|
||||
stderr: "null",
|
||||
}).spawn();
|
||||
|
||||
const raw = new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode(output));
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
await raw.pipeTo(proc.stdin);
|
||||
const { stdout } = await proc.output();
|
||||
|
||||
const manifestStr = new TextDecoder().decode(stdout);
|
||||
const manifestPath = join(directory, "./fresh.gen.ts");
|
||||
|
||||
await Deno.writeTextFile(manifestPath, manifestStr);
|
||||
console.log(
|
||||
`%cThe manifest has been generated for ${routes.length} routes and ${islands.length} islands.`,
|
||||
"color: blue; font-weight: bold",
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user