forked from deco-cx/deco
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dev.ts
executable file
·166 lines (147 loc) · 4.52 KB
/
dev.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
import { setupGithooks } from "https://deno.land/x/[email protected]/githooks.ts";
import { dirname, fromFileUrl, join } from "std/path/mod.ts";
import { gte, parse } from "std/semver/mod.ts";
import { ResolverMap } from "./engine/core/resolver.ts";
import { ManifestBuilder } from "./engine/manifest/manifestBuilder.ts";
import { decoManifestBuilder } from "./engine/manifest/manifestGen.ts";
import { context } from "./live.ts";
import { DecoManifest } from "./types.ts";
import { namespaceFromSiteJson, updateImportMap } from "./utils/namespace.ts";
export { format } from "./utils/formatter.ts";
/**
* Ensures that the target function runs only once per `deno task start`, in other words the watcher will not trigger the function again.
*/
const oncePerRun = (
f: () => Promise<void>,
) => {
const key = `LIVE_RUN_${f.name}`;
if (Deno.env.has(key)) {
return;
}
f().finally(() => {
Deno.env.set(key, "true");
});
};
const MIN_DENO_VERSION = parse("1.32.2");
export function ensureMinDenoVersion() {
// Check that the minimum supported Deno version is being used.
if (!gte(parse(Deno.version.deno), MIN_DENO_VERSION)) {
let message =
`Deno version ${MIN_DENO_VERSION} or higher is required. Please update Deno.\n\n`;
if (Deno.execPath().includes("homebrew")) {
message +=
"You seem to have installed Deno via homebrew. To update, run: `brew upgrade deno`\n";
} else {
message += "To update, run: `deno upgrade`\n";
}
console.error(message);
}
}
const manifestFile = "./live.gen.ts";
export async function generate(
directory: string,
manifest: ManifestBuilder,
) {
const fmt = new Deno.Command(Deno.execPath(), {
args: ["fmt", "-"],
stdin: "piped",
stdout: "piped",
stderr: "null",
});
const proc = fmt.spawn();
const raw = new ReadableStream({
start(controller) {
controller.enqueue(new TextEncoder().encode(manifest.build()));
controller.close();
},
});
await raw.pipeTo(proc.stdin);
const out = await proc.output();
await proc.status;
proc.unref();
const manifestStr = new TextDecoder().decode(out.stdout);
const manifestPath = join(directory, manifestFile);
await Deno.writeTextFile(manifestPath, manifestStr);
console.log(
`%cthe manifest has been generated.`,
"color: blue; font-weight: bold",
);
}
export const siteJSON = "site.json";
const importManifests = (manifests: string[]): Promise<
Array<
DecoManifest | (DecoManifest & Partial<Record<string, ResolverMap>>)
>
> => {
return Promise.all(
manifests.map(async (manifest) => (await import(manifest)).default),
);
};
const getAndUpdateNamespace = async (
dir: string,
): Promise<string | undefined> => {
const ns = await namespaceFromSiteJson(dir);
ns && oncePerRun(async function importMapUpdate() {
await updateImportMap(dir, ns);
});
return ns;
};
export default async function dev(
base: string,
entrypoint: string,
{
imports = [],
onListen,
injectRoutes = true,
}: {
injectRoutes?: boolean;
imports?:
| Array<string>
| Array<
DecoManifest | (DecoManifest & Partial<Record<string, ResolverMap>>)
>
| Record<
string,
DecoManifest | (DecoManifest & Partial<Record<string, ResolverMap>>)
>;
onListen?: () => void;
} = {},
) {
const dir = dirname(fromFileUrl(base));
const ns = await getAndUpdateNamespace(dir) ?? base;
context.namespace = ns;
ensureMinDenoVersion();
entrypoint = new URL(entrypoint, base).href;
let manifest = await decoManifestBuilder(dir, ns, { injectRoutes });
manifest = manifest.mergeWith(
isDyamicImportArray(imports)
? await importManifests(imports)
: typeof imports === "object"
? Object.values(imports)
: imports,
);
oncePerRun(setupGithooks);
await generate(dir, manifest);
onListen?.();
await import(entrypoint);
}
function isDyamicImportArray(
imports:
| string[]
| (DecoManifest | (DecoManifest & Partial<Record<string, ResolverMap>>))[]
| Record<
string,
DecoManifest | (DecoManifest & Partial<Record<string, ResolverMap>>)
>,
): imports is string[] {
return Array.isArray(imports) && imports.length > 0 &&
typeof imports[0] === "string";
}
// Generate live own manifest data so that other sites can import native functions and sections.
export const liveNs = "$live";
if (import.meta.main) {
context.namespace = liveNs;
const dir = Deno.cwd();
const newManifestData = await decoManifestBuilder(dir, liveNs);
await generate(dir, newManifestData);
}