@slotform/vite 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts ADDED
@@ -0,0 +1,307 @@
1
+ import { createRequire } from "node:module";
2
+ import { dirname, join } from "node:path";
3
+ import { api } from "@slotform/api";
4
+ import { GENERATED_DIR, plugin, slot } from "@slotform/cli";
5
+ import type { TsExpression, TsImportSpec } from "@slotform/cli/ast";
6
+ import { cliSlots, emitArtifact } from "@slotform/cli/cli-slots";
7
+ import { SlotformError } from "@slotform/cli/errors";
8
+ import { z } from "zod";
9
+ import { renderViteConfig } from "./node/codegen.ts";
10
+ import { headerKey, mergeClientHeader } from "./node/csp.ts";
11
+ import {
12
+ type AppPlugin,
13
+ type ServerProxyEntry,
14
+ type ViteOptions,
15
+ viteOptionsSchema,
16
+ } from "./types.ts";
17
+
18
+ const SOURCE = "vite";
19
+
20
+ const viteManifestSchema = z.object({ bin: z.object({ vite: z.string() }) });
21
+
22
+ // The consumer's own vite: docs/architecture/plugins/vite.md, "How it works".
23
+ function viteBin(cwd: string): string {
24
+ const consumer = createRequire(join(cwd, "package.json"));
25
+ let manifest: string;
26
+ try {
27
+ manifest = consumer.resolve("vite/package.json");
28
+ } catch (err) {
29
+ if (
30
+ !(err instanceof Error && "code" in err) ||
31
+ err.code !== "MODULE_NOT_FOUND"
32
+ )
33
+ throw err;
34
+ throw new SlotformError(
35
+ "vite is not installed in this app: run `pnpm install` (vite is in its devDependencies), then retry.",
36
+ "VITE_NOT_INSTALLED",
37
+ );
38
+ }
39
+ return join(
40
+ dirname(manifest),
41
+ viteManifestSchema.parse(consumer(manifest)).bin.vite,
42
+ );
43
+ }
44
+
45
+ // Sort config imports by source so the emitted vite.config.ts order is
46
+ // independent of `config.plugins` array order.
47
+ const configImports = slot.list<TsImportSpec>({
48
+ source: SOURCE,
49
+ name: "configImports",
50
+ sortBy: (a, b) => a.source.localeCompare(b.source),
51
+ });
52
+
53
+ // Plugin call order: docs/architecture/plugins/vite.md, "How it works".
54
+ function pluginCallName(expr: TsExpression): string {
55
+ if (expr.kind === "call" && expr.callee.kind === "identifier") {
56
+ return expr.callee.name;
57
+ }
58
+ return "";
59
+ }
60
+ const pluginCalls = slot.list<TsExpression>({
61
+ source: SOURCE,
62
+ name: "pluginCalls",
63
+ sortBy: (a, b) => pluginCallName(a).localeCompare(pluginCallName(b)),
64
+ });
65
+
66
+ // App-only plugin calls: docs/architecture/plugins/vite.md, "App-only plugin calls".
67
+ const appPlugins = slot.list<AppPlugin>({
68
+ source: SOURCE,
69
+ name: "appPlugins",
70
+ });
71
+
72
+ const resolveAliases = slot.list<{ find: string; replacement: string }>({
73
+ source: SOURCE,
74
+ name: "resolveAliases",
75
+ // `find` is the key in the emitted Vite `resolve.alias` object; two
76
+ // contributions with the same `find` would silently overwrite when the
77
+ // TS object literal is rendered. Fail loudly at compose time instead.
78
+ uniqueBy: (a) => a.find,
79
+ });
80
+
81
+ // Dedupe: docs/architecture/plugins/vite.md, "Singletons and the optimizer".
82
+ const resolveDedupe = slot.list<string>({
83
+ source: SOURCE,
84
+ name: "resolveDedupe",
85
+ sortBy: (a, b) => a.localeCompare(b),
86
+ });
87
+
88
+ // Exclude and include: docs/architecture/plugins/vite.md, "Singletons and the optimizer".
89
+ const optimizeExclude = slot.list<string>({
90
+ source: SOURCE,
91
+ name: "optimizeExclude",
92
+ sortBy: (a, b) => a.localeCompare(b),
93
+ });
94
+
95
+ const devServerPort = slot.value<number, ViteOptions>({
96
+ source: SOURCE,
97
+ name: "devServerPort",
98
+ seed: (ctx) => {
99
+ return ctx.options.port ?? 3000;
100
+ },
101
+ });
102
+
103
+ // Dev server proxy: docs/architecture/plugins/vite.md, "Dev server proxy, file access and watching".
104
+ const serverProxy = slot.list<ServerProxyEntry>({
105
+ source: SOURCE,
106
+ name: "serverProxy",
107
+ sortBy: (a, b) => a.path.localeCompare(b.path),
108
+ // `path` is the key in the emitted `server.proxy` object; duplicates
109
+ // would silently overwrite when rendered. Fail loudly at compose time.
110
+ uniqueBy: (e) => e.path,
111
+ });
112
+
113
+ // File access: docs/architecture/plugins/vite.md, "Dev server proxy, file access and watching".
114
+ const fsAllow = slot.list<TsExpression>({
115
+ source: SOURCE,
116
+ name: "fsAllow",
117
+ });
118
+
119
+ // Watching: docs/architecture/plugins/vite.md, "Dev server proxy, file access and watching".
120
+ const watchIgnored = slot.list<string>({
121
+ source: SOURCE,
122
+ name: "watchIgnored",
123
+ sortBy: (a, b) => a.localeCompare(b),
124
+ });
125
+
126
+ // Build output directory: docs/architecture/plugins/vite.md, "Lifecycle contributions".
127
+ const outDir = slot.value<string | null>({
128
+ source: SOURCE,
129
+ name: "outDir",
130
+ seed: () => null,
131
+ });
132
+
133
+ // Client headers: docs/architecture/slot-catalog.md, "`vite.slots.*` (the `vite` plugin)".
134
+ const clientHeaders = slot.map<string>({
135
+ source: SOURCE,
136
+ name: "clientHeaders",
137
+ keyOf: headerKey,
138
+ merge: mergeClientHeader,
139
+ });
140
+
141
+ // Null without an `outDir`, or with no plugin call, import or app-only call,
142
+ // so a vite-less config never writes an empty file.
143
+ const viteConfig = slot.derived({
144
+ source: SOURCE,
145
+ name: "viteConfig",
146
+ inputs: {
147
+ configImports,
148
+ pluginCalls,
149
+ appPlugins,
150
+ resolveAliases,
151
+ resolveDedupe,
152
+ optimizeExclude,
153
+ devServerPort,
154
+ outDir,
155
+ serverProxy,
156
+ fsAllow,
157
+ watchIgnored,
158
+ clientHeaders,
159
+ },
160
+ compute: (inp): string | null => {
161
+ if (inp.outDir === null) return null;
162
+ if (
163
+ inp.pluginCalls.length === 0 &&
164
+ inp.configImports.length === 0 &&
165
+ inp.appPlugins.length === 0
166
+ )
167
+ return null;
168
+ const { appPlugins: app, ...values } = inp;
169
+ return renderViteConfig({
170
+ ...values,
171
+ outDir: inp.outDir,
172
+ configImports: [
173
+ ...inp.configImports,
174
+ ...app.flatMap((a) => a.imports),
175
+ ].sort((a, b) => a.source.localeCompare(b.source)),
176
+ pluginCalls: [...app.map((a) => a.call), ...inp.pluginCalls],
177
+ });
178
+ },
179
+ });
180
+
181
+ export const vite = plugin("vite", {
182
+ // The consumer runs vite: its generated config imports it and the dev
183
+ // process and the build step run its bin.
184
+ devDependencies: {
185
+ vite: "^8.3.8",
186
+ },
187
+ label: "Vite",
188
+
189
+ schema: viteOptionsSchema,
190
+
191
+ slots: {
192
+ configImports,
193
+ pluginCalls,
194
+ appPlugins,
195
+ resolveAliases,
196
+ resolveDedupe,
197
+ optimizeExclude,
198
+ devServerPort,
199
+ outDir,
200
+ serverProxy,
201
+ fsAllow,
202
+ watchIgnored,
203
+ clientHeaders,
204
+ viteConfig,
205
+ },
206
+
207
+ contributes: (self) => [
208
+ self.slots.outDir.contribute(() => "dist/client"),
209
+
210
+ // No Slotform app is framed: `frame-ancestors` is the standard, and
211
+ // `X-Frame-Options` covers a browser without it.
212
+ self.slots.clientHeaders.contribute(() => ({
213
+ "Content-Security-Policy": "frame-ancestors 'none'",
214
+ "X-Frame-Options": "DENY",
215
+ })),
216
+
217
+ self.slots.configImports.contribute(
218
+ (): TsImportSpec => ({
219
+ source: "@slotform/vite/preset",
220
+ named: ["excludedImportsPlugin", "providersPlugin", "schemaPlugin"],
221
+ }),
222
+ ),
223
+ self.slots.pluginCalls.contribute(
224
+ (): TsExpression => ({
225
+ kind: "call",
226
+ callee: { kind: "identifier", name: "providersPlugin" },
227
+ args: [],
228
+ }),
229
+ ),
230
+ self.slots.pluginCalls.contribute(
231
+ (): TsExpression => ({
232
+ kind: "call",
233
+ callee: { kind: "identifier", name: "schemaPlugin" },
234
+ args: [],
235
+ }),
236
+ ),
237
+ // The optimizer bundles what an excluded package imports (`excludedImportsPlugin`).
238
+ self.slots.pluginCalls.contribute(
239
+ (): TsExpression => ({
240
+ kind: "call",
241
+ callee: { kind: "identifier", name: "excludedImportsPlugin" },
242
+ args: [],
243
+ }),
244
+ ),
245
+
246
+ // Dev CORS origin: docs/architecture/plugins/api.md, "CORS and origins".
247
+ // The predicate is `!== undefined`, so `app.origins: []` stays a lockdown.
248
+ api.slots.devCorsOrigins.contribute(async (ctx) => {
249
+ if (ctx.app.origins !== undefined) return undefined;
250
+ const port = await ctx.resolve(self.slots.devServerPort);
251
+ return `http://localhost:${port}`;
252
+ }),
253
+
254
+ emitArtifact(`${GENERATED_DIR}/vite.config.ts`, self.slots.viteConfig),
255
+
256
+ // Dev process: docs/architecture/plugins/vite.md, "Dev server port".
257
+ cliSlots.devProcesses.contribute(async (ctx) => {
258
+ const port = await ctx.resolve(self.slots.devServerPort);
259
+ const opts = self.options;
260
+ return {
261
+ name: "vite",
262
+ command: process.execPath,
263
+ args: [
264
+ viteBin(ctx.cwd),
265
+ "dev",
266
+ "--config",
267
+ `${GENERATED_DIR}/vite.config.ts`,
268
+ ],
269
+ defaultPort: port,
270
+ readyPattern: /Local:/,
271
+ // Default `restart: "never"` — Vite handles HMR; auto-restart
272
+ // on crash usually hides the real failure. Consumer can opt in.
273
+ restart: opts.restart ?? "never",
274
+ maxRestarts: opts.maxRestarts,
275
+ // Use the supervisor's default EADDRINUSE pattern. Explicitly
276
+ // returns `undefined` rather than relying on implicit-void
277
+ // because `() => void` isn't assignable to the spec's
278
+ // `() => { restart: boolean } | undefined` under strict TS.
279
+ onExit: (event) => {
280
+ if (!event.portInUse) return undefined;
281
+ const detected = event.detectedPort ?? port;
282
+ ctx.log.error(
283
+ `vite dev: port :${detected} is in use — set \`vite({ port: ... })\` in slotform.config.ts or stop the process holding it.`,
284
+ );
285
+ return undefined;
286
+ },
287
+ };
288
+ }),
289
+
290
+ // Build step: docs/architecture/plugins/vite.md, "Lifecycle contributions".
291
+ cliSlots.buildSteps.contribute((ctx) => ({
292
+ name: "vite-build",
293
+ phase: "main",
294
+ exec: {
295
+ command: process.execPath,
296
+ args: [
297
+ viteBin(ctx.cwd),
298
+ "build",
299
+ "--config",
300
+ `${GENERATED_DIR}/vite.config.ts`,
301
+ ],
302
+ },
303
+ })),
304
+ ],
305
+ });
306
+
307
+ export type { AppPlugin, ServerProxyEntry, ViteOptions } from "./types.ts";
@@ -0,0 +1,264 @@
1
+ import { posix } from "node:path";
2
+ import {
3
+ dedupeImports,
4
+ renderTsSourceFile,
5
+ type TsExpression,
6
+ type TsImportSpec,
7
+ type TsSourceFile,
8
+ } from "@slotform/cli/ast";
9
+ import type { ViteConfigValues } from "../types.ts";
10
+
11
+ // Renders a Vite config module from the resolved `vite.slots.*` values: docs/architecture/plugins/vite.md, "How it works".
12
+ export function renderViteConfig(values: ViteConfigValues): string {
13
+ const imports: TsImportSpec[] = dedupeImports([
14
+ { source: "node:url", named: ["fileURLToPath"] },
15
+ {
16
+ source: "vite",
17
+ named:
18
+ values.fsAllow.length > 0
19
+ ? ["defineConfig", "searchForWorkspaceRoot"]
20
+ : ["defineConfig"],
21
+ },
22
+ ...values.configImports,
23
+ ]);
24
+
25
+ const configProps: Array<{
26
+ key: string;
27
+ value: TsExpression;
28
+ shorthand?: boolean;
29
+ }> = [
30
+ {
31
+ key: "root",
32
+ value: {
33
+ kind: "call",
34
+ callee: { kind: "identifier", name: "fileURLToPath" },
35
+ args: [
36
+ {
37
+ kind: "new",
38
+ callee: { kind: "identifier", name: "URL" },
39
+ args: [
40
+ { kind: "string", value: "." },
41
+ {
42
+ kind: "member",
43
+ object: { kind: "identifier", name: "import.meta" },
44
+ property: "url",
45
+ },
46
+ ],
47
+ },
48
+ ],
49
+ },
50
+ },
51
+ { key: "publicDir", value: { kind: "string", value: "../public" } },
52
+ {
53
+ key: "build",
54
+ value: {
55
+ kind: "object",
56
+ properties: [
57
+ {
58
+ key: "outDir",
59
+ value: { kind: "string", value: posix.join("..", values.outDir) },
60
+ },
61
+ { key: "emptyOutDir", value: { kind: "boolean", value: true } },
62
+ ],
63
+ },
64
+ },
65
+ {
66
+ key: "plugins",
67
+ value: { kind: "array", items: values.pluginCalls },
68
+ },
69
+ ];
70
+
71
+ const serverProps: Array<{ key: string; value: TsExpression }> = [];
72
+ if (values.devServerPort > 0) {
73
+ serverProps.push({
74
+ key: "port",
75
+ value: { kind: "number", value: values.devServerPort },
76
+ });
77
+ }
78
+ if (values.serverProxy.length > 0) {
79
+ serverProps.push({
80
+ key: "proxy",
81
+ value: {
82
+ kind: "object",
83
+ properties: values.serverProxy.map((entry) => ({
84
+ key: entry.path,
85
+ value: {
86
+ kind: "object",
87
+ properties: [
88
+ {
89
+ key: "target",
90
+ value: { kind: "string", value: entry.target },
91
+ },
92
+ ...(entry.ws
93
+ ? [
94
+ {
95
+ key: "ws" as const,
96
+ value: { kind: "boolean" as const, value: true },
97
+ },
98
+ ]
99
+ : []),
100
+ ],
101
+ },
102
+ })),
103
+ },
104
+ });
105
+ }
106
+ const headerNames = Object.keys(values.clientHeaders).sort();
107
+ if (headerNames.length > 0) {
108
+ serverProps.push({
109
+ key: "headers",
110
+ value: {
111
+ kind: "object",
112
+ properties: headerNames.map((name) => ({
113
+ key: name,
114
+ value: {
115
+ kind: "string",
116
+ // `name` is a key just read from the object; the index read types it possibly undefined.
117
+ value: values.clientHeaders[name] as string,
118
+ },
119
+ })),
120
+ },
121
+ });
122
+ }
123
+ if (values.fsAllow.length > 0) {
124
+ serverProps.push({
125
+ key: "fs",
126
+ value: {
127
+ kind: "object",
128
+ properties: [
129
+ {
130
+ key: "allow",
131
+ value: {
132
+ kind: "array",
133
+ items: [
134
+ {
135
+ kind: "call",
136
+ callee: {
137
+ kind: "identifier",
138
+ name: "searchForWorkspaceRoot",
139
+ },
140
+ args: [
141
+ {
142
+ kind: "call",
143
+ callee: {
144
+ kind: "member",
145
+ object: { kind: "identifier", name: "process" },
146
+ property: "cwd",
147
+ },
148
+ args: [],
149
+ },
150
+ ],
151
+ },
152
+ ...values.fsAllow,
153
+ ],
154
+ },
155
+ },
156
+ ],
157
+ },
158
+ });
159
+ }
160
+ const watchIgnored = [...new Set(values.watchIgnored)];
161
+ if (watchIgnored.length > 0) {
162
+ serverProps.push({
163
+ key: "watch",
164
+ value: {
165
+ kind: "object",
166
+ properties: [
167
+ {
168
+ key: "ignored",
169
+ value: {
170
+ kind: "array",
171
+ items: watchIgnored.map((glob) => ({
172
+ kind: "string",
173
+ value: glob,
174
+ })),
175
+ },
176
+ },
177
+ ],
178
+ },
179
+ });
180
+ }
181
+ if (serverProps.length > 0) {
182
+ configProps.push({
183
+ key: "server",
184
+ value: { kind: "object", properties: serverProps },
185
+ });
186
+ }
187
+
188
+ const resolveProps: Array<{ key: string; value: TsExpression }> = [];
189
+ if (values.resolveAliases.length > 0) {
190
+ resolveProps.push({
191
+ key: "alias",
192
+ value: {
193
+ kind: "object",
194
+ properties: values.resolveAliases.map((a) => ({
195
+ key: a.find,
196
+ value: { kind: "string", value: a.replacement },
197
+ })),
198
+ },
199
+ });
200
+ }
201
+ const dedupe = [...new Set(values.resolveDedupe)];
202
+ if (dedupe.length > 0) {
203
+ resolveProps.push({
204
+ key: "dedupe",
205
+ value: {
206
+ kind: "array",
207
+ items: dedupe.map((specifier) => ({
208
+ kind: "string",
209
+ value: specifier,
210
+ })),
211
+ },
212
+ });
213
+ }
214
+ if (resolveProps.length > 0) {
215
+ configProps.push({
216
+ key: "resolve",
217
+ value: { kind: "object", properties: resolveProps },
218
+ });
219
+ }
220
+ // `.tsx` optimizer extension: docs/architecture/plugins/vite.md, "Singletons and the optimizer".
221
+ const exclude = [...new Set(values.optimizeExclude)];
222
+ configProps.push({
223
+ key: "optimizeDeps",
224
+ value: {
225
+ kind: "object",
226
+ properties: [
227
+ {
228
+ key: "extensions",
229
+ value: { kind: "array", items: [{ kind: "string", value: ".tsx" }] },
230
+ },
231
+ ...(exclude.length > 0
232
+ ? [
233
+ {
234
+ key: "exclude",
235
+ value: {
236
+ kind: "array" as const,
237
+ items: exclude.map((name) => ({
238
+ kind: "string" as const,
239
+ value: name,
240
+ })),
241
+ },
242
+ },
243
+ ]
244
+ : []),
245
+ ],
246
+ },
247
+ });
248
+
249
+ const spec: TsSourceFile = {
250
+ imports,
251
+ statements: [
252
+ {
253
+ kind: "export-default",
254
+ value: {
255
+ kind: "call",
256
+ callee: { kind: "identifier", name: "defineConfig" },
257
+ args: [{ kind: "object", properties: configProps }],
258
+ },
259
+ },
260
+ ],
261
+ };
262
+
263
+ return renderTsSourceFile(spec);
264
+ }
@@ -0,0 +1,106 @@
1
+ // The merge rule of `vite.slots.clientHeaders`: docs/architecture/plugins/vite.md, "Content-Security-Policy".
2
+
3
+ import { createHash } from "node:crypto";
4
+
5
+ const CSP = "content-security-policy";
6
+
7
+ // Header names are case-insensitive: the slot compares them folded.
8
+ export function headerKey(name: string): string {
9
+ return name.toLowerCase();
10
+ }
11
+
12
+ interface Directive {
13
+ name: string;
14
+ sources: string[];
15
+ }
16
+
17
+ // `name source source…` separated by `;`. A directive name compares
18
+ // case-insensitively and keeps its first spelling; an empty segment is
19
+ // dropped. A repeated directive inside one policy is ignored by browsers
20
+ // after its first, so the first wins here too.
21
+ function parse(policy: string): Directive[] {
22
+ const out: Directive[] = [];
23
+ const seen = new Set<string>();
24
+ for (const segment of policy.split(";")) {
25
+ const [name, ...sources] = segment.trim().split(/\s+/);
26
+ if (!name) continue;
27
+ const id = name.toLowerCase();
28
+ if (seen.has(id)) continue;
29
+ seen.add(id);
30
+ out.push({ name, sources });
31
+ }
32
+ return out;
33
+ }
34
+
35
+ const isNone = (source: string) => source.toLowerCase() === "'none'";
36
+
37
+ // Sources of one directive, unioned in first-seen order. `'none'` means "no
38
+ // source": alone it stays, beside real sources it drops.
39
+ function unionSources(a: string[], b: string[]): string[] {
40
+ const union: string[] = [];
41
+ for (const source of [...a, ...b]) {
42
+ if (!union.includes(source)) union.push(source);
43
+ }
44
+ const real = union.filter((source) => !isNone(source));
45
+ return real.length > 0 ? real : union;
46
+ }
47
+
48
+ export function mergeCsp(a: string, b: string): string {
49
+ const merged = new Map<string, Directive>();
50
+ for (const directive of [...parse(a), ...parse(b)]) {
51
+ const id = directive.name.toLowerCase();
52
+ const held = merged.get(id);
53
+ merged.set(
54
+ id,
55
+ held === undefined
56
+ ? directive
57
+ : {
58
+ name: held.name,
59
+ sources: unionSources(held.sources, directive.sources),
60
+ },
61
+ );
62
+ }
63
+ return [...merged.values()]
64
+ .map((d) => [d.name, ...d.sources].join(" "))
65
+ .join("; ");
66
+ }
67
+
68
+ // The CSP source for an inline script: the base64 SHA-256 of its text, which
69
+ // is what a browser hashes (the element's text content, byte for byte).
70
+ export function scriptHash(script: string): string {
71
+ return `'sha256-${createHash("sha256").update(script, "utf8").digest("base64")}'`;
72
+ }
73
+
74
+ // The directives a browser checks a `<script>` element against, in order: the
75
+ // first one a policy names decides.
76
+ const SCRIPT_ELEMENT = ["script-src-elem", "script-src", "default-src"];
77
+
78
+ // `'unsafe-inline'` allows every inline script only while no hash or nonce
79
+ // stands beside it; a hash added beside it revokes it.
80
+ const allowsEveryInline = (sources: string[]) =>
81
+ sources.some((s) => s.toLowerCase() === "'unsafe-inline'") &&
82
+ !sources.some((s) => /^'(?:sha256|sha384|sha512|nonce)-/i.test(s));
83
+
84
+ // `policy` with `source` added to the directive that decides a `<script>`
85
+ // element. A policy that names none of them restricts no script, and one whose
86
+ // deciding directive allows every inline script already allows this one: both
87
+ // come back as they are.
88
+ export function allowScript(policy: string, source: string): string {
89
+ const directives = parse(policy);
90
+ const deciding = SCRIPT_ELEMENT.map((name) =>
91
+ directives.find((d) => d.name.toLowerCase() === name),
92
+ ).find((d) => d !== undefined);
93
+ if (deciding === undefined || allowsEveryInline(deciding.sources))
94
+ return policy;
95
+ return mergeCsp(policy, `${deciding.name} ${source}`);
96
+ }
97
+
98
+ // The slot's `merge`: a CSP combines, any other header declines (undefined),
99
+ // which leaves the duplicate a conflict.
100
+ export function mergeClientHeader(
101
+ a: string,
102
+ b: string,
103
+ key: string,
104
+ ): string | undefined {
105
+ return key === CSP ? mergeCsp(a, b) : undefined;
106
+ }