@nuvio/vite-plugin 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Nuvio contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,7 @@
1
+ # `@nuvio/vite-plugin`
2
+
3
+ Vite plugin: dev WebSocket channel, **dev-time source index**, secure file writes for Nuvio patches.
4
+
5
+ **Peer:** `vite` ^5.4 or ^6.
6
+
7
+ See the [Nuvio README](../../README.md) and [CHANGELOG](../../CHANGELOG.md).
@@ -0,0 +1,14 @@
1
+ import { Plugin } from 'vite';
2
+
3
+ interface NuvioPluginOptions {
4
+ /** Glob patterns relative to Vite config root (see DEFAULT_GLOBS). */
5
+ scanGlobs?: string[];
6
+ /** Log client ops (no source file contents). */
7
+ verbose?: boolean;
8
+ }
9
+ /**
10
+ * Nuvio Vite plugin — Phase 1: WebSocket protocol + dev-time source index + selection ack.
11
+ */
12
+ declare function nuvio(options?: NuvioPluginOptions): Plugin;
13
+
14
+ export { type NuvioPluginOptions, nuvio };
package/dist/index.js ADDED
@@ -0,0 +1,644 @@
1
+ // src/index.ts
2
+ import fs2 from "fs";
3
+ import path2 from "path";
4
+ import { WebSocket } from "ws";
5
+ import { WebSocketServer } from "ws";
6
+ import { applyPatchToSource } from "@nuvio/ast-engine";
7
+ import {
8
+ NUVIO_WS_PATH,
9
+ PROTOCOL_VERSION,
10
+ parseClientMessage,
11
+ serializeServerMessage
12
+ } from "@nuvio/shared";
13
+ import { assertPathWithinRoot } from "@nuvio/shared/secure-path";
14
+
15
+ // src/upgrade-url.ts
16
+ function pathnameFromUpgradeUrl(url) {
17
+ if (!url) {
18
+ return "";
19
+ }
20
+ try {
21
+ return new URL(url, "http://localhost").pathname;
22
+ } catch {
23
+ return "";
24
+ }
25
+ }
26
+
27
+ // src/source-index.ts
28
+ import * as fs from "fs";
29
+ import * as path from "path";
30
+ import { parse } from "@babel/parser";
31
+ import traverseImport from "@babel/traverse";
32
+ import fg from "fast-glob";
33
+ function getTraverseFn() {
34
+ if (typeof traverseImport === "function") {
35
+ return traverseImport;
36
+ }
37
+ const d = traverseImport.default;
38
+ if (typeof d === "function") {
39
+ return d;
40
+ }
41
+ throw new Error("[Nuvio] @babel/traverse did not resolve to a callable export");
42
+ }
43
+ var WRAPPER_TAGS = /* @__PURE__ */ new Set(["EditableText", "EditableContainer"]);
44
+ function extractIdsFromSource(fileAbs, code) {
45
+ const acc = [];
46
+ let ast;
47
+ try {
48
+ ast = parse(code, {
49
+ sourceType: "module",
50
+ plugins: ["typescript", "jsx"],
51
+ sourceFilename: fileAbs
52
+ });
53
+ } catch {
54
+ return acc;
55
+ }
56
+ const traverseFn = getTraverseFn();
57
+ traverseFn(ast, {
58
+ JSXOpeningElement(p) {
59
+ const opening = p.node;
60
+ let tagName = "";
61
+ if (opening.name.type === "JSXIdentifier") {
62
+ tagName = opening.name.name;
63
+ } else {
64
+ return;
65
+ }
66
+ for (const attr of opening.attributes) {
67
+ if (attr.type !== "JSXAttribute") {
68
+ continue;
69
+ }
70
+ if (attr.name.type !== "JSXIdentifier") {
71
+ continue;
72
+ }
73
+ const prop = attr.name.name;
74
+ const loc = attr.loc?.start ?? opening.loc?.start;
75
+ const line = loc?.line ?? 1;
76
+ const column = loc?.column ?? 0;
77
+ if (prop === "data-nuvio-id" && attr.value?.type === "StringLiteral") {
78
+ const id = attr.value.value.trim();
79
+ if (id) {
80
+ acc.push({ id, file: path.resolve(fileAbs), line, column });
81
+ }
82
+ continue;
83
+ }
84
+ if (WRAPPER_TAGS.has(tagName) && prop === "id" && attr.value?.type === "StringLiteral") {
85
+ const id = attr.value.value.trim();
86
+ if (id) {
87
+ acc.push({ id, file: path.resolve(fileAbs), line, column });
88
+ }
89
+ }
90
+ }
91
+ }
92
+ });
93
+ return acc;
94
+ }
95
+ function buildSourceIndex(rootAbs, globPatterns) {
96
+ const root = path.resolve(rootAbs);
97
+ const parseErrors = [];
98
+ const normalizedPatterns = globPatterns.map((g) => {
99
+ const resolved = path.isAbsolute(g) ? path.resolve(g) : path.resolve(root, g);
100
+ return resolved.replace(/\\/g, "/");
101
+ });
102
+ const matched = fg.sync(normalizedPatterns, {
103
+ absolute: true,
104
+ ignore: ["**/node_modules/**", "**/dist/**"],
105
+ onlyFiles: true
106
+ });
107
+ const files = [...new Set(matched)];
108
+ const byId = /* @__PURE__ */ new Map();
109
+ for (const file of files) {
110
+ let code;
111
+ try {
112
+ code = fs.readFileSync(file, "utf8");
113
+ } catch (e) {
114
+ parseErrors.push({ file, message: String(e) });
115
+ continue;
116
+ }
117
+ let occurrences;
118
+ try {
119
+ occurrences = extractIdsFromSource(file, code);
120
+ } catch (e) {
121
+ parseErrors.push({ file, message: String(e) });
122
+ continue;
123
+ }
124
+ for (const occ of occurrences) {
125
+ const list = byId.get(occ.id) ?? [];
126
+ list.push(occ);
127
+ byId.set(occ.id, list);
128
+ }
129
+ }
130
+ const duplicateErrors = [];
131
+ const entries = [];
132
+ for (const [id, list] of byId) {
133
+ if (list.length > 1) {
134
+ duplicateErrors.push({
135
+ id,
136
+ occurrences: list.map((o) => ({
137
+ file: o.file,
138
+ line: o.line,
139
+ column: o.column
140
+ }))
141
+ });
142
+ } else if (list.length === 1) {
143
+ entries.push(list[0]);
144
+ }
145
+ }
146
+ entries.sort((a, b) => {
147
+ const fa = a.file.localeCompare(b.file);
148
+ if (fa !== 0) {
149
+ return fa;
150
+ }
151
+ if (a.line !== b.line) {
152
+ return a.line - b.line;
153
+ }
154
+ return a.column - b.column;
155
+ });
156
+ duplicateErrors.sort((a, b) => a.id.localeCompare(b.id));
157
+ return {
158
+ entries,
159
+ duplicateErrors,
160
+ parseErrors,
161
+ scannedFileCount: files.length
162
+ };
163
+ }
164
+ function indexQuality(b) {
165
+ return [b.entries.length, -b.duplicateErrors.length, b.scannedFileCount];
166
+ }
167
+ function isBetterIndex(candidate, current) {
168
+ const c = indexQuality(candidate);
169
+ const b = indexQuality(current);
170
+ for (let i = 0; i < 3; i++) {
171
+ if (c[i] !== b[i]) {
172
+ return c[i] > b[i];
173
+ }
174
+ }
175
+ return false;
176
+ }
177
+ function pickBestSourceIndex(rootCandidates, globPatterns) {
178
+ const roots = [...new Set(rootCandidates.map((r) => path.resolve(r)).filter((r) => r.length > 0))];
179
+ if (roots.length === 0) {
180
+ return {
181
+ entries: [],
182
+ duplicateErrors: [],
183
+ parseErrors: [],
184
+ scannedFileCount: 0
185
+ };
186
+ }
187
+ let best = buildSourceIndex(roots[0], globPatterns);
188
+ for (let i = 1; i < roots.length; i++) {
189
+ const built = buildSourceIndex(roots[i], globPatterns);
190
+ if (isBetterIndex(built, best)) {
191
+ best = built;
192
+ }
193
+ }
194
+ return best;
195
+ }
196
+
197
+ // src/index.ts
198
+ var APP_ENTRY_CANDIDATES = ["src/App.tsx", "src/app.tsx", "App.tsx"];
199
+ function nuvioWsMessageToText(data) {
200
+ if (typeof data === "string") {
201
+ return data;
202
+ }
203
+ if (Buffer.isBuffer(data)) {
204
+ return data.toString("utf8");
205
+ }
206
+ if (data instanceof ArrayBuffer) {
207
+ return Buffer.from(data).toString("utf8");
208
+ }
209
+ if (ArrayBuffer.isView(data)) {
210
+ const v = data;
211
+ return Buffer.from(v.buffer, v.byteOffset, v.byteLength).toString("utf8");
212
+ }
213
+ return String(data);
214
+ }
215
+ function supplementIndexFromAppTsx(serverRoot, built, emitWarn = console.warn) {
216
+ if (built.entries.length > 0) {
217
+ return built;
218
+ }
219
+ for (const rel of APP_ENTRY_CANDIDATES) {
220
+ const appTsx = path2.resolve(serverRoot, rel);
221
+ if (!fs2.existsSync(appTsx)) {
222
+ continue;
223
+ }
224
+ try {
225
+ const code = fs2.readFileSync(appTsx, "utf8");
226
+ const hits = extractIdsFromSource(appTsx, code);
227
+ if (hits.length === 0) {
228
+ continue;
229
+ }
230
+ emitWarn(
231
+ `[Nuvio] Source index had 0 ids; supplemented from ${appTsx} (${hits.length} id(s)). Fix scan roots if this is unexpected.`
232
+ );
233
+ return {
234
+ ...built,
235
+ entries: hits,
236
+ scannedFileCount: Math.max(built.scannedFileCount, 1)
237
+ };
238
+ } catch {
239
+ }
240
+ }
241
+ return built;
242
+ }
243
+ var DEFAULT_GLOBS = [
244
+ "src/**/*.{tsx,jsx}",
245
+ "apps/**/src/**/*.{tsx,jsx}",
246
+ "packages/**/src/**/*.{tsx,jsx}"
247
+ ];
248
+ function isAllowedOrigin(origin) {
249
+ if (origin === void 0 || origin === "") {
250
+ return true;
251
+ }
252
+ try {
253
+ const u = new URL(origin);
254
+ return (u.hostname === "localhost" || u.hostname === "127.0.0.1") && (u.protocol === "http:" || u.protocol === "https:");
255
+ } catch {
256
+ return false;
257
+ }
258
+ }
259
+ function nuvio(options) {
260
+ const scanGlobs = options?.scanGlobs ?? DEFAULT_GLOBS;
261
+ const verbose = options?.verbose ?? false;
262
+ let indexVersion = 0;
263
+ let cachedIndexPayload = null;
264
+ const idToEntry = /* @__PURE__ */ new Map();
265
+ return {
266
+ name: "nuvio",
267
+ apply: "serve",
268
+ configureServer(server) {
269
+ const log = server.config.logger;
270
+ const fromConfigFile = typeof server.config.configFile === "string" ? path2.dirname(server.config.configFile) : "";
271
+ const serverRoot = path2.resolve(server.config.root);
272
+ const rootCandidates = [
273
+ path2.resolve(fromConfigFile || serverRoot),
274
+ serverRoot,
275
+ process.cwd()
276
+ ];
277
+ const rootsLabel = [...new Set(rootCandidates)].join(" | ");
278
+ const wss = new WebSocketServer({ noServer: true });
279
+ const undoStack = [];
280
+ const UNDO_MAX = 32;
281
+ const pushUndoSnapshot = (file, contents) => {
282
+ undoStack.push({ file, contents });
283
+ while (undoStack.length > UNDO_MAX) {
284
+ undoStack.shift();
285
+ }
286
+ };
287
+ const rebuildIndex = () => {
288
+ let built = pickBestSourceIndex(rootCandidates, scanGlobs);
289
+ built = supplementIndexFromAppTsx(serverRoot, built, log.warn);
290
+ if (built.entries.length === 0) {
291
+ const fallback = buildSourceIndex(serverRoot, ["src/**/*.{tsx,jsx}"]);
292
+ if (fallback.entries.length > 0) {
293
+ log.warn(
294
+ `[Nuvio] Multi-root scan yielded 0 ids; using serverRoot-only index (${fallback.entries.length} id(s)) from ${serverRoot}.`
295
+ );
296
+ built = fallback;
297
+ }
298
+ }
299
+ indexVersion += 1;
300
+ idToEntry.clear();
301
+ for (const e of built.entries) {
302
+ idToEntry.set(e.id, e);
303
+ }
304
+ cachedIndexPayload = serializeServerMessage({
305
+ type: "indexReady",
306
+ protocolVersion: PROTOCOL_VERSION,
307
+ indexVersion,
308
+ entries: built.entries,
309
+ duplicateErrors: built.duplicateErrors
310
+ });
311
+ if (verbose) {
312
+ if (built.parseErrors.length > 0) {
313
+ log.warn(`[Nuvio] index parse issues: ${built.parseErrors.length} file(s)`);
314
+ }
315
+ if (built.duplicateErrors.length > 0) {
316
+ log.warn(
317
+ `[Nuvio] duplicate ids: ${built.duplicateErrors.map((d) => d.id).join(", ")}`
318
+ );
319
+ }
320
+ log.info(
321
+ `[Nuvio] index roots=${rootsLabel} matchedFiles=${built.scannedFileCount} uniqueIds=${built.entries.length}`
322
+ );
323
+ } else {
324
+ log.info(
325
+ `[Nuvio] index v${indexVersion} \u2014 ${built.entries.length} id(s), ${built.scannedFileCount} file(s)`
326
+ );
327
+ }
328
+ if (built.scannedFileCount === 0) {
329
+ log.warn(
330
+ `[Nuvio] Source index matched 0 files for globs [${scanGlobs.join(", ")}] under roots ${rootsLabel}. Dev server cwd does not affect this if Vite root is correct; ensure \`data-nuvio-id\` lives under that root.`
331
+ );
332
+ } else if (built.entries.length === 0 && built.parseErrors.length > 0) {
333
+ const e0 = built.parseErrors[0];
334
+ log.warn(
335
+ `[Nuvio] Source index has 0 ids after ${built.scannedFileCount} file(s); first error: ${e0.file} \u2014 ${e0.message}`
336
+ );
337
+ } else if (built.entries.length === 0 && built.duplicateErrors.length > 0) {
338
+ log.warn(
339
+ `[Nuvio] Source index: all contract ids appear duplicated \u2014 ${built.duplicateErrors.map((d) => d.id).join(", ")}`
340
+ );
341
+ } else if (built.entries.length === 0 && built.duplicateErrors.length === 0 && built.parseErrors.length === 0) {
342
+ log.warn(
343
+ `[Nuvio] Source index scanned ${built.scannedFileCount} file(s) under roots ${rootsLabel} but extracted 0 ids (no \`data-nuvio-id\` / wrapper hits).`
344
+ );
345
+ }
346
+ if (cachedIndexPayload && wss.clients.size > 0) {
347
+ for (const client of wss.clients) {
348
+ if (client.readyState === WebSocket.OPEN) {
349
+ client.send(cachedIndexPayload);
350
+ }
351
+ }
352
+ }
353
+ };
354
+ const debouncedRebuild = /* @__PURE__ */ (() => {
355
+ let t;
356
+ return () => {
357
+ if (t) {
358
+ clearTimeout(t);
359
+ }
360
+ t = setTimeout(() => {
361
+ rebuildIndex();
362
+ t = void 0;
363
+ }, 120);
364
+ };
365
+ })();
366
+ server.watcher.on("change", (file) => {
367
+ if (!/\.(tsx|jsx)$/.test(file)) {
368
+ return;
369
+ }
370
+ debouncedRebuild();
371
+ });
372
+ wss.on("connection", (ws) => {
373
+ if (cachedIndexPayload && ws.readyState === WebSocket.OPEN) {
374
+ ws.send(cachedIndexPayload);
375
+ }
376
+ ws.on("message", async (data) => {
377
+ const text = nuvioWsMessageToText(data);
378
+ const msg = parseClientMessage(text);
379
+ if (!msg) {
380
+ ws.send(
381
+ serializeServerMessage({
382
+ type: "error",
383
+ code: "bad_message",
384
+ message: "Invalid client message"
385
+ })
386
+ );
387
+ return;
388
+ }
389
+ if (msg.protocolVersion !== PROTOCOL_VERSION) {
390
+ ws.send(
391
+ serializeServerMessage({
392
+ type: "error",
393
+ code: "bad_version",
394
+ message: `Expected protocolVersion ${PROTOCOL_VERSION}`,
395
+ requestId: "requestId" in msg ? msg.requestId : void 0
396
+ })
397
+ );
398
+ return;
399
+ }
400
+ if (msg.type === "ping") {
401
+ if (verbose) {
402
+ log.info(`[Nuvio] ping ${msg.requestId}`);
403
+ }
404
+ ws.send(
405
+ serializeServerMessage({
406
+ type: "pong",
407
+ protocolVersion: PROTOCOL_VERSION,
408
+ requestId: msg.requestId
409
+ })
410
+ );
411
+ if (cachedIndexPayload) {
412
+ ws.send(cachedIndexPayload);
413
+ }
414
+ return;
415
+ }
416
+ if (msg.type === "select") {
417
+ if (verbose) {
418
+ log.info(`[Nuvio] select ${msg.id}`);
419
+ }
420
+ const entry = idToEntry.get(msg.id);
421
+ if (!entry) {
422
+ log.warn(`[Nuvio] select unknown_id: ${msg.id} (index has ${idToEntry.size} id(s))`);
423
+ ws.send(
424
+ serializeServerMessage({
425
+ type: "selectAck",
426
+ protocolVersion: PROTOCOL_VERSION,
427
+ requestId: msg.requestId,
428
+ id: msg.id,
429
+ ok: false,
430
+ errorCode: "unknown_id",
431
+ errorMessage: "Id not found in dev source index"
432
+ })
433
+ );
434
+ return;
435
+ }
436
+ ws.send(
437
+ serializeServerMessage({
438
+ type: "selectAck",
439
+ protocolVersion: PROTOCOL_VERSION,
440
+ requestId: msg.requestId,
441
+ id: msg.id,
442
+ ok: true,
443
+ file: entry.file,
444
+ line: entry.line,
445
+ column: entry.column
446
+ })
447
+ );
448
+ return;
449
+ }
450
+ if (msg.type === "patchUndo") {
451
+ const writeGuardRoot = path2.resolve(fromConfigFile || serverRoot);
452
+ const last = undoStack.pop();
453
+ if (!last) {
454
+ ws.send(
455
+ serializeServerMessage({
456
+ type: "patchUndoAck",
457
+ protocolVersion: PROTOCOL_VERSION,
458
+ requestId: msg.requestId,
459
+ ok: false,
460
+ errorCode: "empty_stack",
461
+ errorMessage: "Nothing to undo"
462
+ })
463
+ );
464
+ return;
465
+ }
466
+ try {
467
+ assertPathWithinRoot(writeGuardRoot, last.file);
468
+ fs2.writeFileSync(last.file, last.contents, "utf8");
469
+ } catch (e) {
470
+ undoStack.push(last);
471
+ ws.send(
472
+ serializeServerMessage({
473
+ type: "patchUndoAck",
474
+ protocolVersion: PROTOCOL_VERSION,
475
+ requestId: msg.requestId,
476
+ ok: false,
477
+ errorCode: "undo_write_error",
478
+ errorMessage: String(e)
479
+ })
480
+ );
481
+ return;
482
+ }
483
+ log.info(`[Nuvio] undo restored ${last.file}`);
484
+ ws.send(
485
+ serializeServerMessage({
486
+ type: "patchUndoAck",
487
+ protocolVersion: PROTOCOL_VERSION,
488
+ requestId: msg.requestId,
489
+ ok: true,
490
+ file: last.file,
491
+ undoStackDepth: undoStack.length
492
+ })
493
+ );
494
+ return;
495
+ }
496
+ if (msg.type === "patchApply") {
497
+ const entry = idToEntry.get(msg.id);
498
+ const writeGuardRoot = path2.resolve(fromConfigFile || serverRoot);
499
+ const dryRun = msg.dryRun === true;
500
+ const patchAckExtras = dryRun ? { dryRun: true } : {};
501
+ if (!entry) {
502
+ log.warn(`[Nuvio] patch unknown_id: ${msg.id} (index has ${idToEntry.size} id(s))`);
503
+ ws.send(
504
+ serializeServerMessage({
505
+ type: "patchAck",
506
+ protocolVersion: PROTOCOL_VERSION,
507
+ requestId: msg.requestId,
508
+ id: msg.id,
509
+ ok: false,
510
+ errorCode: "unknown_id",
511
+ errorMessage: "Id not found in dev source index",
512
+ ...patchAckExtras
513
+ })
514
+ );
515
+ return;
516
+ }
517
+ try {
518
+ assertPathWithinRoot(writeGuardRoot, entry.file);
519
+ } catch (e) {
520
+ ws.send(
521
+ serializeServerMessage({
522
+ type: "patchAck",
523
+ protocolVersion: PROTOCOL_VERSION,
524
+ requestId: msg.requestId,
525
+ id: msg.id,
526
+ ok: false,
527
+ errorCode: "path_escape",
528
+ errorMessage: String(e),
529
+ ...patchAckExtras
530
+ })
531
+ );
532
+ return;
533
+ }
534
+ let source;
535
+ try {
536
+ source = fs2.readFileSync(entry.file, "utf8");
537
+ } catch (e) {
538
+ ws.send(
539
+ serializeServerMessage({
540
+ type: "patchAck",
541
+ protocolVersion: PROTOCOL_VERSION,
542
+ requestId: msg.requestId,
543
+ id: msg.id,
544
+ ok: false,
545
+ errorCode: "read_error",
546
+ errorMessage: String(e),
547
+ ...patchAckExtras
548
+ })
549
+ );
550
+ return;
551
+ }
552
+ const result = await applyPatchToSource(source, entry.file, msg.id, msg.ops);
553
+ if (!result.ok) {
554
+ ws.send(
555
+ serializeServerMessage({
556
+ type: "patchAck",
557
+ protocolVersion: PROTOCOL_VERSION,
558
+ requestId: msg.requestId,
559
+ id: msg.id,
560
+ ok: false,
561
+ errorCode: result.code,
562
+ errorMessage: result.message,
563
+ ...patchAckExtras
564
+ })
565
+ );
566
+ return;
567
+ }
568
+ if (dryRun) {
569
+ ws.send(
570
+ serializeServerMessage({
571
+ type: "patchAck",
572
+ protocolVersion: PROTOCOL_VERSION,
573
+ requestId: msg.requestId,
574
+ id: msg.id,
575
+ ok: true,
576
+ diffSummary: result.diffSummary,
577
+ dryRun: true
578
+ })
579
+ );
580
+ if (verbose) {
581
+ log.info(`[Nuvio] patchPreview ${msg.id} ${msg.ops.map((o) => o.kind).join(",")}`);
582
+ }
583
+ return;
584
+ }
585
+ try {
586
+ fs2.writeFileSync(entry.file, result.source, "utf8");
587
+ } catch (e) {
588
+ ws.send(
589
+ serializeServerMessage({
590
+ type: "patchAck",
591
+ protocolVersion: PROTOCOL_VERSION,
592
+ requestId: msg.requestId,
593
+ id: msg.id,
594
+ ok: false,
595
+ errorCode: "write_error",
596
+ errorMessage: String(e)
597
+ })
598
+ );
599
+ return;
600
+ }
601
+ pushUndoSnapshot(entry.file, source);
602
+ log.info(`[Nuvio] touched ${entry.file}`);
603
+ ws.send(
604
+ serializeServerMessage({
605
+ type: "patchAck",
606
+ protocolVersion: PROTOCOL_VERSION,
607
+ requestId: msg.requestId,
608
+ id: msg.id,
609
+ ok: true,
610
+ diffSummary: result.diffSummary,
611
+ writtenFile: entry.file,
612
+ undoStackDepth: undoStack.length
613
+ })
614
+ );
615
+ if (verbose) {
616
+ log.info(`[Nuvio] patchApply ${msg.id} ${msg.ops.map((o) => o.kind).join(",")}`);
617
+ }
618
+ return;
619
+ }
620
+ });
621
+ });
622
+ server.httpServer?.on(
623
+ "upgrade",
624
+ (request, socket, head) => {
625
+ const pathname = pathnameFromUpgradeUrl(request.url);
626
+ if (pathname !== NUVIO_WS_PATH) {
627
+ return;
628
+ }
629
+ if (!isAllowedOrigin(request.headers.origin)) {
630
+ socket.destroy();
631
+ return;
632
+ }
633
+ wss.handleUpgrade(request, socket, head, (ws) => {
634
+ wss.emit("connection", ws, request);
635
+ });
636
+ }
637
+ );
638
+ rebuildIndex();
639
+ }
640
+ };
641
+ }
642
+ export {
643
+ nuvio
644
+ };
package/package.json ADDED
@@ -0,0 +1,63 @@
1
+ {
2
+ "name": "@nuvio/vite-plugin",
3
+ "version": "0.1.0",
4
+ "description": "Nuvio Vite plugin: dev WebSocket, source index for data-nuvio-id, secure patch writes.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/ehah/Nuvio.git",
9
+ "directory": "packages/vite-plugin"
10
+ },
11
+ "keywords": [
12
+ "nuvio",
13
+ "vite",
14
+ "vite-plugin",
15
+ "devtools",
16
+ "react"
17
+ ],
18
+ "publishConfig": {
19
+ "access": "public"
20
+ },
21
+ "files": [
22
+ "dist",
23
+ "README.md"
24
+ ],
25
+ "type": "module",
26
+ "main": "./dist/index.js",
27
+ "types": "./dist/index.d.ts",
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/index.d.ts",
31
+ "import": "./dist/index.js"
32
+ }
33
+ },
34
+ "engines": {
35
+ "node": ">=20"
36
+ },
37
+ "peerDependencies": {
38
+ "vite": "^5.4.0 || ^6.0.0"
39
+ },
40
+ "dependencies": {
41
+ "@babel/parser": "^7.26.9",
42
+ "@babel/traverse": "^7.26.9",
43
+ "fast-glob": "^3.3.3",
44
+ "ws": "^8.18.0",
45
+ "@nuvio/ast-engine": "0.1.0",
46
+ "@nuvio/shared": "0.1.0"
47
+ },
48
+ "devDependencies": {
49
+ "@babel/types": "^7.26.9",
50
+ "@types/babel__traverse": "^7.20.7",
51
+ "@types/node": "^22.13.5",
52
+ "@types/ws": "^8.5.14",
53
+ "tsup": "^8.4.0",
54
+ "typescript": "^5.7.3",
55
+ "vite": "^6.1.0",
56
+ "vitest": "^3.0.6"
57
+ },
58
+ "scripts": {
59
+ "build": "tsup src/index.ts --format esm --dts --clean --external vite --external @nuvio/shared --external @nuvio/ast-engine",
60
+ "typecheck": "tsc -p tsconfig.json --noEmit",
61
+ "test": "vitest run"
62
+ }
63
+ }