@farm.js/islx 0.0.0-stage → 0.0.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.
Files changed (39) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/LICENSE +21 -0
  3. package/README.md +198 -2
  4. package/SPEC.md +220 -0
  5. package/dist/_chunks/actions-BCtIGvrP.d.mts +58 -0
  6. package/dist/_chunks/actions-C4dZ1-XD.mjs +615 -0
  7. package/dist/_chunks/actions-CA_K-In7.mjs +310 -0
  8. package/dist/_chunks/actions-Eutk6UzT.mjs +326 -0
  9. package/dist/_chunks/build-COIcs7wm.mjs +9 -0
  10. package/dist/_chunks/codec-BTDkzzPP.mjs +271 -0
  11. package/dist/_chunks/codec-CK8kZp4u.d.mts +64 -0
  12. package/dist/_chunks/handle-C0N9ZyNV.d.mts +35 -0
  13. package/dist/_chunks/hooks-3VZV8f_d.d.mts +30 -0
  14. package/dist/_chunks/hooks-De0gNpOn.d.mts +64 -0
  15. package/dist/_chunks/prehydration-B1GLTLdk.mjs +36 -0
  16. package/dist/_chunks/schedule-BFoGKRrU.mjs +216 -0
  17. package/dist/_chunks/schedule-Dw14dW0H.d.mts +17 -0
  18. package/dist/_chunks/tree-BEV73f_8.mjs +777 -0
  19. package/dist/_chunks/tree-fID6sz25.d.mts +102 -0
  20. package/dist/_chunks/value-store-Dm-7xJ6W.d.mts +19 -0
  21. package/dist/_chunks/wire-C3Rpbwl6.d.mts +98 -0
  22. package/dist/_chunks/wire-CXOodE06.mjs +121 -0
  23. package/dist/client.d.mts +58 -0
  24. package/dist/client.mjs +197 -0
  25. package/dist/compiler.d.mts +2 -0
  26. package/dist/compiler.mjs +1 -0
  27. package/dist/index.d.mts +3 -0
  28. package/dist/index.mjs +3 -0
  29. package/dist/react/client.d.mts +49 -0
  30. package/dist/react/client.mjs +403 -0
  31. package/dist/react/server.d.mts +51 -0
  32. package/dist/react/server.mjs +84 -0
  33. package/dist/react.d.mts +3 -0
  34. package/dist/react.mjs +1 -0
  35. package/dist/server.d.mts +200 -0
  36. package/dist/server.mjs +378 -0
  37. package/dist/vite.d.mts +57 -0
  38. package/dist/vite.mjs +497 -0
  39. package/package.json +121 -4
