@jxsuite/server 9.3.1 → 9.4.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/README.md +11 -8
- package/package.json +22 -18
- package/src/class-schema.ts +201 -0
- package/src/code-api.ts +195 -92
- package/src/collab.ts +58 -37
- package/src/data-api.ts +17 -52
- package/src/dev.ts +6 -2
- package/src/extension-catalog.ts +4 -5
- package/src/jx-mounts.ts +78 -29
- package/src/live-preview.ts +10 -35
- package/src/packages.ts +20 -8
- package/src/preview-bundles.ts +93 -0
- package/src/project-server.ts +7 -2
- package/src/project-state/host.ts +2 -3
- package/src/refactor/scan.ts +5 -2
- package/src/resolve.ts +43 -3
- package/src/server.ts +12 -9
- package/src/site-output.ts +3 -1
- package/src/studio-api.ts +86 -315
- package/src/types.ts +2 -1
package/src/collab.ts
CHANGED
|
@@ -9,15 +9,18 @@
|
|
|
9
9
|
* last saved as the base, so a save over a file that changed under it is refused and the refusal
|
|
10
10
|
* reaches every participant (`doc-conflict`). Outside it, a room is keyed by its path and saves
|
|
11
11
|
* unconditionally, as before. A room's Y.Text source seeds from the file on disk. Persistence is
|
|
12
|
-
* EXPLICIT: the shared source is written back to disk only on an explicit flush (Cmd+S / Save) and
|
|
13
|
-
*
|
|
14
|
-
* only in the room's in-memory Y.Doc until saved — non-collab consumers
|
|
15
|
-
* plain editors) intentionally keep working off the last-saved file until
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
12
|
+
* EXPLICIT: the shared source is written back to disk only on an explicit flush (Cmd+S / Save), and
|
|
13
|
+
* stopping the server writes nothing (collab.md §1.2). Unsaved collaborative edits therefore live
|
|
14
|
+
* only in the room's in-memory Y.Doc until saved, and are dropped with it — non-collab consumers
|
|
15
|
+
* (preview, live reload, plain editors) intentionally keep working off the last-saved file until
|
|
16
|
+
* then. A flush is answered once: a write that fails, or a save the host refuses, rejects with the
|
|
17
|
+
* reason, which the host sends to the client as the `flush-ack`'s `error` and leaves the room
|
|
18
|
+
* unsaved. The host owns the room-level dirty signal broadcast to every peer; the embedder just
|
|
19
|
+
* tells it a persist landed via `markPersisted`. Genuinely external file changes (not our own
|
|
20
|
+
* write-back echo) bump the doc's epoch and reset subscribers, per the contract, except that a room
|
|
21
|
+
* inside the project holding unsaved edits keeps them and tells its participants of the conflict
|
|
22
|
+
* instead. No persistence beyond the files themselves: this is deliberately a reference
|
|
23
|
+
* implementation.
|
|
21
24
|
*/
|
|
22
25
|
|
|
23
26
|
import { randomUUID } from "node:crypto";
|
|
@@ -89,7 +92,10 @@ export interface CollabRegistry {
|
|
|
89
92
|
websocket: ServeWebSocketHandler<CollabSocketData>;
|
|
90
93
|
/** Watcher hook: a file changed on disk (absolute path). Echoes of our write-back are ignored. */
|
|
91
94
|
handleExternalChange: (absPath: string) => void;
|
|
92
|
-
/**
|
|
95
|
+
/**
|
|
96
|
+
* Tear everything down. Saves already in flight settle; nothing else is written, so a room's
|
|
97
|
+
* unsaved edits are dropped with it (collab.md §1.2).
|
|
98
|
+
*/
|
|
93
99
|
stop: () => Promise<void>;
|
|
94
100
|
}
|
|
95
101
|
|
|
@@ -124,7 +130,10 @@ export function createCollabRegistry(opts: {
|
|
|
124
130
|
const ownWrites = new Set<string>();
|
|
125
131
|
|
|
126
132
|
const destroyTimers = new Map<string, ReturnType<typeof setTimeout>>();
|
|
127
|
-
/**
|
|
133
|
+
/**
|
|
134
|
+
* Rooms with unsaved edits (source changed since the last persist): what a project switch saves
|
|
135
|
+
* before it closes the rooms it covers. Stopping the server does not read it.
|
|
136
|
+
*/
|
|
128
137
|
const pendingPersist = new Set<string>();
|
|
129
138
|
/** Content we last wrote (or are about to write) per path — the watcher-echo signature. */
|
|
130
139
|
const lastWritten = new Map<string, string>();
|
|
@@ -235,14 +244,15 @@ export function createCollabRegistry(opts: {
|
|
|
235
244
|
): Promise<void> => {
|
|
236
245
|
const hash = await contentHash(source);
|
|
237
246
|
const base = override === undefined ? room.base : override.baseHash;
|
|
247
|
+
const name = relative(room.root, room.abs).replaceAll("\\", "/");
|
|
238
248
|
if (hash === base) {
|
|
239
249
|
room.base = hash;
|
|
240
250
|
pendingPersist.delete(key);
|
|
241
|
-
host.markPersisted(key);
|
|
251
|
+
host.markPersisted(key, source);
|
|
242
252
|
return;
|
|
243
253
|
}
|
|
244
254
|
if (through === undefined && projectEvents?.root !== room.root) {
|
|
245
|
-
|
|
255
|
+
throw new Error(`Could not write ${name}: its project is no longer open.`);
|
|
246
256
|
}
|
|
247
257
|
const writeId = `collab-${randomUUID()}`;
|
|
248
258
|
ownWrites.add(writeId);
|
|
@@ -257,21 +267,27 @@ export function createCollabRegistry(opts: {
|
|
|
257
267
|
if (result.ok) {
|
|
258
268
|
room.base = result.hash;
|
|
259
269
|
pendingPersist.delete(key);
|
|
260
|
-
host.markPersisted(key);
|
|
270
|
+
host.markPersisted(key, source);
|
|
261
271
|
return;
|
|
262
272
|
}
|
|
263
273
|
ownWrites.delete(writeId);
|
|
264
274
|
host.conflict(key, { diskHash: result.conflict.diskHash, docId: result.conflict.docId });
|
|
265
|
-
} catch {
|
|
266
|
-
// The write failed (or the host could not start): the
|
|
275
|
+
} catch (error) {
|
|
276
|
+
// The write failed (or the host could not start): the room stays unsaved, and the flush says why.
|
|
267
277
|
ownWrites.delete(writeId);
|
|
278
|
+
throw new Error(
|
|
279
|
+
`Could not write ${name}: ${error instanceof Error ? error.message : String(error)}`,
|
|
280
|
+
{ cause: error },
|
|
281
|
+
);
|
|
268
282
|
}
|
|
283
|
+
throw new Error(`${name} changed on disk since it was opened, so nothing was saved.`);
|
|
269
284
|
};
|
|
270
285
|
|
|
271
286
|
/** Save a room keyed by its path, unconditionally: last writer wins, as before (§11.3). */
|
|
272
287
|
const persistPlain = async (path: string, source: string): Promise<void> => {
|
|
273
288
|
if (lastWritten.get(path) === source) {
|
|
274
289
|
pendingPersist.delete(path);
|
|
290
|
+
host.markPersisted(path, source);
|
|
275
291
|
return;
|
|
276
292
|
}
|
|
277
293
|
// Optimistic: closes the watcher-echo race (our own write must not read back as external).
|
|
@@ -279,11 +295,15 @@ export function createCollabRegistry(opts: {
|
|
|
279
295
|
try {
|
|
280
296
|
await writeFile(absPathFor(path), source, "utf8");
|
|
281
297
|
pendingPersist.delete(path);
|
|
282
|
-
// Tell the host
|
|
283
|
-
host.markPersisted(path);
|
|
284
|
-
} catch {
|
|
298
|
+
// Tell the host what is durable now: it resets the dirty baseline and broadcasts clean.
|
|
299
|
+
host.markPersisted(path, source);
|
|
300
|
+
} catch (error) {
|
|
285
301
|
// Write failed — clear the optimistic signature so the next explicit save retries.
|
|
286
302
|
lastWritten.delete(path);
|
|
303
|
+
throw new Error(
|
|
304
|
+
`Could not write ${path}: ${error instanceof Error ? error.message : String(error)}`,
|
|
305
|
+
{ cause: error },
|
|
306
|
+
);
|
|
287
307
|
}
|
|
288
308
|
};
|
|
289
309
|
|
|
@@ -292,13 +312,15 @@ export function createCollabRegistry(opts: {
|
|
|
292
312
|
* so two saves pressed together never both name the base the first one replaces.
|
|
293
313
|
*/
|
|
294
314
|
const serialize = (key: string, save: () => Promise<void>): Promise<void> => {
|
|
295
|
-
|
|
315
|
+
// An earlier save that failed does not stop this one: it answered its own flush.
|
|
316
|
+
const next = (persisting.get(key) ?? Promise.resolve()).catch(() => {}).then(save);
|
|
296
317
|
persisting.set(key, next);
|
|
297
|
-
|
|
318
|
+
const done = () => {
|
|
298
319
|
if (persisting.get(key) === next) {
|
|
299
320
|
persisting.delete(key);
|
|
300
321
|
}
|
|
301
|
-
}
|
|
322
|
+
};
|
|
323
|
+
next.then(done, done);
|
|
302
324
|
return next;
|
|
303
325
|
};
|
|
304
326
|
|
|
@@ -315,7 +337,9 @@ export function createCollabRegistry(opts: {
|
|
|
315
337
|
serialize(key, async () => {
|
|
316
338
|
const source = host.sourceOf(key);
|
|
317
339
|
if (source === null) {
|
|
318
|
-
|
|
340
|
+
// The host only asks for a room it holds: this keeps an embedder change from turning a
|
|
341
|
+
// Missing room into a silent success.
|
|
342
|
+
throw new Error("The document is not open for co-editing, so nothing was saved.");
|
|
319
343
|
}
|
|
320
344
|
const room = hosted.get(key);
|
|
321
345
|
await (room === undefined
|
|
@@ -378,8 +402,8 @@ export function createCollabRegistry(opts: {
|
|
|
378
402
|
host.resetDoc(path);
|
|
379
403
|
},
|
|
380
404
|
onSourceChange: (path) => {
|
|
381
|
-
// No write-back: edits reach disk only on explicit flush
|
|
382
|
-
//
|
|
405
|
+
// No write-back: edits reach disk only on explicit flush. The host owns the dirty broadcast;
|
|
406
|
+
// We just note the room for a project switch.
|
|
383
407
|
pendingPersist.add(path);
|
|
384
408
|
},
|
|
385
409
|
rejectPath: (path) => {
|
|
@@ -513,7 +537,8 @@ export function createCollabRegistry(opts: {
|
|
|
513
537
|
const saves: Promise<void>[] = [];
|
|
514
538
|
for (const [key, room] of hosted) {
|
|
515
539
|
if (room.root === running.root && pendingPersist.has(key)) {
|
|
516
|
-
|
|
540
|
+
// A save that fails is dropped with its room: the activation is closing either way.
|
|
541
|
+
saves.push(persist(key, running).catch(() => {}));
|
|
517
542
|
}
|
|
518
543
|
}
|
|
519
544
|
await Promise.all(saves);
|
|
@@ -538,7 +563,7 @@ export function createCollabRegistry(opts: {
|
|
|
538
563
|
host.resetDoc(key);
|
|
539
564
|
plain.delete(key);
|
|
540
565
|
if (dirty && source !== null) {
|
|
541
|
-
|
|
566
|
+
serialize(key, () => persistPlain(key, source)).catch(() => {});
|
|
542
567
|
}
|
|
543
568
|
}
|
|
544
569
|
},
|
|
@@ -572,9 +597,9 @@ export function createCollabRegistry(opts: {
|
|
|
572
597
|
if (req.headers.get("upgrade")?.toLowerCase() === "websocket") {
|
|
573
598
|
/*
|
|
574
599
|
* RFC 6455 §4.2.2: echo one of the tokens the client offered, or none if it offered none.
|
|
575
|
-
* An offer we cannot satisfy is refused outright rather than upgraded — two peers
|
|
576
|
-
*
|
|
577
|
-
*
|
|
600
|
+
* An offer we cannot satisfy is refused outright rather than upgraded — two peers that
|
|
601
|
+
* would mis-parse each other's frames must not share a room, and a 400 here is a better
|
|
602
|
+
* outcome than the divergent-history merge that would follow.
|
|
578
603
|
*/
|
|
579
604
|
const answer = selectSubprotocol(
|
|
580
605
|
offeredSubprotocols(req.headers.get("sec-websocket-protocol")),
|
|
@@ -608,14 +633,10 @@ export function createCollabRegistry(opts: {
|
|
|
608
633
|
for (const timer of destroyTimers.values()) {
|
|
609
634
|
clearTimeout(timer);
|
|
610
635
|
}
|
|
611
|
-
// Last-ditch safety on graceful shutdown: flush every path with unsaved edits.
|
|
612
|
-
const flushes: Promise<void>[] = [...persisting.values()];
|
|
613
|
-
for (const path of pendingPersist) {
|
|
614
|
-
flushes.push(persist(path));
|
|
615
|
-
}
|
|
616
|
-
pendingPersist.clear();
|
|
617
636
|
destroyTimers.clear();
|
|
618
|
-
|
|
637
|
+
// A save already in flight settles; none is started, so unsaved edits are dropped.
|
|
638
|
+
await Promise.allSettled(persisting.values());
|
|
639
|
+
pendingPersist.clear();
|
|
619
640
|
host.destroy();
|
|
620
641
|
},
|
|
621
642
|
|
package/src/data-api.ts
CHANGED
|
@@ -12,27 +12,24 @@
|
|
|
12
12
|
* extension registry, reusing the dev server's `local: "<provider>"` stand-in rule from jx-mounts
|
|
13
13
|
* (specs/extensions.md §12). Only the generic Kysely surface (row CRUD + introspection) runs here.
|
|
14
14
|
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
15
|
+
* Section owners (the auth extension's account tables among them) contribute push steps after the
|
|
16
|
+
* connector plan: {@link pushDataSchema} composes them through `pushSectionOwners`
|
|
17
|
+
* (`@jxsuite/compiler/section-push`, specs/extensions.md §11.1).
|
|
17
18
|
*/
|
|
18
19
|
|
|
19
20
|
import { existsSync, readFileSync } from "node:fs";
|
|
20
21
|
import { isAbsolute, relative, resolve } from "node:path";
|
|
21
22
|
import { Kysely, sql } from "kysely";
|
|
22
23
|
import { buildProjectExtensionRegistry } from "@jxsuite/compiler/format-host";
|
|
24
|
+
import { pushSectionOwners } from "@jxsuite/compiler/section-push";
|
|
23
25
|
import { isBoolean, isNonNullObject, isString } from "@jxsuite/schema/guards";
|
|
24
26
|
import { errorMessage } from "@jxsuite/schema/parse";
|
|
25
27
|
import { loadDevVars, parseDevVars, projectDevEnv } from "./dev-vars.ts";
|
|
26
28
|
import type { ProjectDevEnv } from "./dev-vars.ts";
|
|
27
|
-
import { resolveConnectorStandins } from "./jx-mounts.ts";
|
|
28
29
|
import { writeFile } from "node:fs/promises";
|
|
29
30
|
import type { Dialect } from "kysely";
|
|
30
31
|
import type { ExtensionRegistry } from "@jxsuite/schema/extension-registry";
|
|
31
|
-
import type {
|
|
32
|
-
ConnectorBlock,
|
|
33
|
-
FormatEntry,
|
|
34
|
-
SectionDeployOptions,
|
|
35
|
-
} from "@jxsuite/schema/format-registry";
|
|
32
|
+
import type { ConnectorBlock, FormatEntry } from "@jxsuite/schema/format-registry";
|
|
36
33
|
import type { JsonObject, ProjectConfig } from "@jxsuite/schema/types";
|
|
37
34
|
import type {
|
|
38
35
|
DataColumnMeta,
|
|
@@ -94,15 +91,6 @@ interface ArrivingRowUpdate extends Omit<DataRowUpdate, "set"> {
|
|
|
94
91
|
set?: JsonObject;
|
|
95
92
|
}
|
|
96
93
|
|
|
97
|
-
/**
|
|
98
|
-
* How this console reads a section owner's `deploySchema` answer (`SectionDeployResult`): its steps
|
|
99
|
-
* and warnings, each optional and defaulted where it is read.
|
|
100
|
-
*/
|
|
101
|
-
interface SectionDeployReading {
|
|
102
|
-
steps?: DataPushStep[];
|
|
103
|
-
warnings?: string[];
|
|
104
|
-
}
|
|
105
|
-
|
|
106
94
|
declare module "@jxsuite/schema/format-registry" {
|
|
107
95
|
/**
|
|
108
96
|
* A connector's `dialect` (specs/extensions.md §8) answers the Kysely dialect a connection opens
|
|
@@ -514,41 +502,18 @@ export async function pushDataSchema(
|
|
|
514
502
|
}
|
|
515
503
|
}
|
|
516
504
|
|
|
517
|
-
// Section-owner push steps
|
|
518
|
-
//
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
.
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
if (section === undefined || section === null) {
|
|
530
|
-
continue;
|
|
531
|
-
}
|
|
532
|
-
const options: SectionDeployOptions =
|
|
533
|
-
request.connection === undefined
|
|
534
|
-
? { connectors, dryRun, env }
|
|
535
|
-
: { connection: request.connection, connectors, dryRun, env };
|
|
536
|
-
try {
|
|
537
|
-
// A capability that throws is reported below.
|
|
538
|
-
const result: SectionDeployReading = await entry.call(
|
|
539
|
-
"deploySchema",
|
|
540
|
-
section,
|
|
541
|
-
project.config,
|
|
542
|
-
options,
|
|
543
|
-
);
|
|
544
|
-
for (const step of result.steps ?? []) {
|
|
545
|
-
step.kind ||= key;
|
|
546
|
-
plan.push(step);
|
|
547
|
-
}
|
|
548
|
-
warnings.push(...(result.warnings ?? []));
|
|
549
|
-
} catch (error) {
|
|
550
|
-
errors.push(`${key}: ${errorMessage(error)}`);
|
|
551
|
-
}
|
|
505
|
+
// Section-owner push steps (specs/extensions.md §11.1) compose after the connector plan, through
|
|
506
|
+
// The one loop `jx db push` also runs; the studio hands it the `local:` stand-ins its mounts see.
|
|
507
|
+
for (const section of await pushSectionOwners(registry, project.config, {
|
|
508
|
+
dryRun,
|
|
509
|
+
env,
|
|
510
|
+
connection: request.connection,
|
|
511
|
+
standins: true,
|
|
512
|
+
})) {
|
|
513
|
+
plan.push(...section.steps);
|
|
514
|
+
warnings.push(...section.warnings);
|
|
515
|
+
if (section.error !== undefined) {
|
|
516
|
+
errors.push(`${section.section}: ${section.error}`);
|
|
552
517
|
}
|
|
553
518
|
}
|
|
554
519
|
|
package/src/dev.ts
CHANGED
|
@@ -20,7 +20,7 @@ import { errorMessage } from "@jxsuite/schema/parse";
|
|
|
20
20
|
import type { JsonObject } from "@jxsuite/schema/types";
|
|
21
21
|
import { projectDevEnv } from "./dev-vars.ts";
|
|
22
22
|
import { problem } from "./problem.ts";
|
|
23
|
-
import { callServerExport, importServerScript } from "./resolve.ts";
|
|
23
|
+
import { callServerExport, importServerScript, withProjectMediaType } from "./resolve.ts";
|
|
24
24
|
import type { ModuleNamespace } from "./resolve.ts";
|
|
25
25
|
import { serverScriptAddress } from "./server-script.ts";
|
|
26
26
|
import { createDevServer } from "./server.ts";
|
|
@@ -96,7 +96,11 @@ export function createDistMiddleware(
|
|
|
96
96
|
headers: { "Cache-Control": "no-cache", "Content-Type": "text/html; charset=utf-8" },
|
|
97
97
|
});
|
|
98
98
|
}
|
|
99
|
-
return
|
|
99
|
+
return withProjectMediaType(
|
|
100
|
+
new Response(Bun.file(filePath), { headers: { "Cache-Control": "no-cache" } }),
|
|
101
|
+
root,
|
|
102
|
+
filePath,
|
|
103
|
+
);
|
|
100
104
|
};
|
|
101
105
|
}
|
|
102
106
|
|
package/src/extension-catalog.ts
CHANGED
|
@@ -14,11 +14,10 @@
|
|
|
14
14
|
* included (specs/extensions.md §3), so enabling one the project lacks is always
|
|
15
15
|
* install-then-enable.
|
|
16
16
|
*
|
|
17
|
-
* **`installed` is answered here rather than by the client**, because `listPackages`
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
* the other.
|
|
17
|
+
* **`installed` is answered here rather than by the client**, because `listPackages` reports what
|
|
18
|
+
* `package.json` declares, not what resolves under `node_modules` (imports.md §4.2). A surface
|
|
19
|
+
* deciding "do I need to install this first?" from a declaration would call a declared but
|
|
20
|
+
* uninstalled package installed.
|
|
22
21
|
*
|
|
23
22
|
* @docs extending/extensions/first-party
|
|
24
23
|
*/
|
package/src/jx-mounts.ts
CHANGED
|
@@ -13,18 +13,35 @@
|
|
|
13
13
|
* provider (e.g. D1 → sqlite at `<project>/.jx/data/<connection>.sqlite`);
|
|
14
14
|
* - Mount options set `autoSync: true`, so table schemas sync additively on first touch.
|
|
15
15
|
*
|
|
16
|
+
* The data mount's `references` option reads the entries its section points at from the resolve
|
|
17
|
+
* proxy's project context (specs/relationships.md §2).
|
|
18
|
+
*
|
|
19
|
+
* Mounts are activated by the site build's section gate (specs/extensions.md §8.4), so `jx dev`
|
|
20
|
+
* serves the set the worker would.
|
|
21
|
+
*
|
|
16
22
|
* The runtime is cached per project root and invalidated when project.json changes on disk.
|
|
17
23
|
*/
|
|
18
24
|
|
|
19
25
|
import { readFileSync } from "node:fs";
|
|
20
26
|
import { buildProjectExtensionRegistry } from "@jxsuite/compiler/format-host";
|
|
21
|
-
import {
|
|
27
|
+
import { sectionOwnerActive } from "@jxsuite/compiler/project-sections";
|
|
28
|
+
import { resolveConnectorClasses } from "@jxsuite/compiler/section-push";
|
|
22
29
|
import { projectDevEnv } from "./dev-vars.ts";
|
|
30
|
+
import { projectContext } from "./resolve.ts";
|
|
23
31
|
import type { ProjectDevEnv } from "./dev-vars.ts";
|
|
32
|
+
import type { ProjectSections } from "@jxsuite/compiler/project-sections";
|
|
24
33
|
import type { ExtensionRegistry } from "@jxsuite/schema/extension-registry";
|
|
25
|
-
import type {
|
|
26
|
-
|
|
34
|
+
import type {
|
|
35
|
+
ImplementationExport,
|
|
36
|
+
MountHandler,
|
|
37
|
+
MountOptions,
|
|
38
|
+
ProjectSectionData,
|
|
39
|
+
} from "@jxsuite/schema/format-registry";
|
|
40
|
+
import type { ContentLoaderEntry, JxDocumentValue, ProjectConfig } from "@jxsuite/schema/types";
|
|
27
41
|
import { parseProjectSource } from "@jxsuite/schema/project-file";
|
|
42
|
+
import { isFunction, isNonNullObject } from "@jxsuite/schema/guards";
|
|
43
|
+
import { buildReferenceView, relationshipTargets } from "@jxsuite/schema/reference-view";
|
|
44
|
+
import type { RefTarget, ReferenceView } from "@jxsuite/schema/reference-view";
|
|
28
45
|
import { isSameStamp, projectFileStamp } from "@jxsuite/schema/project-file/node";
|
|
29
46
|
|
|
30
47
|
interface MountRuntime {
|
|
@@ -114,7 +131,7 @@ async function buildRuntime(
|
|
|
114
131
|
and any throw lands in getRuntime's catch, which disables the mounts with a warning. */
|
|
115
132
|
const config = parseProjectSource(readFileSync(projectFile, "utf8"), projectFile);
|
|
116
133
|
const registry = await buildProjectExtensionRegistry(projectRoot, config);
|
|
117
|
-
const mounts = registry.serverMounts();
|
|
134
|
+
const mounts = registry.serverMounts().filter((entry) => sectionOwnerActive(entry, config));
|
|
118
135
|
if (mounts.length === 0) {
|
|
119
136
|
return null;
|
|
120
137
|
}
|
|
@@ -136,42 +153,74 @@ async function buildRuntime(
|
|
|
136
153
|
const handlers: MountRuntime["handlers"] = [];
|
|
137
154
|
for (const entry of mounts) {
|
|
138
155
|
const { basePath } = entry.server!;
|
|
139
|
-
const
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
156
|
+
const targets = entry.project ? relationshipTargets(config[entry.project.key]) : [];
|
|
157
|
+
const options: MountOptions = { autoSync: true, basePath, connectors, sections };
|
|
158
|
+
if (targets.length > 0) {
|
|
159
|
+
options.references = referencesFor(projectRoot, targets, config);
|
|
160
|
+
}
|
|
161
|
+
const handler = await entry.call("mount", options, ctx);
|
|
144
162
|
handlers.push({ basePath, handler });
|
|
145
163
|
}
|
|
146
164
|
return { env, handlers };
|
|
147
165
|
}
|
|
148
166
|
|
|
167
|
+
/**
|
|
168
|
+
* The mount's `references` option: a function building the view of every entry its section points
|
|
169
|
+
* at from the project context the resolve proxy loads. Memoized per context object, which the proxy
|
|
170
|
+
* replaces exactly when it reloads, so a view is never older than the context it came from.
|
|
171
|
+
*/
|
|
172
|
+
function referencesFor(
|
|
173
|
+
projectRoot: string,
|
|
174
|
+
targets: RefTarget[],
|
|
175
|
+
config: ProjectConfig,
|
|
176
|
+
): () => Promise<ReferenceView> {
|
|
177
|
+
const views = new WeakMap<object, Promise<ReferenceView>>();
|
|
178
|
+
return async () => {
|
|
179
|
+
// No context (the project file vanished mid-request) reads as an empty view.
|
|
180
|
+
const context = (await projectContext(projectRoot)) ?? {};
|
|
181
|
+
let view = views.get(context);
|
|
182
|
+
if (!view) {
|
|
183
|
+
view = loadTargets(context, targets).then(() =>
|
|
184
|
+
buildReferenceView(targets, { ...context }, config),
|
|
185
|
+
);
|
|
186
|
+
views.set(context, view);
|
|
187
|
+
}
|
|
188
|
+
return view;
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** A section loaded on demand: `load(name)` loads one type, with the types it relates to. */
|
|
193
|
+
interface LazySection {
|
|
194
|
+
load: (name: string) => Promise<ContentLoaderEntry[] | undefined>;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function isLazySection(
|
|
198
|
+
value: ProjectSectionData | undefined,
|
|
199
|
+
): value is ProjectSectionData & LazySection {
|
|
200
|
+
return isNonNullObject(value) && "load" in value && isFunction(value.load);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Load each target type of a lazily loaded section, so the view finds its entries. */
|
|
204
|
+
async function loadTargets(context: ProjectSections, targets: RefTarget[]): Promise<void> {
|
|
205
|
+
for (const { name, section } of targets) {
|
|
206
|
+
const value = context[section];
|
|
207
|
+
if (isLazySection(value)) {
|
|
208
|
+
await value.load(name);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
149
213
|
/**
|
|
150
214
|
* Resolve connector implementation classes keyed by provider id, applying the dev-server `local`
|
|
151
|
-
* stand-in rule
|
|
152
|
-
*
|
|
153
|
-
* section-
|
|
154
|
-
*
|
|
155
|
-
* Each provider is its implementation module's export (specs/extensions.md §6.1): this host only
|
|
156
|
-
* routes it, and the mounts and deploy steps that receive it are the ones that call it. A module
|
|
157
|
-
* exporting no such export yields a nullish entry, which the receiving mount reports as an
|
|
158
|
-
* unavailable provider.
|
|
215
|
+
* stand-in rule (specs/extensions.md §12). The mounts and the studio push (section-owner
|
|
216
|
+
* deploySchema, e.g. auth) receive the same stand-ins; the one resolver lives in the compiler's
|
|
217
|
+
* section-push module so every host picks the implementation export identically.
|
|
159
218
|
*
|
|
160
219
|
* @param {ExtensionRegistry} registry
|
|
161
220
|
* @returns {Promise<Record<string, ImplementationExport | null | undefined>>}
|
|
162
221
|
*/
|
|
163
|
-
export
|
|
222
|
+
export function resolveConnectorStandins(
|
|
164
223
|
registry: ExtensionRegistry,
|
|
165
224
|
): Promise<Record<string, ImplementationExport | null | undefined>> {
|
|
166
|
-
|
|
167
|
-
const out: Record<string, ImplementationExport | null | undefined> = {};
|
|
168
|
-
for (const entry of entries) {
|
|
169
|
-
const provider = String(entry.connector!.provider);
|
|
170
|
-
const { local } = entry.connector!;
|
|
171
|
-
const target = isString(local)
|
|
172
|
-
? (entries.find((e) => e.connector!.provider === local) ?? entry)
|
|
173
|
-
: entry;
|
|
174
|
-
out[provider] = await target.implementationExport();
|
|
175
|
-
}
|
|
176
|
-
return out;
|
|
225
|
+
return resolveConnectorClasses(registry, { standins: true });
|
|
177
226
|
}
|
package/src/live-preview.ts
CHANGED
|
@@ -38,7 +38,6 @@
|
|
|
38
38
|
|
|
39
39
|
import { existsSync } from "node:fs";
|
|
40
40
|
import { readFile } from "node:fs/promises";
|
|
41
|
-
import { createRequire } from "node:module";
|
|
42
41
|
import { extname, join, resolve } from "node:path";
|
|
43
42
|
import { serveSite, siteContext, siteHeaders } from "@jxsuite/site/serve";
|
|
44
43
|
import { pageShell, problemShell } from "@jxsuite/site/shell";
|
|
@@ -50,18 +49,18 @@ import { ComposeError, readProjectConfig } from "@jxsuite/site/compose";
|
|
|
50
49
|
import type { DocumentParser, SiteIO } from "@jxsuite/site/compose";
|
|
51
50
|
import { buildProjectExtensionRegistry } from "@jxsuite/compiler/format-host";
|
|
52
51
|
import { isNonNullObject } from "@jxsuite/schema/guards";
|
|
52
|
+
import { projectMediaType, handleResolve, handleServerFunction } from "./resolve.ts";
|
|
53
53
|
import { createSseHub } from "./sse.ts";
|
|
54
54
|
import type { SseHub } from "./sse.ts";
|
|
55
55
|
import { LIVE_NAMESPACE, PREVIEW_CLIENT_JS } from "./preview-client.ts";
|
|
56
56
|
import { HARNESS_KEY_PARAM, composeHarness, harnessTarget } from "./preview-harness.ts";
|
|
57
57
|
import { HARNESS_ROUTE } from "@jxsuite/protocol/preview-harness";
|
|
58
|
-
import { handleResolve, handleServerFunction } from "./resolve.ts";
|
|
59
58
|
import { handleJxMounts } from "./jx-mounts.ts";
|
|
60
59
|
import { hostIsLoopbackOrAbsent, loopbackGate, originHostGate, secretsMatch } from "./net-guard.ts";
|
|
61
60
|
import { problem } from "./problem.ts";
|
|
62
61
|
import { scanFiles } from "./fs-glob.ts";
|
|
63
62
|
import { serve } from "#serve";
|
|
64
|
-
import {
|
|
63
|
+
import { loadPreviewBundle } from "./preview-bundles.ts";
|
|
65
64
|
|
|
66
65
|
/** A running live preview for one project. */
|
|
67
66
|
export interface LivePreview {
|
|
@@ -170,35 +169,11 @@ const starting = new Map<string, Promise<Running>>();
|
|
|
170
169
|
let runtimeBundle: string | null = null;
|
|
171
170
|
|
|
172
171
|
/**
|
|
173
|
-
* The `@jxsuite/runtime` browser bundle.
|
|
174
|
-
*
|
|
175
|
-
* Preferred from the package's own `dist`, which is what it publishes and what a packaged app
|
|
176
|
-
* ships. A checkout that has not run `bun run build:runtime` has none, and building it here on
|
|
177
|
-
* first request is better than an origin that renders nothing until someone runs a script.
|
|
178
|
-
*
|
|
179
|
-
* That fallback is the one branch in this file no test reaches, and deliberately so: reaching it
|
|
180
|
-
* means `@jxsuite/runtime/dist/runtime.js` neither resolving nor existing, which in this repository
|
|
181
|
-
* it always does, and `mock.module` cannot override a `node:fs` builtin to pretend otherwise. It is
|
|
182
|
-
* exercised for real by any fresh clone that previews before it builds.
|
|
172
|
+
* The `@jxsuite/runtime` browser bundle (`preview-bundles.ts` says where it comes from). Every page
|
|
173
|
+
* imports it, so a failure here is a blank page.
|
|
183
174
|
*/
|
|
184
175
|
async function loadRuntimeBundle(): Promise<string> {
|
|
185
|
-
|
|
186
|
-
return runtimeBundle;
|
|
187
|
-
}
|
|
188
|
-
const require_ = createRequire(import.meta.url);
|
|
189
|
-
try {
|
|
190
|
-
const built = require_.resolve("@jxsuite/runtime/dist/runtime.js");
|
|
191
|
-
if (existsSync(built)) {
|
|
192
|
-
runtimeBundle = await readFile(built, "utf8");
|
|
193
|
-
return runtimeBundle;
|
|
194
|
-
}
|
|
195
|
-
} catch {
|
|
196
|
-
// No published dist on this install; fall through and build one.
|
|
197
|
-
}
|
|
198
|
-
runtimeBundle = await bundleToString(require_.resolve("@jxsuite/runtime"), {
|
|
199
|
-
minify: false,
|
|
200
|
-
target: "browser",
|
|
201
|
-
});
|
|
176
|
+
runtimeBundle ??= await loadPreviewBundle("runtime");
|
|
202
177
|
return runtimeBundle;
|
|
203
178
|
}
|
|
204
179
|
|
|
@@ -211,10 +186,7 @@ let eraserBundle: string | null = null;
|
|
|
211
186
|
* that fails is not kept, so the next page that needs it tries again.
|
|
212
187
|
*/
|
|
213
188
|
async function loadEraserBundle(): Promise<string> {
|
|
214
|
-
eraserBundle ??= await
|
|
215
|
-
createRequire(import.meta.url).resolve("@jxsuite/erase/browser"),
|
|
216
|
-
{ minify: true, target: "browser" },
|
|
217
|
-
);
|
|
189
|
+
eraserBundle ??= await loadPreviewBundle("eraser");
|
|
218
190
|
return eraserBundle;
|
|
219
191
|
}
|
|
220
192
|
|
|
@@ -584,7 +556,10 @@ async function handle(entry: Running, projectRoot: string, req: Request): Promis
|
|
|
584
556
|
|
|
585
557
|
const { context, paths } = await ensureCache(entry, projectRoot);
|
|
586
558
|
const { assets, io } = makeIO(projectRoot, paths);
|
|
587
|
-
return serveSite(pathname, io, assets, context, {
|
|
559
|
+
return serveSite(pathname, io, assets, context, {
|
|
560
|
+
mediaType: (path) => projectMediaType(projectRoot, path),
|
|
561
|
+
shell: shellOptions(entry),
|
|
562
|
+
});
|
|
588
563
|
}
|
|
589
564
|
|
|
590
565
|
/**
|
package/src/packages.ts
CHANGED
|
@@ -72,22 +72,34 @@ async function readPackageJson(root: string): Promise<PackageJson | null> {
|
|
|
72
72
|
}
|
|
73
73
|
}
|
|
74
74
|
|
|
75
|
-
/**
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
75
|
+
/**
|
|
76
|
+
* The entries a manifest declares: `dependencies` first, then `devDependencies` tagged with `dev:
|
|
77
|
+
* true`, each with its range as written. Pure; the one mapping every backend's package list shares
|
|
78
|
+
* (imports.md §4.2).
|
|
79
|
+
*/
|
|
80
|
+
export function declaredPackages(manifest: {
|
|
81
|
+
dependencies?: Record<string, string>;
|
|
82
|
+
devDependencies?: Record<string, string>;
|
|
83
|
+
}): PackageInfo[] {
|
|
81
84
|
const out: PackageInfo[] = [];
|
|
82
|
-
for (const [name, version] of Object.entries(
|
|
85
|
+
for (const [name, version] of Object.entries(manifest.dependencies ?? {})) {
|
|
83
86
|
out.push({ name, version });
|
|
84
87
|
}
|
|
85
|
-
for (const [name, version] of Object.entries(
|
|
88
|
+
for (const [name, version] of Object.entries(manifest.devDependencies ?? {})) {
|
|
86
89
|
out.push({ dev: true, name, version });
|
|
87
90
|
}
|
|
88
91
|
return out;
|
|
89
92
|
}
|
|
90
93
|
|
|
94
|
+
/**
|
|
95
|
+
* List the dependencies and devDependencies the project's `package.json` declares, installed or not
|
|
96
|
+
* (imports.md §4.2); `[]` for a missing or unparseable manifest.
|
|
97
|
+
*/
|
|
98
|
+
export async function listPackages(root: string): Promise<PackageInfo[]> {
|
|
99
|
+
const pkg = await readPackageJson(root);
|
|
100
|
+
return pkg ? declaredPackages(pkg) : [];
|
|
101
|
+
}
|
|
102
|
+
|
|
91
103
|
/** Whether the project has a package.json but no installed node_modules. */
|
|
92
104
|
export function dependenciesNeedInstall(root: string): boolean {
|
|
93
105
|
if (!existsSync(resolve(root, "package.json"))) {
|