@jxsuite/server 9.2.1 → 9.3.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/package.json +24 -18
- package/src/collab.ts +390 -18
- package/src/jxn-response.ts +41 -0
- package/src/net-guard.ts +4 -3
- package/src/project-events.ts +622 -0
- package/src/project-server.ts +102 -3
- package/src/project-state/collections.ts +108 -0
- package/src/project-state/git-monitor.ts +302 -0
- package/src/project-state/graph.ts +651 -0
- package/src/project-state/host-deps.ts +224 -0
- package/src/project-state/host.ts +2113 -0
- package/src/project-state/overlays.ts +231 -0
- package/src/project-state/rename.ts +473 -0
- package/src/project-state/settle.ts +38 -0
- package/src/refactor/apply.ts +177 -67
- package/src/refactor/find-refs.ts +0 -0
- package/src/refactor/index.ts +2 -1
- package/src/refactor/paths.ts +3 -325
- package/src/refactor/refs.ts +5 -388
- package/src/refactor/scan.ts +17 -4
- package/src/refactor/watcher.ts +47 -2
- package/src/serve.node.ts +1 -0
- package/src/serve.ts +7 -5
- package/src/server.ts +40 -1
- package/src/sse.ts +1 -1
- package/src/studio-api.ts +76 -9
package/src/refactor/refs.ts
CHANGED
|
@@ -1,393 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Refs.ts —
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
* visitor that always returns `null` is a pure reader. Three passes are built on it:
|
|
7
|
-
*
|
|
8
|
-
* - `rewriteDocRefs` — recompute every file-path reference across a rename (Pillar B).
|
|
9
|
-
* - `rewriteTagName` — rename a custom-element tag wherever it is used (Pillar C).
|
|
10
|
-
* - `countTagUses` — the same tag walk, counting instead of writing (the usage query).
|
|
11
|
-
*
|
|
12
|
-
* The walk dispatches by JSON key rather than searching strings, and mutates the passed document in
|
|
13
|
-
* place — callers parse a fresh object per file, so this is safe. Precision comes from
|
|
14
|
-
* `rewriteRef`'s resolve-and-compare gate in paths.ts: a reference is only rewritten (or counted as
|
|
15
|
-
* a usage) when it actually resolves to the file in question.
|
|
16
|
-
*
|
|
17
|
-
* **A reference is not always a value.** Three of the four visit helpers offer a value under a
|
|
18
|
-
* container-plus-position; {@link visitKeys} offers a map's KEYS, because `project.json`'s `copy`
|
|
19
|
-
* map names the files it copies there. Everything downstream is unchanged — a key is renamed by the
|
|
20
|
-
* same visitor returning the same kind of string — but the fourth shape had to exist before the
|
|
21
|
-
* walk could see the reference at all (issue 242).
|
|
22
|
-
*
|
|
23
|
-
* The visitor seam is what stops the read side from being a second, drifting copy of the key list.
|
|
24
|
-
* A new reference-bearing key added below is a key the usage count sees on the same commit.
|
|
2
|
+
* Refs.ts — the reference walk (`project-state.md` §12), published here as
|
|
3
|
+
* `@jxsuite/server/refactor/refs` for the hosts that already import it from the server. Its one
|
|
4
|
+
* definition lives in `@jxsuite/protocol/refs`, beside the contract, so a client that must not
|
|
5
|
+
* depend on a backend (Studio, `studio.md` §3) walks with the same code.
|
|
25
6
|
*
|
|
26
7
|
* @docs studio/projects/pages-layouts-components
|
|
27
8
|
*/
|
|
28
9
|
|
|
29
|
-
|
|
30
|
-
import type { JsonObject, JsonValue } from "@jxsuite/schema/types";
|
|
31
|
-
import { classifyRef, looksLikeFileRef, rewriteRef } from "./paths.ts";
|
|
32
|
-
import type { RemapCtx } from "./paths.ts";
|
|
33
|
-
|
|
34
|
-
/** A single reference rewrite, for the rename report. */
|
|
35
|
-
export interface RefChange {
|
|
36
|
-
refType: string;
|
|
37
|
-
from: string;
|
|
38
|
-
to: string;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
export interface RewriteResult {
|
|
42
|
-
doc: JsonValue;
|
|
43
|
-
changes: RefChange[];
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
/** The outcome of {@link rewriteTagName}: the same document, and how many nodes were renamed. */
|
|
47
|
-
export interface TagRewriteResult {
|
|
48
|
-
doc: JsonValue;
|
|
49
|
-
count: number;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
/**
|
|
53
|
-
* One visit of a reference-bearing string.
|
|
54
|
-
*
|
|
55
|
-
* @param value — the raw authored reference, exactly as written.
|
|
56
|
-
* @param refType — which key carried it (`$ref`, `$layout`, `attr`, `imports`, `$elements`, `url`,
|
|
57
|
-
* `source`, `copy` for a map KEY naming a copied file, or `path` for a value matched by shape
|
|
58
|
-
* rather than by key name).
|
|
59
|
-
* @param rootRelativeBare — whether a bare value resolves against the project root (`$layout`,
|
|
60
|
-
* `copy`).
|
|
61
|
-
* @returns A replacement string to write back, or `null` to leave the document untouched.
|
|
62
|
-
*/
|
|
63
|
-
export type RefVisitor = (
|
|
64
|
-
value: string,
|
|
65
|
-
refType: string,
|
|
66
|
-
rootRelativeBare: boolean,
|
|
67
|
-
) => string | null;
|
|
68
|
-
|
|
69
|
-
/** Matches `url(...)` targets inside a CSS string value, capturing the optional quote. */
|
|
70
|
-
const URL_RE = /url\(\s*(['"]?)([^'")]+)\1\s*\)/g;
|
|
71
|
-
|
|
72
|
-
/**
|
|
73
|
-
* Keys whose string values are PROSE, and are therefore never offered to the shape fallback.
|
|
74
|
-
*
|
|
75
|
-
* A page that writes "see layouts/base.json" in its body text names a file without referencing it,
|
|
76
|
-
* and rewriting that sentence during a rename would be vandalism. Almost every such string is
|
|
77
|
-
* already excluded by the whitespace test in `looksLikeFileRef`; these two keys are where a
|
|
78
|
-
* single-token one is plausible, and a whole-repo survey of file-shaped string values found
|
|
79
|
-
* non-reference hits under no other key.
|
|
80
|
-
*/
|
|
81
|
-
const PROSE_KEYS = new Set(["textContent", "innerHTML"]);
|
|
82
|
-
|
|
83
|
-
/** Offer a scalar string reference under `key` to the visitor, writing back any replacement. */
|
|
84
|
-
function visitScalar(
|
|
85
|
-
container: JsonObject,
|
|
86
|
-
key: string,
|
|
87
|
-
refType: string,
|
|
88
|
-
visit: RefVisitor,
|
|
89
|
-
rootRelativeBare: boolean,
|
|
90
|
-
): void {
|
|
91
|
-
const value = container[key];
|
|
92
|
-
if (!isString(value)) {
|
|
93
|
-
return;
|
|
94
|
-
}
|
|
95
|
-
const out = visit(value, refType, rootRelativeBare);
|
|
96
|
-
if (out !== null) {
|
|
97
|
-
container[key] = out;
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
/**
|
|
102
|
-
* Offer every KEY of a map to the visitor, renaming in place and preserving insertion order.
|
|
103
|
-
*
|
|
104
|
-
* The fourth visit helper, and the only one whose reference is not a value. `project.json`'s `copy`
|
|
105
|
-
* map names its sources in its keys (`{"assets/brochure.pdf": "brochure.pdf"}`), so a walk that
|
|
106
|
-
* only ever offered values could not see them at all — renaming a copied file reported zero
|
|
107
|
-
* references and rewrote nothing (issue 242).
|
|
108
|
-
*
|
|
109
|
-
* Order is preserved by rebuilding rather than by deleting one key and re-adding it: a plain
|
|
110
|
-
* `delete` + set moves the renamed entry to the end, which is a diff on a file nobody edited. When
|
|
111
|
-
* a rename collides with an existing key the later entry wins, exactly as an authored duplicate
|
|
112
|
-
* would.
|
|
113
|
-
*/
|
|
114
|
-
function visitKeys(
|
|
115
|
-
container: JsonObject,
|
|
116
|
-
refType: string,
|
|
117
|
-
visit: RefVisitor,
|
|
118
|
-
rootRelativeBare: boolean,
|
|
119
|
-
): void {
|
|
120
|
-
const entries = Object.entries(container);
|
|
121
|
-
const renamed = entries.map(([key, value]): [string, JsonValue] => {
|
|
122
|
-
const out = visit(key, refType, rootRelativeBare);
|
|
123
|
-
return [out === null ? key : out, value];
|
|
124
|
-
});
|
|
125
|
-
if (renamed.every(([key], i) => key === entries[i]![0])) {
|
|
126
|
-
return;
|
|
127
|
-
}
|
|
128
|
-
for (const [key] of entries) {
|
|
129
|
-
delete container[key];
|
|
130
|
-
}
|
|
131
|
-
for (const [key, value] of renamed) {
|
|
132
|
-
container[key] = value;
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
/** Offer a string array member (e.g. an `$elements` entry) to the visitor. */
|
|
137
|
-
function visitIndexed(arr: JsonValue[], index: number, refType: string, visit: RefVisitor): void {
|
|
138
|
-
const value = arr[index];
|
|
139
|
-
if (!isString(value)) {
|
|
140
|
-
return;
|
|
141
|
-
}
|
|
142
|
-
const out = visit(value, refType, false);
|
|
143
|
-
if (out !== null) {
|
|
144
|
-
arr[index] = out;
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
/** Offer every `url(...)` target inside a CSS string to the visitor. */
|
|
149
|
-
function visitUrls(value: string, visit: RefVisitor): string {
|
|
150
|
-
return value.replaceAll(URL_RE, (match, quote: string, inner: string) => {
|
|
151
|
-
const out = visit(inner.trim(), "url", false);
|
|
152
|
-
return out === null ? match : `url(${quote}${out}${quote})`;
|
|
153
|
-
});
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
/** Walk a `style` value tree, visiting `url(...)` in every string it contains. */
|
|
157
|
-
function walkStyle(node: JsonValue | undefined, visit: RefVisitor): void {
|
|
158
|
-
if (Array.isArray(node)) {
|
|
159
|
-
for (let i = 0; i < node.length; i += 1) {
|
|
160
|
-
const item = node[i];
|
|
161
|
-
if (isString(item)) {
|
|
162
|
-
const out = visitUrls(item, visit);
|
|
163
|
-
if (out !== item) {
|
|
164
|
-
node[i] = out;
|
|
165
|
-
}
|
|
166
|
-
} else {
|
|
167
|
-
walkStyle(item, visit);
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
return;
|
|
171
|
-
}
|
|
172
|
-
if (!isJsonObject(node)) {
|
|
173
|
-
return;
|
|
174
|
-
}
|
|
175
|
-
for (const key of Object.keys(node)) {
|
|
176
|
-
const value = node[key];
|
|
177
|
-
if (isString(value)) {
|
|
178
|
-
const out = visitUrls(value, visit);
|
|
179
|
-
if (out !== value) {
|
|
180
|
-
node[key] = out;
|
|
181
|
-
}
|
|
182
|
-
} else {
|
|
183
|
-
walkStyle(value, visit);
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
/**
|
|
189
|
-
* Recursive document walk dispatching each reference-bearing key to `visit`.
|
|
190
|
-
*
|
|
191
|
-
* This is the single definition of "what counts as a reference" in a Jx document. Mutates `doc`
|
|
192
|
-
* only where the visitor asks it to.
|
|
193
|
-
*/
|
|
194
|
-
export function walkDocRefs(node: JsonValue | undefined, visit: RefVisitor): void {
|
|
195
|
-
if (Array.isArray(node)) {
|
|
196
|
-
for (const item of node) {
|
|
197
|
-
walkDocRefs(item, visit);
|
|
198
|
-
}
|
|
199
|
-
return;
|
|
200
|
-
}
|
|
201
|
-
if (!isJsonObject(node)) {
|
|
202
|
-
return;
|
|
203
|
-
}
|
|
204
|
-
for (const key of Object.keys(node)) {
|
|
205
|
-
const value = node[key];
|
|
206
|
-
switch (key) {
|
|
207
|
-
case "$ref": {
|
|
208
|
-
// File-path $ref only; state-scope refs (#/…, $map/…) are filtered by classifyRef.
|
|
209
|
-
visitScalar(node, key, "$ref", visit, false);
|
|
210
|
-
break;
|
|
211
|
-
}
|
|
212
|
-
case "$layout": {
|
|
213
|
-
visitScalar(node, key, "$layout", visit, true);
|
|
214
|
-
break;
|
|
215
|
-
}
|
|
216
|
-
case "$src":
|
|
217
|
-
case "$implementation": {
|
|
218
|
-
visitScalar(node, key, key, visit, false);
|
|
219
|
-
break;
|
|
220
|
-
}
|
|
221
|
-
case "src":
|
|
222
|
-
case "href": {
|
|
223
|
-
visitScalar(node, key, "attr", visit, false);
|
|
224
|
-
break;
|
|
225
|
-
}
|
|
226
|
-
case "imports": {
|
|
227
|
-
if (isJsonObject(value)) {
|
|
228
|
-
for (const name of Object.keys(value)) {
|
|
229
|
-
visitScalar(value, name, "imports", visit, false);
|
|
230
|
-
}
|
|
231
|
-
}
|
|
232
|
-
break;
|
|
233
|
-
}
|
|
234
|
-
case "$elements": {
|
|
235
|
-
if (Array.isArray(value)) {
|
|
236
|
-
for (let i = 0; i < value.length; i += 1) {
|
|
237
|
-
if (isString(value[i])) {
|
|
238
|
-
visitIndexed(value, i, "$elements", visit);
|
|
239
|
-
} else {
|
|
240
|
-
walkDocRefs(value[i], visit);
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
} else {
|
|
244
|
-
walkDocRefs(value, visit);
|
|
245
|
-
}
|
|
246
|
-
break;
|
|
247
|
-
}
|
|
248
|
-
case "style": {
|
|
249
|
-
walkStyle(value, visit);
|
|
250
|
-
break;
|
|
251
|
-
}
|
|
252
|
-
case "copy": {
|
|
253
|
-
/*
|
|
254
|
-
* `project.json`'s declarative copy map (site-architecture.md §5). Its KEYS are project
|
|
255
|
-
* files and its VALUES are destinations inside `outDir` — a directory the project does not
|
|
256
|
-
* contain and a rename can never move. So the key is visited and the value deliberately is
|
|
257
|
-
* not: offering the value to the shape fallback, which is what happened before, meant
|
|
258
|
-
* renaming a file at the project root could rewrite an unrelated copy DESTINATION that
|
|
259
|
-
* merely shared its name.
|
|
260
|
-
*/
|
|
261
|
-
if (isJsonObject(value)) {
|
|
262
|
-
visitKeys(value, "copy", visit, true);
|
|
263
|
-
}
|
|
264
|
-
break;
|
|
265
|
-
}
|
|
266
|
-
case "source": {
|
|
267
|
-
/*
|
|
268
|
-
* A content collection's source (site-architecture.md §6), which may name a single file
|
|
269
|
-
* (`./content/listings.csv`) or a DIRECTORY (`./content/posts/`).
|
|
270
|
-
*
|
|
271
|
-
* Named rather than left to the shape fallback because a directory has no extension, and
|
|
272
|
-
* the extension test is exactly what keeps that fallback from admitting every route and
|
|
273
|
-
* bare word. Here the key is known and the value's shape is not diagnostic, so the value is
|
|
274
|
-
* offered unconditionally and precision stays where it always was — the caller's
|
|
275
|
-
* resolve-and-compare gate, which only matches a value resolving to the file or directory
|
|
276
|
-
* in question. A remote `https://…` source is filtered by `classifyRef` before that.
|
|
277
|
-
*/
|
|
278
|
-
visitScalar(node, key, "source", visit, false);
|
|
279
|
-
break;
|
|
280
|
-
}
|
|
281
|
-
/*
|
|
282
|
-
* Everything else, by SHAPE.
|
|
283
|
-
*
|
|
284
|
-
* The cases above are the keys that carry a reference BY NAME, and for years that list was
|
|
285
|
-
* taken to be the whole of it. It is not: the commonest media reference in a real project is
|
|
286
|
-
* a schema-typed component prop (`$props.bg`, `attributes["props.image"]`), and beside it sit
|
|
287
|
-
* a content entry's frontmatter (`cover:`), a prop schema's `default`, `project.json`'s
|
|
288
|
-
* `defaults.layout`, `poster`, `srcset` and `$head` meta `content`. Measured across the
|
|
289
|
-
* committed starters, 73 of 101 files under `public/` were used and reported zero.
|
|
290
|
-
*
|
|
291
|
-
* Naming those keys one at a time would be the same mistake with a longer list — the next
|
|
292
|
-
* extension to define a media-typed prop would reopen it. So an unrecognised string is
|
|
293
|
-
* offered whenever it is SHAPED like a file, and precision stays where it already was: the
|
|
294
|
-
* caller's resolve-and-compare gate, which only counts a value that resolves to the exact
|
|
295
|
-
* file in question.
|
|
296
|
-
*/
|
|
297
|
-
default: {
|
|
298
|
-
if (isString(value)) {
|
|
299
|
-
if (!PROSE_KEYS.has(key) && looksLikeFileRef(value)) {
|
|
300
|
-
visitScalar(node, key, "path", visit, false);
|
|
301
|
-
}
|
|
302
|
-
} else if (Array.isArray(value)) {
|
|
303
|
-
for (let i = 0; i < value.length; i += 1) {
|
|
304
|
-
const item = value[i];
|
|
305
|
-
if (isString(item)) {
|
|
306
|
-
if (!PROSE_KEYS.has(key) && looksLikeFileRef(item)) {
|
|
307
|
-
visitIndexed(value, i, "path", visit);
|
|
308
|
-
}
|
|
309
|
-
} else {
|
|
310
|
-
walkDocRefs(item, visit);
|
|
311
|
-
}
|
|
312
|
-
}
|
|
313
|
-
} else {
|
|
314
|
-
walkDocRefs(value, visit);
|
|
315
|
-
}
|
|
316
|
-
}
|
|
317
|
-
}
|
|
318
|
-
}
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
/** Rewrite every file-path reference in `doc` for a rename described by `ctx`. Mutates `doc`. */
|
|
322
|
-
export function rewriteDocRefs(doc: JsonValue, ctx: RemapCtx): RewriteResult {
|
|
323
|
-
const changes: RefChange[] = [];
|
|
324
|
-
walkDocRefs(doc, (value, refType, rootRelativeBare) => {
|
|
325
|
-
const cls = classifyRef(value);
|
|
326
|
-
if (cls.kind !== "path") {
|
|
327
|
-
return null;
|
|
328
|
-
}
|
|
329
|
-
const out = rewriteRef(cls, ctx, rootRelativeBare);
|
|
330
|
-
if (out === null) {
|
|
331
|
-
return null;
|
|
332
|
-
}
|
|
333
|
-
changes.push({ from: value, refType, to: out });
|
|
334
|
-
return out;
|
|
335
|
-
});
|
|
336
|
-
return { changes, doc };
|
|
337
|
-
}
|
|
338
|
-
|
|
339
|
-
/**
|
|
340
|
-
* Recursive tag walk. With `newTag` set, every `tagName === oldTag` is rewritten; with `newTag`
|
|
341
|
-
* null, they are only counted — the read side of the same traversal.
|
|
342
|
-
*/
|
|
343
|
-
function walkTags(
|
|
344
|
-
node: JsonValue | undefined,
|
|
345
|
-
oldTag: string,
|
|
346
|
-
newTag: string | null,
|
|
347
|
-
counter: { n: number },
|
|
348
|
-
): void {
|
|
349
|
-
if (Array.isArray(node)) {
|
|
350
|
-
for (const item of node) {
|
|
351
|
-
walkTags(item, oldTag, newTag, counter);
|
|
352
|
-
}
|
|
353
|
-
return;
|
|
354
|
-
}
|
|
355
|
-
if (!isJsonObject(node)) {
|
|
356
|
-
return;
|
|
357
|
-
}
|
|
358
|
-
if (node.tagName === oldTag) {
|
|
359
|
-
if (newTag !== null) {
|
|
360
|
-
node.tagName = newTag;
|
|
361
|
-
}
|
|
362
|
-
counter.n += 1;
|
|
363
|
-
}
|
|
364
|
-
for (const key of Object.keys(node)) {
|
|
365
|
-
walkTags(node[key], oldTag, newTag, counter);
|
|
366
|
-
}
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
/**
|
|
370
|
-
* Rename a custom-element tag throughout `doc` — instance nodes (`<old-tag>`), mapped-list
|
|
371
|
-
* `map.tagName`, and the component definition file's own root `tagName`. File references (`$ref`,
|
|
372
|
-
* `$elements`, `cases`) are intentionally left to `rewriteDocRefs`, so the two passes compose.
|
|
373
|
-
* Mutates `doc`.
|
|
374
|
-
*/
|
|
375
|
-
export function rewriteTagName(doc: JsonValue, oldTag: string, newTag: string): TagRewriteResult {
|
|
376
|
-
const counter = { n: 0 };
|
|
377
|
-
if (oldTag !== newTag) {
|
|
378
|
-
walkTags(doc, oldTag, newTag, counter);
|
|
379
|
-
}
|
|
380
|
-
return { count: counter.n, doc };
|
|
381
|
-
}
|
|
382
|
-
|
|
383
|
-
/**
|
|
384
|
-
* How many nodes in `doc` carry `tagName === tag`. Read-only; `doc` is never touched.
|
|
385
|
-
*
|
|
386
|
-
* A component's OWN definition file answers 1 for its root node, which is why the usage query skips
|
|
387
|
-
* the definition file rather than subtracting one — a component may legitimately nest itself.
|
|
388
|
-
*/
|
|
389
|
-
export function countTagUses(doc: JsonValue, tag: string): number {
|
|
390
|
-
const counter = { n: 0 };
|
|
391
|
-
walkTags(doc, tag, null, counter);
|
|
392
|
-
return counter.n;
|
|
393
|
-
}
|
|
10
|
+
export * from "@jxsuite/protocol/refs";
|
package/src/refactor/scan.ts
CHANGED
|
@@ -85,7 +85,20 @@ export function documentGlob(registry: FormatRegistry): string {
|
|
|
85
85
|
* when no parser claims the extension.
|
|
86
86
|
*/
|
|
87
87
|
export async function loadDoc(fp: string, registry: FormatRegistry): Promise<LoadedDoc> {
|
|
88
|
-
|
|
88
|
+
return parseDoc(fp, await readFile(fp, "utf8"), registry);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Parse a document's text as the file at `fp` would be read, returning the doc and whichever
|
|
93
|
+
* write-back paths the format declares: {@link loadDoc} without the read, for a caller that already
|
|
94
|
+
* holds the bytes it will name as a write's base (the project state host's rename, §9). Throws when
|
|
95
|
+
* no parser claims the extension.
|
|
96
|
+
*/
|
|
97
|
+
export async function parseDoc(
|
|
98
|
+
fp: string,
|
|
99
|
+
raw: string,
|
|
100
|
+
registry: FormatRegistry | null,
|
|
101
|
+
): Promise<LoadedDoc> {
|
|
89
102
|
if (isJsonPath(fp)) {
|
|
90
103
|
return {
|
|
91
104
|
// SAFETY: JSON.parse without a reviver only ever yields a JSON value; its `any` says no more.
|
|
@@ -119,7 +132,7 @@ export async function loadDoc(fp: string, registry: FormatRegistry): Promise<Loa
|
|
|
119
132
|
};
|
|
120
133
|
}
|
|
121
134
|
const ext = extname(fp);
|
|
122
|
-
const parseEntry = registry
|
|
135
|
+
const parseEntry = registry?.byExtension(ext, "parse");
|
|
123
136
|
if (!parseEntry) {
|
|
124
137
|
throw new Error(`No parser for "${ext}"`);
|
|
125
138
|
}
|
|
@@ -128,8 +141,8 @@ export async function loadDoc(fp: string, registry: FormatRegistry): Promise<Loa
|
|
|
128
141
|
over it in refs.ts re-checks each node with Array.isArray / isJsonObject / isString before
|
|
129
142
|
reading it, so such a leaf is skipped rather than misread. */
|
|
130
143
|
const doc = (await parseEntry.call("parse", raw)) as JsonValue;
|
|
131
|
-
const serializeEntry = registry
|
|
132
|
-
const rewriteEntry = registry
|
|
144
|
+
const serializeEntry = registry?.byExtension(ext, "serialize");
|
|
145
|
+
const rewriteEntry = registry?.byExtension(ext, "rewrite");
|
|
133
146
|
return {
|
|
134
147
|
doc,
|
|
135
148
|
rewrite: rewriteEntry
|
package/src/refactor/watcher.ts
CHANGED
|
@@ -30,22 +30,54 @@ function isIgnored(root: string, path: string): boolean {
|
|
|
30
30
|
|
|
31
31
|
export interface FsWatcherHandle {
|
|
32
32
|
close: () => Promise<void>;
|
|
33
|
+
/**
|
|
34
|
+
* Settles once chokidar's initial scan is done and every directory under the root is watched.
|
|
35
|
+
*
|
|
36
|
+
* `ignoreInitial` means nothing that existed, or was written, while the scan ran is announced: a
|
|
37
|
+
* consumer that listed the tree before this settles must list it again after, or a file written
|
|
38
|
+
* in that window (a scaffold, an install) stays invisible until something else touches it. It
|
|
39
|
+
* never rejects; a watcher closed before it was ready resolves it too.
|
|
40
|
+
*/
|
|
41
|
+
ready: Promise<void>;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Options for {@link createFsWatcher}. */
|
|
45
|
+
export interface FsWatcherOptions {
|
|
46
|
+
/** Quiet period, in ms, before a coalesced batch is delivered. Defaults to 40. */
|
|
47
|
+
debounce?: number;
|
|
48
|
+
/**
|
|
49
|
+
* How long, in ms, a file's size must hold still before its `add`/`change` is reported. Defaults
|
|
50
|
+
* to 50, the dev server's own watcher setting, so an editor's or an installer's partial write is
|
|
51
|
+
* reported once, finished, rather than as a half-written file.
|
|
52
|
+
*/
|
|
53
|
+
stabilityThreshold?: number;
|
|
54
|
+
/**
|
|
55
|
+
* Told about every watcher error, a non-Error cause wrapped in one. Errors are never fatal;
|
|
56
|
+
* without this they are logged.
|
|
57
|
+
*/
|
|
58
|
+
onError?: (error: Error) => void;
|
|
33
59
|
}
|
|
34
60
|
|
|
35
61
|
/**
|
|
36
62
|
* Watch `root`, coalescing rapid changes and delivering batches to `sink`. Returns a handle whose
|
|
37
|
-
* `close()` stops the watcher and clears any pending batch
|
|
63
|
+
* `close()` stops the watcher and clears any pending batch, and whose `ready` settles when the
|
|
64
|
+
* initial scan has finished.
|
|
38
65
|
*/
|
|
39
66
|
export function createFsWatcher(
|
|
40
67
|
root: string,
|
|
41
68
|
sink: (events: FsEventPayload[]) => void,
|
|
42
|
-
opts:
|
|
69
|
+
opts: FsWatcherOptions = {},
|
|
43
70
|
): FsWatcherHandle {
|
|
44
71
|
const debounceMs = opts.debounce ?? 40;
|
|
45
72
|
let buffer: FsEventPayload[] = [];
|
|
46
73
|
let timer: ReturnType<typeof setTimeout> | null = null;
|
|
47
74
|
|
|
48
75
|
const watcher = watch(root, {
|
|
76
|
+
// The same settings as the dev server's watcher (watch.ts), so both report a write once it is whole.
|
|
77
|
+
awaitWriteFinish: {
|
|
78
|
+
pollInterval: 10,
|
|
79
|
+
stabilityThreshold: opts.stabilityThreshold ?? 50,
|
|
80
|
+
},
|
|
49
81
|
/* Left on deliberately: a symlink inside a project is project content, and its events belong
|
|
50
82
|
in the sidebar. It is the link pointing OUT of the root that walks the watcher off into the
|
|
51
83
|
rest of the filesystem, and createWatchIgnore drops exactly those — along with the sockets
|
|
@@ -81,11 +113,23 @@ export function createFsWatcher(
|
|
|
81
113
|
watches. The filter above means these should now be rare; the listener means they are never
|
|
82
114
|
fatal when they are not. */
|
|
83
115
|
watcher.on("error", (cause) => {
|
|
116
|
+
if (opts.onError) {
|
|
117
|
+
opts.onError(cause instanceof Error ? cause : new Error(errorMessage(cause)));
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
84
120
|
console.error(`[fs-watch] ${errorMessage(cause)}`);
|
|
85
121
|
});
|
|
86
122
|
|
|
123
|
+
// Assigned synchronously by the executor, so it is set before anything below can call it.
|
|
124
|
+
let markReady: (() => void) | undefined;
|
|
125
|
+
const ready = new Promise<void>((resolve) => {
|
|
126
|
+
markReady = resolve;
|
|
127
|
+
});
|
|
128
|
+
watcher.once("ready", () => markReady?.());
|
|
129
|
+
|
|
87
130
|
return {
|
|
88
131
|
close: async () => {
|
|
132
|
+
markReady?.();
|
|
89
133
|
if (timer) {
|
|
90
134
|
clearTimeout(timer);
|
|
91
135
|
timer = null;
|
|
@@ -93,5 +137,6 @@ export function createFsWatcher(
|
|
|
93
137
|
buffer = [];
|
|
94
138
|
await watcher.close();
|
|
95
139
|
},
|
|
140
|
+
ready,
|
|
96
141
|
};
|
|
97
142
|
}
|
package/src/serve.node.ts
CHANGED
|
@@ -221,6 +221,7 @@ export async function serve<Data = undefined>(
|
|
|
221
221
|
const socket: ServeSocket<Data> = {
|
|
222
222
|
data,
|
|
223
223
|
send: (message) => ws.send(message),
|
|
224
|
+
getBufferedAmount: () => ws.bufferedAmount,
|
|
224
225
|
close: (code, reason) => ws.close(code, reason),
|
|
225
226
|
};
|
|
226
227
|
ws.on("message", (raw, isBinary) => {
|
package/src/serve.ts
CHANGED
|
@@ -2,11 +2,11 @@
|
|
|
2
2
|
* The HTTP + WebSocket server surface the backend's servers are written against.
|
|
3
3
|
*
|
|
4
4
|
* It is the part of `Bun.serve` they use and nothing more: a Fetch-API handler that may upgrade, a
|
|
5
|
-
* bound port and URL, `stop()`, an idle timeout, and a socket's `data`, `send
|
|
6
|
-
* implementations answer it, selected at resolution time by the `#serve` import's
|
|
7
|
-
* (Node's conditional exports): `serve.bun.ts` passes through to `Bun.serve` under Bun,
|
|
8
|
-
* `serve.node.ts` is `node:http` plus `ws` everywhere else, which is the packaged desktop
|
|
9
|
-
* (specs/desktop.md §7.1). A bundle built for Node therefore contains no Bun code at all.
|
|
5
|
+
* bound port and URL, `stop()`, an idle timeout, and a socket's `data`, `send`, `getBufferedAmount`
|
|
6
|
+
* and `close`. Two implementations answer it, selected at resolution time by the `#serve` import's
|
|
7
|
+
* conditions (Node's conditional exports): `serve.bun.ts` passes through to `Bun.serve` under Bun,
|
|
8
|
+
* and `serve.node.ts` is `node:http` plus `ws` everywhere else, which is the packaged desktop
|
|
9
|
+
* backend (specs/desktop.md §7.1). A bundle built for Node therefore contains no Bun code at all.
|
|
10
10
|
*
|
|
11
11
|
* `serve()` resolves once the server is listening, because Node binds asynchronously: a port read
|
|
12
12
|
* straight after `listen()` is not there yet.
|
|
@@ -19,6 +19,8 @@ export interface ServeSocket<Data> {
|
|
|
19
19
|
readonly data: Data;
|
|
20
20
|
/** Send a text frame (a string) or a binary frame (bytes). A closed socket drops the frame. */
|
|
21
21
|
send: (message: string | Uint8Array) => void;
|
|
22
|
+
/** How many bytes sent frames still hold in the socket's buffer, waiting for the peer to read. */
|
|
23
|
+
getBufferedAmount: () => number;
|
|
22
24
|
close: (code?: number, reason?: string) => void;
|
|
23
25
|
}
|
|
24
26
|
|
package/src/server.ts
CHANGED
|
@@ -16,6 +16,9 @@
|
|
|
16
16
|
import { dirname, isAbsolute, relative, resolve } from "node:path";
|
|
17
17
|
import { buildAll } from "./build.ts";
|
|
18
18
|
import { createCollabRegistry } from "./collab.ts";
|
|
19
|
+
import { createProjectEventsService } from "./project-events.ts";
|
|
20
|
+
import type { ProjectEventsOptions } from "./project-events.ts";
|
|
21
|
+
import { PROJECT_EVENTS_PATH } from "@jxsuite/protocol/project-state-frames";
|
|
19
22
|
import { createWatcher, injectSSE } from "./watch.ts";
|
|
20
23
|
import { invalidateReferenceCache } from "./refactor/find-refs.ts";
|
|
21
24
|
import { createFsWatcher } from "./refactor/watcher.ts";
|
|
@@ -29,6 +32,7 @@ import {
|
|
|
29
32
|
import {
|
|
30
33
|
assertAccessible,
|
|
31
34
|
assertCreatableParent,
|
|
35
|
+
getExtensionRegistry,
|
|
32
36
|
handleStudioApi,
|
|
33
37
|
isOwnedProjectDir,
|
|
34
38
|
} from "./studio-api.ts";
|
|
@@ -39,6 +43,7 @@ import {
|
|
|
39
43
|
serveProjectFile,
|
|
40
44
|
} from "./net-guard.ts";
|
|
41
45
|
import { handleCodeApi } from "./code-api.ts";
|
|
46
|
+
import { clearLivePreviewOverlay, setLivePreviewOverlay } from "./live-preview.ts";
|
|
42
47
|
import { handleAiApi } from "./ai-api.ts";
|
|
43
48
|
import { handleImportApi } from "./import-api.ts";
|
|
44
49
|
import { mediaTypeForPath } from "@jxsuite/schema/media-type";
|
|
@@ -95,6 +100,8 @@ export async function createDevServer(options: {
|
|
|
95
100
|
watch?: boolean | DevWatchOptions;
|
|
96
101
|
studio?: boolean;
|
|
97
102
|
middleware?: (req: Request, url: URL) => Response | null | Promise<Response | null>;
|
|
103
|
+
/** How the project state service runs its host (`project-state.md` §10.2); its defaults otherwise. */
|
|
104
|
+
projectState?: ProjectEventsOptions;
|
|
98
105
|
}) {
|
|
99
106
|
const {
|
|
100
107
|
root,
|
|
@@ -105,6 +112,7 @@ export async function createDevServer(options: {
|
|
|
105
112
|
watch = true,
|
|
106
113
|
studio: enableStudio = true,
|
|
107
114
|
middleware,
|
|
115
|
+
projectState,
|
|
108
116
|
} = options;
|
|
109
117
|
|
|
110
118
|
if (!root) {
|
|
@@ -225,6 +233,18 @@ export async function createDevServer(options: {
|
|
|
225
233
|
}
|
|
226
234
|
}
|
|
227
235
|
|
|
236
|
+
// ─── Project state (/__studio/project/events) ───────────────────────────────
|
|
237
|
+
|
|
238
|
+
/* The active project's host (`project-state.md` §10.2): it serves `activeProjectRoot ?? absRoot`,
|
|
239
|
+
the root every other route resolves against, and starts only when a request needs it. */
|
|
240
|
+
const projectEvents = createProjectEventsService({
|
|
241
|
+
publish: setLivePreviewOverlay,
|
|
242
|
+
registryFor: getExtensionRegistry,
|
|
243
|
+
unpublish: clearLivePreviewOverlay,
|
|
244
|
+
...projectState,
|
|
245
|
+
});
|
|
246
|
+
await projectEvents.activate(absRoot);
|
|
247
|
+
|
|
228
248
|
// ─── Realtime co-editing (/__studio/collab) ─────────────────────────────────
|
|
229
249
|
|
|
230
250
|
// Created unconditionally (it is inert until an upgrade) so Bun.serve always has real
|
|
@@ -232,6 +252,7 @@ export async function createDevServer(options: {
|
|
|
232
252
|
const collabRegistry = createCollabRegistry({
|
|
233
253
|
absRoot,
|
|
234
254
|
activeProjectRoot: () => activeProjectRoot,
|
|
255
|
+
projectEvents,
|
|
235
256
|
});
|
|
236
257
|
if (enableStudio && fsWatcher) {
|
|
237
258
|
fsWatcher.on("change", (changedPath: string) => {
|
|
@@ -333,6 +354,11 @@ export async function createDevServer(options: {
|
|
|
333
354
|
});
|
|
334
355
|
}
|
|
335
356
|
|
|
357
|
+
// The project state stream (`project-state.md` §3.2), separate from /__reload.
|
|
358
|
+
if (path === PROJECT_EVENTS_PATH && req.method === "GET") {
|
|
359
|
+
return projectEvents.handleEvents(req, url, (named) => resolve(absRoot, named));
|
|
360
|
+
}
|
|
361
|
+
|
|
336
362
|
// Activate project — tells the server which project root to use for static file fallback.
|
|
337
363
|
// Contain the requested root: it must be under absRoot, an explicitly allowed root, a
|
|
338
364
|
// Project this server just created, or an existing project of the account's own
|
|
@@ -348,6 +374,7 @@ export async function createDevServer(options: {
|
|
|
348
374
|
if (!raw) {
|
|
349
375
|
activeProjectRoot = null;
|
|
350
376
|
await watchActiveProject(null);
|
|
377
|
+
await projectEvents.activate(absRoot);
|
|
351
378
|
return Response.json({ ok: true, root: null });
|
|
352
379
|
}
|
|
353
380
|
const requested = resolve(absRoot, raw);
|
|
@@ -366,6 +393,8 @@ export async function createDevServer(options: {
|
|
|
366
393
|
await watchActiveProject(requested);
|
|
367
394
|
}
|
|
368
395
|
activeProjectRoot = requested;
|
|
396
|
+
// Another project ends every subscription and starts a new epoch (`project-state.md` §10.2).
|
|
397
|
+
await projectEvents.activate(requested);
|
|
369
398
|
return Response.json({ ok: true, root: activeProjectRoot });
|
|
370
399
|
}
|
|
371
400
|
|
|
@@ -409,6 +438,7 @@ export async function createDevServer(options: {
|
|
|
409
438
|
allowedRoots,
|
|
410
439
|
onFileMoved: (absPath) => collabRegistry.handleExternalChange(absPath),
|
|
411
440
|
onProjectCreated: (created) => createdRoots.push(created),
|
|
441
|
+
projectEvents,
|
|
412
442
|
});
|
|
413
443
|
if (res) {
|
|
414
444
|
return res;
|
|
@@ -460,7 +490,8 @@ export async function createDevServer(options: {
|
|
|
460
490
|
for (const [name, value] of Object.entries(NO_CACHE)) {
|
|
461
491
|
headers.set(name, value);
|
|
462
492
|
}
|
|
463
|
-
|
|
493
|
+
// The status too: a `.jxn` that does not parse answers 422 with its reason.
|
|
494
|
+
return new Response(mountRes.body, { headers, status: mountRes.status });
|
|
464
495
|
}
|
|
465
496
|
}
|
|
466
497
|
|
|
@@ -557,6 +588,14 @@ export async function createDevServer(options: {
|
|
|
557
588
|
websocket: collabRegistry.websocket,
|
|
558
589
|
});
|
|
559
590
|
|
|
591
|
+
/* Stopping the server stops the project's host too: its watcher and git monitor would otherwise
|
|
592
|
+
outlive the server that started them, and its open streams would never end. */
|
|
593
|
+
const stopServer = server.stop.bind(server);
|
|
594
|
+
server.stop = async (closeActiveConnections?: boolean) => {
|
|
595
|
+
await projectEvents.close();
|
|
596
|
+
return stopServer(closeActiveConnections);
|
|
597
|
+
};
|
|
598
|
+
|
|
560
599
|
console.log(`\n@jxsuite/server listening on http://${hostname}:${server.port}`);
|
|
561
600
|
|
|
562
601
|
return server;
|