package/dist/vite.mjs ADDED
@@ -0,0 +1,497 @@
1
+ import { i as transformActions, r as hasModuleDirective, t as ActionCompileError } from "./_chunks/actions-Eutk6UzT.mjs";
2
+ import { t as ISLAND_STRATEGIES } from "./_chunks/schedule-BFoGKRrU.mjs";
3
+ import { randomBytes } from "node:crypto";
4
+ import path from "node:path";
5
+ import { walk } from "estree-walker";
6
+ import MagicString from "magic-string";
7
+ import { analyze } from "periscopic";
8
+ import { readFile, readdir, writeFile } from "node:fs/promises";
9
+ // src/compiler/client.ts
10
+ /**
11
+ * The `"use client"` compiler. In the server build, every component a `"use client"` module
12
+ * exports renders as an island: its server HTML, and its props for the browser. The browser build
13
+ * keeps the module as it is.
14
+ *
15
+ * A component is an export named in PascalCase (`Chart`, not `COLORS` or `useChart`) that is not
16
+ * a literal value, or the default export. Other exports (hooks, constants, helpers) stay as they
17
+ * are on both sides.
18
+ *
19
+ * When an island hydrates comes from the module's `hydrate` export:
20
+ *
21
+ * export const hydrate = "visible"; // every component in the file
22
+ * export const hydrate = { Chart: "visible", Legend: "idle" }; // per component; others "load"
23
+ */
24
+ const FUNCTION_TYPES = /* @__PURE__ */ new Set([
25
+ "FunctionDeclaration",
26
+ "FunctionExpression",
27
+ "ArrowFunctionExpression"
28
+ ]);
29
+ function isComponentName(name) {
30
+ return /^[A-Z]/.test(name) && /[a-z]/.test(name);
31
+ }
32
+ const VALUE_TYPES = /* @__PURE__ */ new Set([
33
+ "Literal",
34
+ "ArrayExpression",
35
+ "ObjectExpression",
36
+ "TemplateLiteral",
37
+ "UnaryExpression",
38
+ "BinaryExpression"
39
+ ]);
40
+ /** Reads the `hydrate` export: a strategy for every component, or one per component. */
41
+ function readStrategies(program, fail) {
42
+ const byName = /* @__PURE__ */ new Map();
43
+ const check = (value, node) => {
44
+ if (typeof value !== "string" || !ISLAND_STRATEGIES.includes(value)) fail(`hydrate must be one of ${ISLAND_STRATEGIES.map((s) => `"${s}"`).join(", ")}`, node);
45
+ return value;
46
+ };
47
+ for (const node of program.body ?? []) {
48
+ if (node.type !== "ExportNamedDeclaration" || node.declaration?.type !== "VariableDeclaration") continue;
49
+ for (const declarator of node.declaration.declarations ?? []) {
50
+ if (declarator.id?.type !== "Identifier" || declarator.id.name !== "hydrate") continue;
51
+ let init = declarator.init;
52
+ while (init && (init.type === "TSAsExpression" || init.type === "TSSatisfiesExpression")) init = init.expression;
53
+ if (init?.type === "Literal") return {
54
+ all: check(init.value, init),
55
+ byName
56
+ };
57
+ if (init?.type === "ObjectExpression") {
58
+ for (const property of init.properties ?? []) {
59
+ const key = property.key?.type === "Identifier" ? property.key.name : property.key?.value;
60
+ if (property.type !== "Property" || property.computed || typeof key !== "string" || property.value?.type !== "Literal") fail("hydrate must be a string, or an object of strings: { Chart: \"visible\" }", property);
61
+ byName.set(key, check(property.value.value, property.value));
62
+ }
63
+ return { byName };
64
+ }
65
+ fail("hydrate must be written as a literal: \"visible\", or { Chart: \"visible\" }", declarator);
66
+ }
67
+ }
68
+ return { byName };
69
+ }
70
+ /** Wraps a `"use client"` module's components as islands, or returns null for any other module. */
71
+ function transformClientModule(options) {
72
+ const { code, id, root } = options;
73
+ if (!hasModuleDirective(code, options.directive ?? "use client")) return null;
74
+ const file = id.split("?", 1)[0];
75
+ const relative = path.relative(root, file).split(path.sep).join("/");
76
+ const program = options.parse(code);
77
+ const fail = (message, node) => {
78
+ throw new ActionCompileError(message, file, code, node.start);
79
+ };
80
+ const strategies = readStrategies(program, fail);
81
+ const strategyOf = (name) => {
82
+ const configured = options.strategy?.(name);
83
+ if (configured !== void 0 && !ISLAND_STRATEGIES.includes(configured)) throw new Error(`islx: strategy for ${name} must be one of ${ISLAND_STRATEGIES.join(", ")}`);
84
+ return configured ?? strategies.byName.get(name) ?? strategies.all ?? "load";
85
+ };
86
+ const output = new MagicString(code);
87
+ const wrapped = [];
88
+ for (const node of program.body ?? []) if (node.type === "ExportNamedDeclaration" && !node.source && node.exportKind !== "type") {
89
+ const declaration = node.declaration;
90
+ if (declaration) {
91
+ const names = declaration.type === "VariableDeclaration" ? declaration.declarations.flatMap((d) => d.id?.type === "Identifier" && !(d.init && VALUE_TYPES.has(d.init.type)) ? [d.id.name] : []) : declaration.id?.name ? [declaration.id.name] : [];
92
+ const declared = declaration.type === "VariableDeclaration" ? declaration.declarations.length : names.length;
93
+ const components = names.filter(isComponentName);
94
+ if (components.length === 0 || String(declaration.type).startsWith("TS")) continue;
95
+ if (components.length !== declared) fail("Export components and other values in separate statements", declaration);
96
+ output.remove(node.start, declaration.start);
97
+ for (const name of components) wrapped.push({
98
+ local: name,
99
+ exportName: name
100
+ });
101
+ continue;
102
+ }
103
+ const kept = [];
104
+ for (const specifier of node.specifiers ?? []) {
105
+ const exported = specifier.exported?.name ?? specifier.exported?.value;
106
+ const local = specifier.local?.name ?? specifier.local?.value;
107
+ if (specifier.exportKind !== "type" && (isComponentName(exported) || exported === "default")) wrapped.push({
108
+ local,
109
+ exportName: exported
110
+ });
111
+ else kept.push(output.slice(specifier.start, specifier.end));
112
+ }
113
+ output.overwrite(node.start, node.end, kept.length > 0 ? `export { ${kept.join(", ")} };` : "");
114
+ } else if (node.type === "ExportDefaultDeclaration") {
115
+ const declaration = node.declaration;
116
+ if (FUNCTION_TYPES.has(declaration.type) || declaration.type === "ClassDeclaration" || declaration.type === "ClassExpression") {
117
+ if (declaration.id?.name) {
118
+ output.remove(node.start, declaration.start);
119
+ wrapped.push({
120
+ local: declaration.id.name,
121
+ exportName: "default"
122
+ });
123
+ } else {
124
+ output.overwrite(node.start, declaration.start, "const $$islx_default = ");
125
+ wrapped.push({
126
+ local: "$$islx_default",
127
+ exportName: "default"
128
+ });
129
+ }
130
+ } else if (declaration.type === "Identifier" || declaration.type.endsWith("Expression")) {
131
+ output.overwrite(node.start, declaration.start, "const $$islx_default = ");
132
+ if (!code.slice(declaration.end, node.end).includes(";")) output.appendLeft(declaration.end, ";");
133
+ wrapped.push({
134
+ local: "$$islx_default",
135
+ exportName: "default"
136
+ });
137
+ }
138
+ }
139
+ if (wrapped.length === 0) return null;
140
+ const runtime = options.runtime ?? "@farm.js/islx/react";
141
+ const src = options.reference(relative);
142
+ const lines = [...wrapped.map(({ local, exportName }, index) => {
143
+ return `const $$islx_island_${index} = $$islx_island(${local}, ${src}, ${JSON.stringify(exportName)}, ${JSON.stringify(strategyOf(exportName === "default" ? "default" : exportName))});`;
144
+ }), `export { ${wrapped.map(({ exportName }, index) => `$$islx_island_${index} as ${exportName}`).join(", ")} };`];
145
+ const imports = [`import { createIsland as $$islx_island } from ${JSON.stringify(runtime)};`, ...(options.sideEffects ?? []).map((module) => `import ${JSON.stringify(module)};`)];
146
+ output.prepend(`${imports.join("\n")}\n`);
147
+ output.append(`\n${lines.join("\n")}\n`);
148
+ return {
149
+ code: output.toString(),
150
+ map: output.generateMap({
151
+ hires: true,
152
+ source: file
153
+ }),
154
+ islands: wrapped.map(({ exportName }) => ({
155
+ exportName,
156
+ strategy: strategyOf(exportName)
157
+ }))
158
+ };
159
+ }
160
+ // src/vite.ts
161
+ /**
162
+ * @farm.js/islx/vite: islx for Vite 6 and later (the Environment API).
163
+ *
164
+ * import react from "@vitejs/plugin-react";
165
+ * import { islx } from "@farm.js/islx/vite";
166
+ * export default defineConfig({ plugins: [react(), islx()] });
167
+ *
168
+ * - Server environments: `"use client"` components render as islands, `"use server"` exports
169
+ * and inline actions register.
170
+ * - The client environment: `"use server"` modules become references; inline actions are
171
+ * refused; the browser entry hydrates islands.
172
+ * - `vite build` builds the server first, which finds the client components pages use, then the
173
+ * browser with exactly those (plus `clientComponents.include`), each in a chunk of its own that
174
+ * the browser entry imports when an island needs it. An island names its module by its path
175
+ * from the root; the server build learns the entry's URL once the browser build has named it.
176
+ */
177
+ const RUNTIME_ID = "virtual:islx/runtime";
178
+ const ENTRY_ID = "virtual:islx/client-entry";
179
+ const CLIENT_HOOKS_ID = "virtual:islx/hooks-client";
180
+ const SERVER_HOOKS_ID = "virtual:islx/hooks-server";
181
+ const BROWSER_GLOBALS = /* @__PURE__ */ new Set([
182
+ "window",
183
+ "document",
184
+ "location",
185
+ "history",
186
+ "navigator",
187
+ "screen",
188
+ "localStorage",
189
+ "sessionStorage",
190
+ "alert",
191
+ "confirm",
192
+ "prompt",
193
+ "requestAnimationFrame",
194
+ "cancelAnimationFrame",
195
+ "requestIdleCallback",
196
+ "cancelIdleCallback",
197
+ "IntersectionObserver",
198
+ "MutationObserver",
199
+ "ResizeObserver",
200
+ "HTMLElement",
201
+ "Element",
202
+ "Node",
203
+ "CustomEvent",
204
+ "Event",
205
+ "matchMedia",
206
+ "getComputedStyle",
207
+ "innerWidth",
208
+ "innerHeight",
209
+ "scrollX",
210
+ "scrollY",
211
+ "self"
212
+ ]);
213
+ /**
214
+ * The source of a hooks module made from callbacks. Each callback is copied as written, so it
215
+ * must not use anything from where it was written: an outside variable, an import.
216
+ */
217
+ function serializeHooks(hooks, where, parse) {
218
+ const entries = [];
219
+ for (const [name, value] of Object.entries(hooks)) {
220
+ if (value === void 0) continue;
221
+ if (typeof value !== "function") throw new Error(`islx: hooks.${where}.${name} must be a function`);
222
+ const source = Function.prototype.toString.call(value);
223
+ if (source.includes("[native code]")) throw new Error(`islx: hooks.${where}.${name} must be written in the config, not a built-in or bound function`);
224
+ const expression = parse("hook.js", `(${source});`).errors.length === 0;
225
+ entries.push(expression ? `${JSON.stringify(name)}: ${source}` : source);
226
+ }
227
+ const code = `export default {\n${entries.join(",\n")}\n};\n`;
228
+ const program = parse("hooks.js", code);
229
+ const { globals } = analyze(program);
230
+ const outside = [...globals.keys()].filter((name) => where === "client" ? !(name in globalThis) && !BROWSER_GLOBALS.has(name) : BROWSER_GLOBALS.has(name) || !(name in globalThis));
231
+ let imports = false;
232
+ walk(program, { enter(node) {
233
+ if (node.type === "ImportExpression") imports = true;
234
+ } });
235
+ if (outside.length > 0 || imports) {
236
+ const what = imports ? "`import()`" : outside.map((name) => `\`${name}\``).join(", ");
237
+ throw new Error(`islx: hooks.${where} uses ${what}, which does not exist where the hook runs: hooks written in the config are copied into the ${where === "client" ? "browser" : "server"} build as source. Use a global${where === "client" ? " (window.analytics)" : ""}, or put the hooks in a module and pass its path: hooks: { ${where}: "./src/islx.${where}.ts" }.`);
238
+ }
239
+ return code;
240
+ }
241
+ /** Stand for the browser entry's URL, and the files each client module needs, in the server
242
+ * build until the browser build names them. */
243
+ const ENTRY_PLACEHOLDER = "__islx_client_entry_url__";
244
+ const MODULES_PLACEHOLDER = "__islx_client_modules__";
245
+ const SCRIPT = /\.[cm]?[jt]sx?$/;
246
+ async function createParser() {
247
+ const withErrors = (result) => Object.assign(result.program, { errors: result.errors ?? [] });
248
+ const vite = await import("vite");
249
+ if (typeof vite.parseSync === "function") return (file, code) => withErrors(vite.parseSync(file, code));
250
+ try {
251
+ const oxc = await import("oxc-parser");
252
+ return (file, code) => withErrors(oxc.parseSync(file, code));
253
+ } catch {
254
+ throw new Error("@farm.js/islx/vite needs Vite 8, or oxc-parser installed with an older Vite");
255
+ }
256
+ }
257
+ /** A tiny glob matcher: `**`, `*` and `?`, on paths from the root. */
258
+ function globToRegExp(glob) {
259
+ let pattern = "";
260
+ for (let index = 0; index < glob.length; index++) {
261
+ const char = glob[index];
262
+ if (char === "*" && glob[index + 1] === "*") {
263
+ pattern += glob[index + 2] === "/" ? "(?:.*/)?" : ".*";
264
+ index += glob[index + 2] === "/" ? 2 : 1;
265
+ } else if (char === "*") pattern += "[^/]*";
266
+ else if (char === "?") pattern += "[^/]";
267
+ else pattern += char.replace(/[.+^${}()|[\]\\]/g, "\\$&");
268
+ }
269
+ return new RegExp(`^${pattern.replace(/^\.\//, "")}$`);
270
+ }
271
+ async function listFiles(root, directory = root) {
272
+ const entries = await readdir(directory, { withFileTypes: true }).catch(() => []);
273
+ const files = [];
274
+ for (const entry of entries) {
275
+ if (entry.name === "node_modules" || entry.name.startsWith(".") || entry.name === "dist") continue;
276
+ const full = path.join(directory, entry.name);
277
+ if (entry.isDirectory()) files.push(...await listFiles(root, full));
278
+ else if (SCRIPT.test(entry.name)) files.push(full);
279
+ }
280
+ return files;
281
+ }
282
+ async function listOutput(directory) {
283
+ const entries = await readdir(directory, { withFileTypes: true }).catch(() => []);
284
+ const files = [];
285
+ for (const entry of entries) {
286
+ const full = path.join(directory, entry.name);
287
+ if (entry.isDirectory()) files.push(...await listOutput(full));
288
+ else if (/\.[cm]?js$/.test(entry.name)) files.push(full);
289
+ }
290
+ return files;
291
+ }
292
+ const toPosix = (value) => value.split(path.sep).join("/");
293
+ const RESERVED_DIRECTIVES = /* @__PURE__ */ new Set(["use strict", "use asm"]);
294
+ /** The directives to use, refusing ones that would make a file mean two things. */
295
+ function resolveDirectives(directives = {}) {
296
+ const client = directives.client ?? "use client";
297
+ const server = directives.server ?? "use server";
298
+ for (const [kind, value] of [["client", client], ["server", server]]) if (typeof value !== "string" || !/^[\w-]+( [\w-]+)*$/.test(value) || RESERVED_DIRECTIVES.has(value)) throw new Error(`islx: directives.${kind} must be a plain directive such as "use island", not ${JSON.stringify(value)}`);
299
+ if (client === server) throw new Error(`islx: directives.client and directives.server are both ${JSON.stringify(client)}`);
300
+ return {
301
+ client,
302
+ server
303
+ };
304
+ }
305
+ function islx(options = {}) {
306
+ const directives = resolveDirectives(options.directives);
307
+ let config;
308
+ let parse;
309
+ let preamble = false;
310
+ const include = (options.clientComponents?.include ?? []).map(globToRegExp);
311
+ const exclude = (options.clientComponents?.exclude ?? []).map(globToRegExp);
312
+ /** Client modules the server build rendered, by path from the root. */
313
+ const discovered = /* @__PURE__ */ new Set();
314
+ /** The browser entry's URL, once the browser build named it. */
315
+ let entryUrl;
316
+ /** The files each client module needs, once the browser build named them. */
317
+ const moduleFiles = {};
318
+ const buildKey = randomBytes(32).toString("base64url");
319
+ const isServer = (name) => options.serverEnvironments ? options.serverEnvironments.includes(name) : name !== "client";
320
+ const relativeOf = (id) => toPosix(path.relative(config.root, id.split("?", 1)[0]));
321
+ const excluded = (relative) => exclude.some((pattern) => pattern.test(relative));
322
+ const isBuild = () => config.command === "build";
323
+ const clientInputs = async () => {
324
+ const inputs = new Set(discovered);
325
+ if (include.length > 0) for (const file of await listFiles(config.root)) {
326
+ const relative = relativeOf(file);
327
+ if (!include.some((pattern) => pattern.test(relative)) || excluded(relative)) continue;
328
+ if ((await readFile(file, "utf8")).includes("use client")) inputs.add(relative);
329
+ }
330
+ return [...inputs].sort();
331
+ };
332
+ return [
333
+ {
334
+ name: "islx",
335
+ enforce: "pre",
336
+ sharedDuringBuild: true,
337
+ config(user) {
338
+ const clientBuild = user.environments?.client?.build;
339
+ const input = clientBuild?.rollupOptions?.input;
340
+ return {
341
+ builder: user.builder ?? {},
342
+ environments: { client: {
343
+ optimizeDeps: { include: [
344
+ "react",
345
+ "react/jsx-runtime",
346
+ "react/jsx-dev-runtime",
347
+ "react-dom",
348
+ "react-dom/client"
349
+ ] },
350
+ build: {
351
+ outDir: clientBuild?.outDir ?? "dist/client",
352
+ rollupOptions: { input: {
353
+ ...typeof input === "string" ? { index: input } : Array.isArray(input) ? Object.fromEntries(input.map((entry, index) => [`input${index}`, entry])) : input,
354
+ "islx-entry": ENTRY_ID
355
+ } }
356
+ }
357
+ } }
358
+ };
359
+ },
360
+ async configResolved(resolved) {
361
+ config = resolved;
362
+ parse = await createParser();
363
+ preamble = resolved.plugins.some((plugin) => plugin.name === "vite:react-virtual-preamble");
364
+ },
365
+ resolveId(id) {
366
+ if (id === RUNTIME_ID || id === ENTRY_ID || id === CLIENT_HOOKS_ID || id === SERVER_HOOKS_ID) return `\0${id}`;
367
+ },
368
+ async load(id) {
369
+ if (id === `\0${RUNTIME_ID}`) {
370
+ const entry = isBuild() ? ENTRY_PLACEHOLDER : `${config.base}@id/__x00__${ENTRY_ID}`;
371
+ const modules = isBuild() ? `JSON.parse(${JSON.stringify(MODULES_PLACEHOLDER)})` : "{}";
372
+ return [
373
+ `import { setBuildDefaults, setServerHooks } from "@farm.js/islx/server";`,
374
+ `import hooks from ${JSON.stringify(SERVER_HOOKS_ID)};`,
375
+ `setBuildDefaults({ entry: ${JSON.stringify(entry)}, key: ${JSON.stringify(buildKey)}, modules: ${modules} });`,
376
+ `setServerHooks(hooks);`
377
+ ].join("\n");
378
+ }
379
+ if (id === `\0${CLIENT_HOOKS_ID}` || id === `\0${SERVER_HOOKS_ID}`) {
380
+ const where = id === `\0${CLIENT_HOOKS_ID}` ? "client" : "server";
381
+ const hooks = options.hooks?.[where];
382
+ if (hooks === void 0) return "export default undefined;";
383
+ if (typeof hooks === "string") return `export { default } from ${JSON.stringify(path.resolve(config.root, hooks))};`;
384
+ return serializeHooks(hooks, where, parse);
385
+ }
386
+ if (id === `\0${ENTRY_ID}`) {
387
+ const load = isBuild() ? `const modules = {\n${(await clientInputs()).map((relative) => ` ${JSON.stringify(relative)}: () => import(${JSON.stringify(path.resolve(config.root, relative))}),`).join("\n")}\n};\nconst load = (src) => modules[src] ? modules[src]() : Promise.reject(new Error("islx: no client module " + src));` : `const root = new URL(${JSON.stringify(`file://${toPosix(config.root)}/`)});\nconst load = (src) => import(/* @vite-ignore */ src.startsWith("../") ? "/@fs" + new URL(src, root).pathname : ${JSON.stringify(config.base)} + src);`;
388
+ return [
389
+ ...preamble && !isBuild() ? [`import "@vitejs/plugin-react/preamble";`] : [],
390
+ `import { createHydrationRuntime, refreshDocument, scheduleHydration, swapDocument } from "@farm.js/islx/react/client";`,
391
+ `import { enhanceForms, setActionNavigator, setClientHooks, startNavigation, navigate } from "@farm.js/islx/client";`,
392
+ `import hooks from ${JSON.stringify(CLIENT_HOOKS_ID)};`,
393
+ `setClientHooks(hooks);`,
394
+ load,
395
+ `const runtime = createHydrationRuntime({ load, schedule: scheduleHydration });`,
396
+ `setActionNavigator({ refresh: () => refreshDocument(runtime), navigate: (href) => navigate(href) });`,
397
+ `enhanceForms();`,
398
+ ...options.navigation === false ? [] : [`startNavigation({ swap: (next) => swapDocument(runtime, next), viewTransition: ${typeof options.navigation === "object" && options.navigation.viewTransition === true} });`],
399
+ `runtime.hydrate(document);`,
400
+ `export { runtime };`
401
+ ].join("\n");
402
+ }
403
+ },
404
+ transform(code, id) {
405
+ if (id.startsWith("\0") || !SCRIPT.test(id.split("?", 1)[0])) return null;
406
+ const library = id.includes("/node_modules/");
407
+ const clientDirective = library ? "use client" : directives.client;
408
+ if (!code.includes(clientDirective) && (library || !code.includes(directives.server))) return null;
409
+ const file = id.split("?", 1)[0];
410
+ const server = isServer(this.environment.name);
411
+ const relative = relativeOf(file);
412
+ const parseFile = (source) => parse(file, source);
413
+ if (server && !excluded(relative)) {
414
+ const island = transformClientModule({
415
+ code,
416
+ id: file,
417
+ root: config.root,
418
+ parse: parseFile,
419
+ reference: (relative) => {
420
+ discovered.add(relative);
421
+ return JSON.stringify(relative);
422
+ },
423
+ sideEffects: [RUNTIME_ID],
424
+ directive: clientDirective
425
+ });
426
+ if (island) {
427
+ if (!library) transformActions({
428
+ code,
429
+ id: file,
430
+ root: config.root,
431
+ environment: "client",
432
+ parse: parseFile,
433
+ directive: directives.server
434
+ });
435
+ return {
436
+ code: island.code,
437
+ map: island.map
438
+ };
439
+ }
440
+ }
441
+ if (library) return null;
442
+ const actions = transformActions({
443
+ code,
444
+ id: file,
445
+ root: config.root,
446
+ environment: server ? "server" : "client",
447
+ parse: parseFile,
448
+ directive: directives.server
449
+ });
450
+ if (!actions) return null;
451
+ return {
452
+ code: server ? `import ${JSON.stringify(RUNTIME_ID)};\n${actions.code}` : actions.code,
453
+ map: server ? null : actions.map
454
+ };
455
+ }
456
+ },
457
+ {
458
+ name: "islx:reload",
459
+ apply: "serve",
460
+ hotUpdate({ file, modules, server }) {
461
+ if (!isServer(this.environment.name) || modules.length === 0) return;
462
+ const client = server.environments.client;
463
+ if (client?.moduleGraph.getModulesByFile(file)?.size) return;
464
+ client?.hot.send({ type: "full-reload" });
465
+ }
466
+ },
467
+ {
468
+ name: "islx:build",
469
+ sharedDuringBuild: true,
470
+ async buildApp(builder) {
471
+ const servers = Object.values(builder.environments).filter((environment) => isServer(environment.name));
472
+ for (const environment of servers) await builder.build(environment);
473
+ await builder.build(builder.environments.client);
474
+ if (!entryUrl) throw new Error("islx: the browser build did not emit the islx entry");
475
+ for (const environment of servers) {
476
+ const outDir = path.resolve(config.root, environment.config.build.outDir);
477
+ for (const file of await listOutput(outDir)) {
478
+ const source = await readFile(file, "utf8");
479
+ if (!source.includes(ENTRY_PLACEHOLDER) && !source.includes(MODULES_PLACEHOLDER)) continue;
480
+ const modules = JSON.stringify(JSON.stringify(moduleFiles)).slice(1, -1);
481
+ await writeFile(file, source.replaceAll(ENTRY_PLACEHOLDER, entryUrl).replaceAll(MODULES_PLACEHOLDER, modules));
482
+ }
483
+ }
484
+ },
485
+ generateBundle(_options, bundle) {
486
+ if (this.environment.name !== "client") return;
487
+ const url = (fileName) => `${config.base}${fileName}`;
488
+ for (const chunk of Object.values(bundle)) {
489
+ if (chunk.type !== "chunk" || !chunk.facadeModuleId) continue;
490
+ if (chunk.isEntry && chunk.facadeModuleId === `\0${ENTRY_ID}`) entryUrl = url(chunk.fileName);
491
+ else if (chunk.isDynamicEntry && !chunk.facadeModuleId.startsWith("\0")) moduleFiles[relativeOf(chunk.facadeModuleId)] = [chunk.fileName, ...chunk.imports].map(url);
492
+ }
493
+ }
494
+ }
495
+ ];
496
+ }
497
+ export { islx as default, islx, resolveDirectives, serializeHooks };
package/package.json CHANGED
@@ -1,6 +1,123 @@
1
1
  {
2
2
  "name": "@farm.js/islx",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.1",
4
+ "description": "A renderer-agnostic wire format for server-rendered islands: typed props, values sent once, server actions, and partial navigations.",
5
+ "keywords": [
6
+ "islands",
7
+ "server-components",
8
+ "server-actions",
9
+ "ssr",
10
+ "hydration",
11
+ "react",
12
+ "vite"
13
+ ],
14
+ "license": "MIT",
15
+ "author": "Farming Labs",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/farming-labs/islx.git"
19
+ },
20
+ "homepage": "https://github.com/farming-labs/islx#readme",
21
+ "type": "module",
22
+ "sideEffects": [
23
+ "./dist/react/server.mjs"
24
+ ],
25
+ "engines": {
26
+ "node": "^20.19.0 || >=22.12.0"
27
+ },
28
+ "files": [
29
+ "dist",
30
+ "SPEC.md",
31
+ "CHANGELOG.md"
32
+ ],
33
+ "exports": {
34
+ ".": {
35
+ "types": "./dist/index.d.mts",
36
+ "default": "./dist/index.mjs"
37
+ },
38
+ "./client": {
39
+ "types": "./dist/client.d.mts",
40
+ "default": "./dist/client.mjs"
41
+ },
42
+ "./server": {
43
+ "types": "./dist/server.d.mts",
44
+ "default": "./dist/server.mjs"
45
+ },
46
+ "./compiler": {
47
+ "types": "./dist/compiler.d.mts",
48
+ "default": "./dist/compiler.mjs"
49
+ },
50
+ "./react": {
51
+ "types": "./dist/react.d.mts",
52
+ "default": "./dist/react.mjs"
53
+ },
54
+ "./react/server": {
55
+ "types": "./dist/react/server.d.mts",
56
+ "default": "./dist/react/server.mjs"
57
+ },
58
+ "./react/client": {
59
+ "types": "./dist/react/client.d.mts",
60
+ "default": "./dist/react/client.mjs"
61
+ },
62
+ "./vite": {
63
+ "types": "./dist/vite.d.mts",
64
+ "default": "./dist/vite.mjs"
65
+ },
66
+ "./package.json": "./package.json"
67
+ },
68
+ "scripts": {
69
+ "build": "tsdown",
70
+ "test": "vitest run",
71
+ "typecheck": "tsc --noEmit",
72
+ "lint": "oxlint src test",
73
+ "format": "oxfmt src test",
74
+ "format:check": "oxfmt --check src test",
75
+ "prepublishOnly": "pnpm build",
76
+ "test:e2e": "playwright test",
77
+ "release:check": "pnpm build && pnpm typecheck && pnpm lint && pnpm format:check && pnpm test && npm pack --dry-run"
78
+ },
79
+ "devDependencies": {
80
+ "@playwright/test": "^1.64.1",
81
+ "@types/estree": "^1.0.10",
82
+ "@types/node": "^20.19.43",
83
+ "@types/react": "^19.3.0",
84
+ "@types/react-dom": "^19.3.0",
85
+ "@vitejs/plugin-react": "^6.1.2",
86
+ "jsdom": "25.0.1",
87
+ "oxc-parser": "0.156.0",
88
+ "oxfmt": "0.27.0",
89
+ "oxlint": "1.42.0",
90
+ "react": "19.2.8",
91
+ "react-dom": "19.2.8",
92
+ "tsdown": "0.15.7",
93
+ "typescript": "5.9.3",
94
+ "vite": "8.3.5",
95
+ "vitest": "3.2.7"
96
+ },
97
+ "packageManager": "pnpm@10.9.0",
98
+ "publishConfig": {
99
+ "access": "public"
100
+ },
101
+ "dependencies": {
102
+ "estree-walker": "3.0.3",
103
+ "is-reference": "3.0.3",
104
+ "magic-string": "0.30.21",
105
+ "periscopic": "4.0.3"
106
+ },
107
+ "peerDependencies": {
108
+ "react": ">=19",
109
+ "react-dom": ">=19",
110
+ "vite": ">=6"
111
+ },
112
+ "peerDependenciesMeta": {
113
+ "react": {
114
+ "optional": true
115
+ },
116
+ "react-dom": {
117
+ "optional": true
118
+ },
119
+ "vite": {
120
+ "optional": true
121
+ }
122
+ }
123
+ }