@silkui/vite 0.0.0-stage → 0.1.1
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/README.md +84 -2
- package/package.json +22 -4
- package/src/apis.js +188 -0
- package/src/dev-client.js +43 -0
- package/src/dev-shims.js +17 -0
- package/src/dev.js +169 -0
- package/src/index.d.ts +23 -0
- package/src/index.js +159 -0
- package/src/resolve.js +6 -0
package/README.md
CHANGED
|
@@ -1,3 +1,85 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @silkui/vite
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The [Vite](https://vite.dev) plugin for [Silk UI](https://github.com/silk-lang/SilkUI)
|
|
4
|
+
JavaScript apps. It builds the app into the one ES module a Silk UI host runs, serves its
|
|
5
|
+
modules to the window under the dev server with hot module replacement, and reports the web
|
|
6
|
+
and Node APIs the build uses that the embedded SilkJS runtime does not have. It knows no UI
|
|
7
|
+
framework: a React app adds `react()` from `@silkui/react/vite`.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
The templates (`silk init my-app -t ui-react`, `ui-foldkit` or `ui-js`) set it up, and
|
|
12
|
+
`silk task dev` and `silk task build` run Vite for you. See
|
|
13
|
+
[Get started](https://silk-ui-docs.juliaortiz-js.workers.dev/start/). To add it to an
|
|
14
|
+
existing project:
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
npm install -D @silkui/vite vite
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Usage
|
|
21
|
+
|
|
22
|
+
```js
|
|
23
|
+
// vite.config.js
|
|
24
|
+
import { defineConfig } from "vite";
|
|
25
|
+
import silk from "@silkui/vite";
|
|
26
|
+
import react from "@silkui/react/vite";
|
|
27
|
+
|
|
28
|
+
export default defineConfig({ plugins: [silk({ entry: "src/main.tsx" }), react()] });
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
- `vite build` writes the production bundle, `dist/app.js`, with `process.env.NODE_ENV`
|
|
32
|
+
from the Vite mode.
|
|
33
|
+
- `vite` serves the modules to the host and replaces the ones an edit touches. A module
|
|
34
|
+
nothing accepts restarts the app. With `@silkui/react/vite`, component files keep their
|
|
35
|
+
state (React Fast Refresh). A build error is printed and the running app is left alone.
|
|
36
|
+
`import.meta.hot` works as in Vite.
|
|
37
|
+
- `vite build --watch --mode development` rebuilds the bundle on every change and writes
|
|
38
|
+
`<bundle>.stamp` after each successful build. A host that watches it reloads the whole app.
|
|
39
|
+
This is the production code path, so it is the mode to check a bundle in.
|
|
40
|
+
|
|
41
|
+
## Options
|
|
42
|
+
|
|
43
|
+
| Option | Default | Meaning |
|
|
44
|
+
| --- | --- | --- |
|
|
45
|
+
| `entry` | `src/main.jsx` | Entry module, relative to the Vite root |
|
|
46
|
+
| `fileName` | `app.js` | Name of the bundle in `build.outDir` |
|
|
47
|
+
| `host` | the `SILKUI_HOST` program, which `silk task dev` sets | `{ command, args, cwd }`: a host binary to start, given `--dev <port>` under the dev server and `--watch <bundle>` in watch mode. Without one, the plugin prints the port for a host you start yourself |
|
|
48
|
+
| `port` | any free one | Port the dev server listens on for the host |
|
|
49
|
+
| `apis` | `"warn"` | What to do when the build uses an API the runtime does not have: `"warn"`, `"error"` or `"off"` |
|
|
50
|
+
| `allow` | none | Names of such APIs the app provides itself, such as `provided` from `@silkui/foldkit/apis` |
|
|
51
|
+
| `node` | `false` | The host runs the full SilkJS runtime: `node:fs` and the other Node builtins stay imports, and `apis` reports only what that runtime lacks |
|
|
52
|
+
|
|
53
|
+
## The missing API report
|
|
54
|
+
|
|
55
|
+
A realm has ECMAScript, timers, `requestAnimationFrame`, `console`, `performance.now`,
|
|
56
|
+
`navigator.clipboard` and `@silkui/core`, but no `fetch`, `URL`, `Intl`, `document`,
|
|
57
|
+
`process` or Node modules. Libraries written for browsers or Node often expect them, so the
|
|
58
|
+
plugin reads every module of a build and says which are used, and by whom:
|
|
59
|
+
|
|
60
|
+
```
|
|
61
|
+
APIs used here that a ui-js runtime does not have:
|
|
62
|
+
fetch (network): src/api.js, ky
|
|
63
|
+
Intl (intl): date-fns
|
|
64
|
+
node:fs (node): some-package
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
A name counts when a module reads it as a global. A `typeof` test for it, a local of the
|
|
68
|
+
same name and `process.env.NAME` do not count. Under the dev server the warning comes when
|
|
69
|
+
the module is first served. For Node's APIs at run time, build with `node: true` and give
|
|
70
|
+
the app the full runtime (`App.runtime(Runtime.node())` in `src/tasks.silk`).
|
|
71
|
+
|
|
72
|
+
## TypeScript
|
|
73
|
+
|
|
74
|
+
The package ships its types: `silk(options?: SilkOptions): Plugin[]`.
|
|
75
|
+
|
|
76
|
+
## Requirements
|
|
77
|
+
|
|
78
|
+
`vite` 8.
|
|
79
|
+
|
|
80
|
+
## More
|
|
81
|
+
|
|
82
|
+
- [The ui-js reference](https://github.com/silk-lang/SilkUI/blob/main/modules/js/README.md#silkuivite),
|
|
83
|
+
including how the dev server talks to the host.
|
|
84
|
+
- [Templates](https://github.com/silk-lang/examples).
|
|
85
|
+
- [Source](https://github.com/silk-lang/SilkUI/tree/main/modules/js/packages/vite). MIT license.
|
package/package.json
CHANGED
|
@@ -1,6 +1,24 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@silkui/vite",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Vite plugin that builds a ui-js application and reloads it in the native window",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/silk-lang/SilkUI.git",
|
|
8
|
+
"directory": "modules/js/packages/vite"
|
|
9
|
+
},
|
|
10
|
+
"type": "module",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./src/index.d.ts",
|
|
14
|
+
"default": "./src/index.js"
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"src"
|
|
19
|
+
],
|
|
20
|
+
"peerDependencies": {
|
|
21
|
+
"vite": "^8.0.0"
|
|
22
|
+
},
|
|
23
|
+
"license": "MIT"
|
|
24
|
+
}
|
package/src/apis.js
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
// Finds the web and Node APIs a module uses that a ui-js runtime does not have, so the
|
|
2
|
+
// build can say which ones an application or one of its libraries needs.
|
|
3
|
+
import { builtinModules } from "node:module";
|
|
4
|
+
|
|
5
|
+
/** Globals a ui-js realm lacks, by area. The areas are what a build will choose from. */
|
|
6
|
+
export const MISSING = {
|
|
7
|
+
network: ["fetch", "Request", "Response", "Headers", "WebSocket", "XMLHttpRequest", "EventSource"],
|
|
8
|
+
url: ["URL", "URLSearchParams"],
|
|
9
|
+
encoding: ["TextEncoder", "TextDecoder", "atob", "btoa"],
|
|
10
|
+
intl: ["Intl"],
|
|
11
|
+
temporal: ["Temporal"],
|
|
12
|
+
wasm: ["WebAssembly"],
|
|
13
|
+
crypto: ["crypto"],
|
|
14
|
+
streams: ["ReadableStream", "WritableStream", "TransformStream", "Blob", "File", "FormData"],
|
|
15
|
+
events: ["Event", "EventTarget", "CustomEvent", "AbortController", "AbortSignal", "MessageChannel", "structuredClone", "DOMException"],
|
|
16
|
+
workers: ["Worker"],
|
|
17
|
+
storage: ["localStorage", "sessionStorage", "indexedDB"],
|
|
18
|
+
dom: [
|
|
19
|
+
"document", "window", "navigator", "location", "history", "MutationObserver", "ResizeObserver",
|
|
20
|
+
"IntersectionObserver", "matchMedia", "getComputedStyle", "Image", "HTMLElement",
|
|
21
|
+
],
|
|
22
|
+
node: ["process", "Buffer", "require", "setImmediate", "__dirname", "__filename"],
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
const AREA = new Map();
|
|
26
|
+
for (const [area, names] of Object.entries(MISSING)) for (const name of names) AREA.set(name, area);
|
|
27
|
+
|
|
28
|
+
const BUILTIN = new Set(builtinModules);
|
|
29
|
+
|
|
30
|
+
/** The area of global `name`, or undefined when a ui-js realm has it. */
|
|
31
|
+
export function areaOf(name) {
|
|
32
|
+
return AREA.get(name);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function isNode(value) {
|
|
36
|
+
return value !== null && typeof value === "object" && typeof value.type === "string";
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Every binding name a pattern declares. */
|
|
40
|
+
function declare(pattern, declared) {
|
|
41
|
+
if (!pattern) return;
|
|
42
|
+
switch (pattern.type) {
|
|
43
|
+
case "Identifier":
|
|
44
|
+
declared.add(pattern.name);
|
|
45
|
+
break;
|
|
46
|
+
case "ObjectPattern":
|
|
47
|
+
for (const property of pattern.properties) declare(property.type === "RestElement" ? property.argument : property.value, declared);
|
|
48
|
+
break;
|
|
49
|
+
case "ArrayPattern":
|
|
50
|
+
for (const element of pattern.elements) declare(element, declared);
|
|
51
|
+
break;
|
|
52
|
+
case "AssignmentPattern":
|
|
53
|
+
declare(pattern.left, declared);
|
|
54
|
+
break;
|
|
55
|
+
case "RestElement":
|
|
56
|
+
declare(pattern.argument, declared);
|
|
57
|
+
break;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The missing APIs the program `ast` (ESTree) uses: global names it reads without
|
|
63
|
+
* declaring them or testing for them with `typeof`, and Node builtin modules it imports.
|
|
64
|
+
* A name the module declares anywhere counts as its own, whatever the scope: the scan
|
|
65
|
+
* would rather miss a use than report one that is not there.
|
|
66
|
+
* @returns {{ name: string, area: string }[]}
|
|
67
|
+
*/
|
|
68
|
+
export function missingApis(ast) {
|
|
69
|
+
const declared = new Set();
|
|
70
|
+
const guarded = new Set();
|
|
71
|
+
const used = new Set();
|
|
72
|
+
const modules = new Set();
|
|
73
|
+
|
|
74
|
+
const visit = (node, parent) => {
|
|
75
|
+
switch (node.type) {
|
|
76
|
+
case "Identifier":
|
|
77
|
+
if (AREA.has(node.name)) used.add(node.name);
|
|
78
|
+
return;
|
|
79
|
+
case "ImportDeclaration":
|
|
80
|
+
for (const specifier of node.specifiers) declared.add(specifier.local.name);
|
|
81
|
+
builtin(node.source.value);
|
|
82
|
+
return;
|
|
83
|
+
case "ExportNamedDeclaration":
|
|
84
|
+
case "ExportAllDeclaration":
|
|
85
|
+
if (node.source) builtin(node.source.value);
|
|
86
|
+
if (node.declaration) visit(node.declaration, node);
|
|
87
|
+
return;
|
|
88
|
+
case "ImportExpression":
|
|
89
|
+
if (node.source.type === "Literal") builtin(node.source.value);
|
|
90
|
+
break;
|
|
91
|
+
case "VariableDeclarator":
|
|
92
|
+
declare(node.id, declared);
|
|
93
|
+
if (node.init) visit(node.init, node);
|
|
94
|
+
return;
|
|
95
|
+
case "FunctionDeclaration":
|
|
96
|
+
case "FunctionExpression":
|
|
97
|
+
case "ArrowFunctionExpression":
|
|
98
|
+
if (node.id) declared.add(node.id.name);
|
|
99
|
+
for (const parameter of node.params) declare(parameter, declared);
|
|
100
|
+
break;
|
|
101
|
+
case "ClassDeclaration":
|
|
102
|
+
case "ClassExpression":
|
|
103
|
+
if (node.id) declared.add(node.id.name);
|
|
104
|
+
break;
|
|
105
|
+
case "CatchClause":
|
|
106
|
+
declare(node.param, declared);
|
|
107
|
+
break;
|
|
108
|
+
case "UnaryExpression":
|
|
109
|
+
// `typeof fetch` asks whether it is there: the module copes without it.
|
|
110
|
+
if (node.operator === "typeof" && node.argument.type === "Identifier") {
|
|
111
|
+
guarded.add(node.argument.name);
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
break;
|
|
115
|
+
case "CallExpression":
|
|
116
|
+
// `require("x")` is the bundler's to resolve, as an import is.
|
|
117
|
+
if (node.callee.type === "Identifier" && node.callee.name === "require" && node.arguments[0]?.type === "Literal") {
|
|
118
|
+
builtin(node.arguments[0].value);
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
break;
|
|
122
|
+
case "MemberExpression":
|
|
123
|
+
// `process.env.NAME` is replaced at build time.
|
|
124
|
+
if (node.object.type === "Identifier" && node.object.name === "process" && !node.computed && node.property.name === "env") return;
|
|
125
|
+
visit(node.object, node);
|
|
126
|
+
if (node.computed) visit(node.property, node);
|
|
127
|
+
return;
|
|
128
|
+
case "Property":
|
|
129
|
+
case "MethodDefinition":
|
|
130
|
+
case "PropertyDefinition":
|
|
131
|
+
if (node.computed) visit(node.key, node);
|
|
132
|
+
if (node.value) visit(node.value, node);
|
|
133
|
+
return;
|
|
134
|
+
case "LabeledStatement":
|
|
135
|
+
visit(node.body, node);
|
|
136
|
+
return;
|
|
137
|
+
case "BreakStatement":
|
|
138
|
+
case "ContinueStatement":
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
for (const key in node) {
|
|
142
|
+
if (key === "type" || key === "loc" || key === "range") continue;
|
|
143
|
+
const value = node[key];
|
|
144
|
+
if (Array.isArray(value)) {
|
|
145
|
+
for (const item of value) if (isNode(item)) visit(item, node);
|
|
146
|
+
} else if (isNode(value)) {
|
|
147
|
+
visit(value, node);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
const builtin = (source) => {
|
|
153
|
+
if (typeof source !== "string") return;
|
|
154
|
+
if (source.startsWith("node:")) modules.add(source);
|
|
155
|
+
else if (BUILTIN.has(source)) modules.add(`node:${source}`);
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
visit(ast, null);
|
|
159
|
+
const found = [];
|
|
160
|
+
for (const name of used) if (!declared.has(name) && !guarded.has(name)) found.push({ name, area: AREA.get(name) });
|
|
161
|
+
for (const name of modules) found.push({ name, area: "node" });
|
|
162
|
+
return found;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Who a module belongs to: the package under node_modules, or its path in the project. */
|
|
166
|
+
export function ownerOf(id, root) {
|
|
167
|
+
const [file] = id.split("?");
|
|
168
|
+
const marker = "/node_modules/";
|
|
169
|
+
const at = file.lastIndexOf(marker);
|
|
170
|
+
if (at !== -1) {
|
|
171
|
+
const parts = file.slice(at + marker.length).split("/");
|
|
172
|
+
if (parts[0] === ".vite") return parts[2]?.replace(/\.js$/, "") ?? file;
|
|
173
|
+
return parts[0].startsWith("@") ? `${parts[0]}/${parts[1]}` : parts[0];
|
|
174
|
+
}
|
|
175
|
+
return file.startsWith(root) ? file.slice(root.length).replace(/^\//, "") : file;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** The report of `uses` (name → { area, owners }), one line per API. */
|
|
179
|
+
export function report(uses) {
|
|
180
|
+
const lines = ["APIs used here that a ui-js runtime does not have:"];
|
|
181
|
+
const names = [...uses.keys()].sort((a, b) => uses.get(a).area.localeCompare(uses.get(b).area) || a.localeCompare(b));
|
|
182
|
+
for (const name of names) {
|
|
183
|
+
const { area, owners } = uses.get(name);
|
|
184
|
+
lines.push(` ${name} (${area}): ${[...owners].sort().join(", ")}`);
|
|
185
|
+
}
|
|
186
|
+
lines.push("Code that reaches them fails when it runs. Pass `apis: \"off\"` to silence this, or `allow` for names the application provides itself.");
|
|
187
|
+
return lines.join("\n");
|
|
188
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// Runs inside the realm of a ui-js host in development: Vite's module runner over the
|
|
2
|
+
// host's line transport (`__ui.devSend` out, `__ui.devMessage` in).
|
|
3
|
+
import "./dev-shims.js";
|
|
4
|
+
import { ModuleRunner, ESModulesEvaluator } from "vite/module-runner";
|
|
5
|
+
|
|
6
|
+
const native = globalThis.__ui;
|
|
7
|
+
let handlers = null;
|
|
8
|
+
|
|
9
|
+
native.devMessage = (line) => {
|
|
10
|
+
const payload = JSON.parse(line);
|
|
11
|
+
// A full reload is a new realm: the host runs this script again in it.
|
|
12
|
+
if (payload.type === "full-reload") return native.devReload();
|
|
13
|
+
if (payload.type === "error") {
|
|
14
|
+
const { message, id, frame } = payload.err ?? {};
|
|
15
|
+
console.error(`[vite] ${message ?? "error"}${id ? `\n in ${id}` : ""}${frame ? `\n${frame}` : ""}`);
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
handlers?.onMessage(payload);
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
const runner = new ModuleRunner(
|
|
22
|
+
{
|
|
23
|
+
transport: {
|
|
24
|
+
connect(given) {
|
|
25
|
+
handlers = given;
|
|
26
|
+
},
|
|
27
|
+
send(data) {
|
|
28
|
+
native.devSend(JSON.stringify(data));
|
|
29
|
+
},
|
|
30
|
+
},
|
|
31
|
+
hmr: true,
|
|
32
|
+
sourcemapInterceptor: false,
|
|
33
|
+
},
|
|
34
|
+
new ESModulesEvaluator(),
|
|
35
|
+
);
|
|
36
|
+
|
|
37
|
+
native.devStart = async (modules) => {
|
|
38
|
+
try {
|
|
39
|
+
for (const module of modules) await runner.import(module);
|
|
40
|
+
} catch (error) {
|
|
41
|
+
console.error(`Uncaught ${error?.stack ?? error}`);
|
|
42
|
+
}
|
|
43
|
+
};
|
package/src/dev-shims.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// What Vite's module runner touches that a ui-js realm does not have. Source map
|
|
2
|
+
// interception is off, so the decoder is never asked for text.
|
|
3
|
+
globalThis.TextDecoder ??= class TextDecoder {
|
|
4
|
+
decode() {
|
|
5
|
+
return "";
|
|
6
|
+
}
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
// The runner builds file URLs for import.meta: this covers `new URL("file://…").href`.
|
|
10
|
+
globalThis.URL ??= class URL {
|
|
11
|
+
constructor(text) {
|
|
12
|
+
this.href = encodeURI(String(text));
|
|
13
|
+
}
|
|
14
|
+
toString() {
|
|
15
|
+
return this.href;
|
|
16
|
+
}
|
|
17
|
+
};
|
package/src/dev.js
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
// The development side of @silkui/vite: a Vite environment whose modules run in a ui-js host,
|
|
2
|
+
// reached over a local TCP connection the host opens (`--dev <port>`).
|
|
3
|
+
import { spawn } from "node:child_process";
|
|
4
|
+
import net from "node:net";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { build, DevEnvironment } from "vite";
|
|
7
|
+
import { resolveOptions } from "./resolve.js";
|
|
8
|
+
|
|
9
|
+
// The longest text on one line: the host reads lines of up to one mebibyte.
|
|
10
|
+
const CHUNK = 256 * 1024;
|
|
11
|
+
|
|
12
|
+
/** The lines that carry `text` as a message of `kind`. */
|
|
13
|
+
export function frames(kind, text) {
|
|
14
|
+
const bytes = Buffer.from(text, "utf8");
|
|
15
|
+
const lines = [];
|
|
16
|
+
let at = 0;
|
|
17
|
+
do {
|
|
18
|
+
let end = Math.min(at + CHUNK, bytes.length);
|
|
19
|
+
// Not inside a UTF-8 sequence: each line is text of its own.
|
|
20
|
+
while (end < bytes.length && (bytes[end] & 0xc0) === 0x80) end--;
|
|
21
|
+
lines.push(`${kind}${end < bytes.length ? "+" : "."}${bytes.toString("utf8", at, end)}\n`);
|
|
22
|
+
at = end;
|
|
23
|
+
} while (at < bytes.length);
|
|
24
|
+
return lines;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The hot channel of the environment: every connected host is a client. */
|
|
28
|
+
function createChannel() {
|
|
29
|
+
const sockets = new Set();
|
|
30
|
+
const listeners = new Map();
|
|
31
|
+
const emit = (event, data, client) => {
|
|
32
|
+
for (const listener of listeners.get(event) ?? []) listener(data, client);
|
|
33
|
+
};
|
|
34
|
+
const write = (socket, kind, text) => {
|
|
35
|
+
for (const line of frames(kind, text)) socket.write(line);
|
|
36
|
+
};
|
|
37
|
+
return {
|
|
38
|
+
channel: {
|
|
39
|
+
skipFsCheck: true,
|
|
40
|
+
send(payload) {
|
|
41
|
+
const text = JSON.stringify(payload);
|
|
42
|
+
for (const socket of sockets) write(socket, "m", text);
|
|
43
|
+
},
|
|
44
|
+
on(event, listener) {
|
|
45
|
+
if (!listeners.has(event)) listeners.set(event, new Set());
|
|
46
|
+
listeners.get(event).add(listener);
|
|
47
|
+
},
|
|
48
|
+
off(event, listener) {
|
|
49
|
+
listeners.get(event)?.delete(listener);
|
|
50
|
+
},
|
|
51
|
+
},
|
|
52
|
+
/** Takes a host's connection: `bootstrap` first, then messages both ways. */
|
|
53
|
+
accept(socket, bootstrap) {
|
|
54
|
+
sockets.add(socket);
|
|
55
|
+
socket.setNoDelay(true);
|
|
56
|
+
const client = { send: (payload) => write(socket, "m", JSON.stringify(payload)) };
|
|
57
|
+
let pending = "";
|
|
58
|
+
socket.setEncoding("utf8");
|
|
59
|
+
socket.on("data", (text) => {
|
|
60
|
+
pending += text;
|
|
61
|
+
let end;
|
|
62
|
+
while ((end = pending.indexOf("\n")) !== -1) {
|
|
63
|
+
const line = pending.slice(0, end);
|
|
64
|
+
pending = pending.slice(end + 1);
|
|
65
|
+
let payload;
|
|
66
|
+
try {
|
|
67
|
+
payload = JSON.parse(line);
|
|
68
|
+
} catch {
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
if (payload.type === "custom") emit(payload.event, payload.data, client);
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
const gone = () => sockets.delete(socket);
|
|
75
|
+
socket.on("close", gone);
|
|
76
|
+
socket.on("error", gone);
|
|
77
|
+
write(socket, "b", JSON.stringify(bootstrap));
|
|
78
|
+
emit("connection", undefined, client);
|
|
79
|
+
},
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The script a host runs first in each realm: the module runner, then the application. */
|
|
84
|
+
async function bootstrapScript(modules) {
|
|
85
|
+
const output = await build({
|
|
86
|
+
configFile: false,
|
|
87
|
+
logLevel: "silent",
|
|
88
|
+
root: fileURLToPath(new URL(".", import.meta.url)),
|
|
89
|
+
build: {
|
|
90
|
+
write: false,
|
|
91
|
+
minify: false,
|
|
92
|
+
target: "es2022",
|
|
93
|
+
lib: { entry: "dev-client.js", formats: ["iife"], name: "__silkDev" },
|
|
94
|
+
rolldownOptions: { output: { codeSplitting: false } },
|
|
95
|
+
},
|
|
96
|
+
});
|
|
97
|
+
const code = (Array.isArray(output) ? output[0] : output).output[0].code;
|
|
98
|
+
return `${code}\n__ui.devStart(${JSON.stringify(modules)});`;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* The plugins of `vite` (serve) for a ui-js application.
|
|
103
|
+
* @param {{ entry: string, port: number, host?: { command: string, args?: readonly string[], cwd?: string } }} options
|
|
104
|
+
*/
|
|
105
|
+
export function devPlugins(options) {
|
|
106
|
+
const { channel, accept } = createChannel();
|
|
107
|
+
let listener = null;
|
|
108
|
+
let child = null;
|
|
109
|
+
// Modules other plugins ask to run before the entry, such as a framework's refresh runtime.
|
|
110
|
+
let preload = [];
|
|
111
|
+
|
|
112
|
+
const main = {
|
|
113
|
+
name: "silk:dev",
|
|
114
|
+
apply: "serve",
|
|
115
|
+
// For tests and tools: the TCP server hosts connect to, once the dev server is set up.
|
|
116
|
+
api: { listener: () => listener },
|
|
117
|
+
|
|
118
|
+
config() {
|
|
119
|
+
const define = { "process.env.NODE_ENV": JSON.stringify("development") };
|
|
120
|
+
return {
|
|
121
|
+
appType: "custom",
|
|
122
|
+
environments: {
|
|
123
|
+
silk: {
|
|
124
|
+
define,
|
|
125
|
+
// Nothing is left to the host to load: it has no module resolution of its own.
|
|
126
|
+
resolve: { ...resolveOptions, noExternal: true },
|
|
127
|
+
optimizeDeps: { noDiscovery: false, rolldownOptions: { transform: { define } } },
|
|
128
|
+
dev: {
|
|
129
|
+
createEnvironment: (name, config) => new DevEnvironment(name, config, { hot: true, transport: channel }),
|
|
130
|
+
},
|
|
131
|
+
},
|
|
132
|
+
},
|
|
133
|
+
};
|
|
134
|
+
},
|
|
135
|
+
|
|
136
|
+
configResolved(config) {
|
|
137
|
+
preload = config.plugins.flatMap((plugin) => plugin.api?.silkPreload ?? []);
|
|
138
|
+
},
|
|
139
|
+
|
|
140
|
+
async configureServer(server) {
|
|
141
|
+
const entry = options.entry.startsWith("/") ? options.entry : `/${options.entry}`;
|
|
142
|
+
const bootstrap = await bootstrapScript([...preload, entry]);
|
|
143
|
+
listener = net.createServer((socket) => accept(socket, bootstrap));
|
|
144
|
+
await new Promise((resolve, reject) => {
|
|
145
|
+
listener.once("error", reject);
|
|
146
|
+
listener.listen(options.port, "127.0.0.1", resolve);
|
|
147
|
+
});
|
|
148
|
+
const { port } = listener.address();
|
|
149
|
+
// Closes with the dev server, whether or not that has an HTTP server of its own.
|
|
150
|
+
const close = server.close.bind(server);
|
|
151
|
+
server.close = async () => {
|
|
152
|
+
listener.close();
|
|
153
|
+
await close();
|
|
154
|
+
};
|
|
155
|
+
if (!options.host) {
|
|
156
|
+
server.config.logger.info(` [silk] waiting for a ui-js host: start one with --dev ${port}`);
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
const { command, args = [], cwd } = options.host;
|
|
160
|
+
child = spawn(command, [...args, "--dev", String(port)], { cwd, stdio: "inherit" });
|
|
161
|
+
child.on("error", (error) => server.config.logger.error(`[silk] could not start ${command}: ${error.message}`));
|
|
162
|
+
// Closing the window ends the dev session.
|
|
163
|
+
child.on("exit", (code) => process.exit(code ?? 0));
|
|
164
|
+
process.on("exit", () => child.kill());
|
|
165
|
+
},
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
return [main];
|
|
169
|
+
}
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { Plugin } from "vite";
|
|
2
|
+
|
|
3
|
+
export interface SilkOptions {
|
|
4
|
+
/** Entry module, relative to the Vite root. Default `src/main.jsx`. */
|
|
5
|
+
entry?: string;
|
|
6
|
+
/** Name of the bundle in `build.outDir`. Default `app.js`. */
|
|
7
|
+
fileName?: string;
|
|
8
|
+
/** Host binary to start: given `--watch <bundle>` in watch mode, `--dev <port>` under the dev server. */
|
|
9
|
+
host?: { command: string; args?: readonly string[]; cwd?: string };
|
|
10
|
+
/** Port the dev server listens on for the host. Default: any free one. */
|
|
11
|
+
port?: number;
|
|
12
|
+
/** What to do when the build uses a web or Node API the runtime does not have. Default `warn`. */
|
|
13
|
+
apis?: "warn" | "error" | "off";
|
|
14
|
+
/** Such APIs the application provides itself. */
|
|
15
|
+
allow?: readonly string[];
|
|
16
|
+
/**
|
|
17
|
+
* The host runs the full SilkJS runtime (ui-js-node): Node builtins stay `node:` imports,
|
|
18
|
+
* and `apis` reports only what that runtime lacks.
|
|
19
|
+
*/
|
|
20
|
+
node?: boolean;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export default function silk(options?: SilkOptions): Plugin[];
|
package/src/index.js
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
// Vite plugin for ui-js applications.
|
|
2
|
+
//
|
|
3
|
+
// A ui-js host evaluates one ES module, so the plugin configures a library build with a
|
|
4
|
+
// single output file. After each successful build it writes `<bundle>.stamp`; a host
|
|
5
|
+
// started with --watch reloads the application when that file changes. With `host` set
|
|
6
|
+
// and `vite build --watch`, the plugin starts the host after the first build.
|
|
7
|
+
//
|
|
8
|
+
// Under `vite` (the dev server) the host runs the application's modules as Vite serves
|
|
9
|
+
// them, and an edit replaces only the modules it touches: see dev.js. The plugin knows no
|
|
10
|
+
// UI framework: `@silkui/react/vite` adds React's JSX, its reconciler fix and Fast Refresh.
|
|
11
|
+
import { spawn } from "node:child_process";
|
|
12
|
+
import { writeFileSync } from "node:fs";
|
|
13
|
+
import { builtinModules } from "node:module";
|
|
14
|
+
import { resolve } from "node:path";
|
|
15
|
+
import { missingApis, ownerOf, report } from "./apis.js";
|
|
16
|
+
import { devPlugins } from "./dev.js";
|
|
17
|
+
import { resolveOptions } from "./resolve.js";
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @param {object} [options]
|
|
21
|
+
* @param {string} [options.entry] Entry module, relative to the Vite root. Default `src/main.jsx`.
|
|
22
|
+
* @param {string} [options.fileName] Name of the bundle in `build.outDir`. Default `app.js`.
|
|
23
|
+
* @param {{ command: string, args?: readonly string[], cwd?: string }} [options.host] Host binary to
|
|
24
|
+
* start. In watch mode it is given `--watch <bundle>` after `args`, under the dev
|
|
25
|
+
* server `--dev <port>`.
|
|
26
|
+
* @param {number} [options.port] Port the dev server listens on for the host. Default: any
|
|
27
|
+
* free one.
|
|
28
|
+
* @param {"warn" | "error" | "off"} [options.apis] What to do when the application or one
|
|
29
|
+
* of its libraries uses a web or Node API a ui-js runtime does not have. Default `warn`.
|
|
30
|
+
* @param {string[]} [options.allow] Such APIs the application provides itself.
|
|
31
|
+
* @param {boolean} [options.node] The host runs the full SilkJS runtime (ui-js-node): Node
|
|
32
|
+
* builtins stay `node:` imports instead of empty stubs, and the API report leaves out
|
|
33
|
+
* what that runtime has.
|
|
34
|
+
*/
|
|
35
|
+
export default function silk(options = {}) {
|
|
36
|
+
// silkui's tasks start Vite with the host they built in SILKUI_HOST.
|
|
37
|
+
if (options.host === undefined && process.env.SILKUI_HOST) options = { ...options, host: { command: process.env.SILKUI_HOST } };
|
|
38
|
+
const entry = options.entry ?? "src/main.jsx";
|
|
39
|
+
const fileName = options.fileName ?? "app.js";
|
|
40
|
+
const node = options.node === true;
|
|
41
|
+
let bundle = "";
|
|
42
|
+
let watching = false;
|
|
43
|
+
let child = null;
|
|
44
|
+
|
|
45
|
+
function startHost() {
|
|
46
|
+
const { command, args = [], cwd } = options.host;
|
|
47
|
+
child = spawn(command, [...args, "--watch", bundle], { cwd, stdio: "inherit" });
|
|
48
|
+
child.on("error", (error) => {
|
|
49
|
+
console.error(`[silk] could not start ${command}: ${error.message}`);
|
|
50
|
+
});
|
|
51
|
+
// Closing the window ends the dev session.
|
|
52
|
+
child.on("exit", (code) => process.exit(code ?? 0));
|
|
53
|
+
process.on("exit", () => child.kill());
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const buildPlugin = {
|
|
57
|
+
name: "silk",
|
|
58
|
+
apply: "build",
|
|
59
|
+
|
|
60
|
+
config(_user, { mode }) {
|
|
61
|
+
const config = {
|
|
62
|
+
resolve: resolveOptions,
|
|
63
|
+
// Libraries read it to pick their development or production build.
|
|
64
|
+
define: { "process.env.NODE_ENV": JSON.stringify(mode === "development" ? "development" : "production") },
|
|
65
|
+
build: {
|
|
66
|
+
target: "es2022",
|
|
67
|
+
minify: mode !== "development",
|
|
68
|
+
lib: { entry, formats: ["es"], fileName: () => fileName },
|
|
69
|
+
rolldownOptions: { output: { codeSplitting: false } },
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
return config;
|
|
73
|
+
},
|
|
74
|
+
|
|
75
|
+
configResolved(config) {
|
|
76
|
+
bundle = resolve(config.root, config.build.outDir, fileName);
|
|
77
|
+
watching = config.build.watch != null;
|
|
78
|
+
},
|
|
79
|
+
|
|
80
|
+
// Runs only after a build that wrote its files, so a failed build keeps the old app.
|
|
81
|
+
writeBundle() {
|
|
82
|
+
writeFileSync(`${bundle}.stamp`, `${Date.now()}\n`);
|
|
83
|
+
if (watching && options.host && child === null) startHost();
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
const apis = options.apis ?? "warn";
|
|
87
|
+
const allow = new Set(options.allow ?? []);
|
|
88
|
+
let root = "";
|
|
89
|
+
let serving = false;
|
|
90
|
+
/** name → { area, owners } */
|
|
91
|
+
const uses = new Map();
|
|
92
|
+
const apiPlugin = {
|
|
93
|
+
name: "silk:apis",
|
|
94
|
+
enforce: "post",
|
|
95
|
+
|
|
96
|
+
configResolved(config) {
|
|
97
|
+
root = config.root;
|
|
98
|
+
serving = config.command === "serve";
|
|
99
|
+
},
|
|
100
|
+
|
|
101
|
+
buildStart() {
|
|
102
|
+
uses.clear();
|
|
103
|
+
},
|
|
104
|
+
|
|
105
|
+
// After the other transforms, so what is scanned is JavaScript.
|
|
106
|
+
transform(code, id) {
|
|
107
|
+
if (apis === "off" || id.startsWith("\0")) return;
|
|
108
|
+
if (serving && this.environment.name !== "silk") return;
|
|
109
|
+
if (!/\.[cm]?[jt]sx?$/.test(id.split("?")[0])) return;
|
|
110
|
+
let ast;
|
|
111
|
+
try {
|
|
112
|
+
ast = this.parse(code);
|
|
113
|
+
} catch {
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
const owner = ownerOf(id, root);
|
|
117
|
+
for (const { name, area } of missingApis(ast)) {
|
|
118
|
+
if (allow.has(name) || (node && !NOT_IN_NODE.has(area))) continue;
|
|
119
|
+
let use = uses.get(name);
|
|
120
|
+
if (!use) uses.set(name, (use = { area, owners: new Set() }));
|
|
121
|
+
if (use.owners.has(owner)) continue;
|
|
122
|
+
use.owners.add(owner);
|
|
123
|
+
// The dev server has no end to report at: say it when the module is first served.
|
|
124
|
+
if (serving) this.warn(`${name} (${area}) is not in a ui-js runtime, and ${owner} uses it`);
|
|
125
|
+
}
|
|
126
|
+
},
|
|
127
|
+
|
|
128
|
+
buildEnd(error) {
|
|
129
|
+
if (error || serving || uses.size === 0) return;
|
|
130
|
+
if (apis === "error") this.error(report(uses));
|
|
131
|
+
this.warn(report(uses));
|
|
132
|
+
},
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
const plugins = [buildPlugin, apiPlugin];
|
|
136
|
+
if (node) plugins.push(builtinsPlugin);
|
|
137
|
+
return [...plugins, ...devPlugins({ entry, port: options.port ?? 0, host: options.host })];
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** The areas of `MISSING` the SilkJS runtime does not have either. */
|
|
141
|
+
const NOT_IN_NODE = new Set(["dom", "storage", "workers"]);
|
|
142
|
+
|
|
143
|
+
const BUILTINS = new Set(builtinModules);
|
|
144
|
+
|
|
145
|
+
/** `node:<name>` when `id` names a Node builtin, with or without the prefix. */
|
|
146
|
+
function builtinOf(id) {
|
|
147
|
+
if (id.startsWith("node:")) return id;
|
|
148
|
+
return BUILTINS.has(id) ? `node:${id}` : null;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// Before Vite's resolver, which turns builtins into empty browser stubs: the runtime has them.
|
|
152
|
+
const builtinsPlugin = {
|
|
153
|
+
name: "silk:node-builtins",
|
|
154
|
+
enforce: "pre",
|
|
155
|
+
resolveId(id) {
|
|
156
|
+
const builtin = builtinOf(id);
|
|
157
|
+
if (builtin) return { id: builtin, external: true };
|
|
158
|
+
},
|
|
159
|
+
};
|
package/src/resolve.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// A ui-js realm is neither a browser nor Node: a package's `browser` or `node` build reaches
|
|
2
|
+
// for `document` or `process`, so resolution takes its portable one.
|
|
3
|
+
export const resolveOptions = {
|
|
4
|
+
conditions: ["module", "development|production"],
|
|
5
|
+
mainFields: ["module", "jsnext:main", "jsnext"],
|
|
6
|
+
};
|