@runic-artifex/vite-plugin-runic 0.12.0 → 0.13.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 CHANGED
@@ -27,7 +27,7 @@ or later 24.x, or Node 26.
27
27
  same as omitting the option: the development client is injected while serving,
28
28
  and the Runic dock appears when `DevTools()` is registered. `true` also requires
29
29
  `DevTools()`: serving without it fails with
30
- [`RUNICP007`](https://github.com/Runic-Artifex/runic-sdk/blob/v0.12.0/docs/diagnostics.md#runicp007).
30
+ [`RUNICP007`](https://github.com/Runic-Artifex/runic-sdk/blob/v0.13.0/docs/diagnostics.md#runicp007).
31
31
  `false` turns off both the dock and the development client.
32
32
  `maxTimelineEntries` sets how many timeline entries the dock keeps: 200 by
33
33
  default, rounded down and limited to 1 to 500.
@@ -53,6 +53,19 @@ The plugin adds `@runic-artifex/vite-plugin-runic/client` to
53
53
  client: with a cold `node_modules/.vite` cache, the first page would otherwise
54
54
  discover it, and Vite would reload the page and close the host's connection.
55
55
 
56
+ The development client also warns about a text field that loses typed
57
+ characters: when script sets the focused `<input>` or `<textarea>` to a value
58
+ it had before the user's last edit while a Bridge request is in flight, which
59
+ happens when a field is bound with a command per key. It reports a
60
+ `stale-input` Views diagnostic, shown on the timeline and passed to
61
+ `onBridgeDiagnostic` listeners, and logs a console warning, once per field.
62
+ The warning names the field by its `id` or `name`, never its value. Bind text
63
+ fields with the text-field binding of your framework package
64
+ (`injectTextField` in `@runic-artifex/angular`, `useTextField` in
65
+ `@runic-artifex/react`, `vue` or `svelte`) or a setter. Turn the warning off with
66
+ `runic({ staleInputWarning: false })`, or from the page by setting
67
+ `globalThis[Symbol.for("runic.vite.staleInputWarning")] = false`.
68
+
56
69
  Under `dotnet runic dev`, the Vite process gets a random value for the session
57
70
  in `RUNIC_APPLICATION_DEV_SESSION`, and `/__runic/state` answers with it in the
58
71
  `X-Runic-Dev-Session` header. Since 0.11, `dev` treats the server as ready
package/dist/client.js CHANGED
@@ -1,7 +1,9 @@
1
1
  // The development client that the plugin injects into served pages. It forwards the
2
- // diagnostics and connection state of `@runic-artifex/views` to the DevTools dock. It has
3
- // no exports: applications do not import it.
2
+ // diagnostics and connection state of `@runic-artifex/views` to the DevTools dock and warns
3
+ // about script that overwrites a focused text field with an older value (`stale-input`). It
4
+ // has no exports: applications do not import it.
4
5
  import { sanitizeDiagnosticSummary } from "./diagnostics.js";
6
+ import { installStaleInputWarning } from "./stale-input.js";
5
7
  const hot = import.meta.hot;
6
8
  const diagnosticEvent = "runic:diagnostic";
7
9
  const connectionEvent = "runic:connection";
@@ -20,6 +22,8 @@ function fallbackType(code) {
20
22
  return "Error";
21
23
  if (code === "uncertain")
22
24
  return "BridgeOperationUncertainError";
25
+ if (code === "stale-input")
26
+ return "StaleInputWarning";
23
27
  return "BridgeError";
24
28
  }
25
29
  /** Forwards a Views runtime diagnostic to the DevTools timeline. */
@@ -84,3 +88,7 @@ function connectViewsConnection() {
84
88
  }
85
89
  connectViewsDiagnostics();
86
90
  connectViewsConnection();
91
+ // Development only: without Vite's HMR context (a production build that imports the client)
92
+ // nothing is installed. Installs once per page; HMR re-evaluation leaves it in place.
93
+ if (hot)
94
+ installStaleInputWarning(globalThis);
package/dist/index.d.ts CHANGED
@@ -23,6 +23,12 @@ export interface RunicViteOptions {
23
23
  */
24
24
  readonly devtools?: boolean | "auto";
25
25
  readonly maxTimelineEntries?: number;
26
+ /**
27
+ * `false` turns off the development client's `stale-input` warning: script that sets a
28
+ * focused text field to a value from before the user's last edit while a Bridge request
29
+ * is in flight. Defaults to `true`.
30
+ */
31
+ readonly staleInputWarning?: boolean;
26
32
  /** Injects the Runic Desktop bootstrap without taking ownership of Vite or HMR. */
27
33
  readonly desktop?: boolean | Readonly<{
28
34
  /** Absolute development bootstrap URL; production uses the surface-relative default. */
package/dist/index.js CHANGED
@@ -7,6 +7,10 @@ export { runicDevSession, runicDevSessionProxy } from "./dev-session.js";
7
7
  const virtualClientId = "virtual:runic/client";
8
8
  const resolvedVirtualClientId = `\0${virtualClientId}`;
9
9
  const clientPackageId = "@runic-artifex/vite-plugin-runic/client";
10
+ // Turns the client's `stale-input` warning off. A separate module, because the import of the
11
+ // client is hoisted above any statement in the virtual client module.
12
+ const staleInputOffId = "virtual:runic/stale-input-off";
13
+ const resolvedStaleInputOffId = `\0${staleInputOffId}`;
10
14
  const stateEvent = "runic:state";
11
15
  const diagnosticEvent = "runic:diagnostic";
12
16
  const connectionEvent = "runic:connection";
@@ -15,6 +19,9 @@ const defaultTimelineLimit = 200;
15
19
  const maximumTimelineLimit = 500;
16
20
  export function runic(options = {}) {
17
21
  const maxTimelineEntries = timelineLimit(options.maxTimelineEntries);
22
+ if (options.staleInputWarning !== undefined && typeof options.staleInputWarning !== "boolean") {
23
+ throw new TypeError("staleInputWarning must be true or false.");
24
+ }
18
25
  let server;
19
26
  let sharedState;
20
27
  let jsonRenderer;
@@ -146,12 +153,20 @@ export function runic(options = {}) {
146
153
  });
147
154
  },
148
155
  resolveId(id) {
149
- return id === virtualClientId ? resolvedVirtualClientId : undefined;
156
+ if (id === virtualClientId)
157
+ return resolvedVirtualClientId;
158
+ return id === staleInputOffId ? resolvedStaleInputOffId : undefined;
150
159
  },
151
160
  load(id) {
161
+ if (id === resolvedStaleInputOffId) {
162
+ return `globalThis[Symbol.for("runic.vite.staleInputWarning")] = false;`;
163
+ }
152
164
  if (id !== resolvedVirtualClientId)
153
165
  return undefined;
154
- return `import ${JSON.stringify(clientPackageId)};`;
166
+ // Imports evaluate in order, so the flag is set before the client installs the warning.
167
+ return options.staleInputWarning === false
168
+ ? `import ${JSON.stringify(staleInputOffId)};\nimport ${JSON.stringify(clientPackageId)};`
169
+ : `import ${JSON.stringify(clientPackageId)};`;
155
170
  },
156
171
  devtools: {
157
172
  async setup(context) {
@@ -0,0 +1,19 @@
1
+ /** Set to `false` on `globalThis` to turn the warning off, before or after this module loads. */
2
+ export declare const staleInputWarningKey: unique symbol;
3
+ /**
4
+ * A typing burst ends on blur or after this long without an `input` event. One second
5
+ * covers a normal Bridge round trip while the user keeps typing, and a script write
6
+ * after a pause is no longer a race with the user's keystrokes.
7
+ */
8
+ export declare const burstQuietPeriodMs = 1000;
9
+ export declare const staleInputMessage: string;
10
+ export interface StaleInputOptions {
11
+ /** The clock, in milliseconds; tests replace it. */
12
+ readonly now?: () => number;
13
+ }
14
+ /**
15
+ * Installs the warning on `host` (normally `globalThis`) once. Does nothing without a DOM,
16
+ * when it is already installed, or when `host[staleInputWarningKey]` is `false`.
17
+ * Returns whether this call installed it.
18
+ */
19
+ export declare function installStaleInputWarning(host: object, options?: StaleInputOptions): boolean;
@@ -0,0 +1,201 @@
1
+ // The `stale-input` development warning (views-protocol-4 design, section 2.4 item 5).
2
+ //
3
+ // A text field bound with a command per key can lose typed characters: the user types
4
+ // "ab", the command for "a" is still in flight, and the framework writes the model's older
5
+ // "a" back into the focused field. Frameworks (React, the Angular renderer, Vue, Svelte)
6
+ // write through the `value` property, so wrapping the `value` setters of
7
+ // `HTMLInputElement` and `HTMLTextAreaElement` sees every such write.
8
+ //
9
+ // The warning fires when script sets `.value` on the focused field to a value that
10
+ // - differs from the field's current value and from the user's latest value, and
11
+ // - the field had earlier in the user's current typing burst,
12
+ // while a Bridge request is in flight. A value equal to an earlier burst value counts as
13
+ // stale even when it looks like a normalization (the user typed "ab " after "ab", and
14
+ // script sets "ab"): the check compares values, not intent.
15
+ //
16
+ // The warning never carries the typed value, which may be a secret: only the element's
17
+ // tag and its id or name.
18
+ /** Set to `false` on `globalThis` to turn the warning off, before or after this module loads. */
19
+ export const staleInputWarningKey = Symbol.for("runic.vite.staleInputWarning");
20
+ // The installed state, shared by every evaluation of this module (HMR, duplicate copies),
21
+ // so the setters and the Bridge are wrapped once per page.
22
+ const installedKey = Symbol.for("runic.vite.staleInput");
23
+ const viewsDiagnosticsKey = Symbol.for("runic.views.diagnostics");
24
+ /**
25
+ * A typing burst ends on blur or after this long without an `input` event. One second
26
+ * covers a normal Bridge round trip while the user keeps typing, and a script write
27
+ * after a pause is no longer a race with the user's keystrokes.
28
+ */
29
+ export const burstQuietPeriodMs = 1_000;
30
+ // Bounds the values remembered per burst; older values are dropped first.
31
+ const maximumBurstValues = 64;
32
+ const maximumNameLength = 40;
33
+ export const staleInputMessage = "to a value it had before the user's last edit while a Bridge request was in flight, which loses " +
34
+ "typed characters. Bind text inputs with the text-field binding of your framework package " +
35
+ "(`injectTextField` in @runic-artifex/angular, `useTextField` in @runic-artifex/react, vue or svelte) " +
36
+ "or a setter instead of a command per key. This warning comes from @runic-artifex/vite-plugin-runic " +
37
+ "in development; turn it off with runic({ staleInputWarning: false }).";
38
+ /**
39
+ * Installs the warning on `host` (normally `globalThis`) once. Does nothing without a DOM,
40
+ * when it is already installed, or when `host[staleInputWarningKey]` is `false`.
41
+ * Returns whether this call installed it.
42
+ */
43
+ export function installStaleInputWarning(host, options = {}) {
44
+ const scope = host;
45
+ if (scope[installedKey] !== undefined || scope[staleInputWarningKey] === false)
46
+ return false;
47
+ const inputClass = scope.HTMLInputElement;
48
+ const textAreaClass = scope.HTMLTextAreaElement;
49
+ const document = scope.document;
50
+ if (typeof inputClass !== "function" || typeof textAreaClass !== "function" ||
51
+ typeof document?.addEventListener !== "function")
52
+ return false;
53
+ const now = options.now ?? (() => Date.now());
54
+ const bursts = new WeakMap();
55
+ const warned = new WeakSet();
56
+ // "In flight" counts the Bridge's `request` promises from call until they settle.
57
+ let inFlight = 0;
58
+ let wrappedBridge;
59
+ const wrappers = new WeakSet();
60
+ const unwrappable = new WeakSet();
61
+ // The host script, or a mock bridge, may install `__runicBridge` after this client runs
62
+ // or replace it later, so the Bridge is (re)wrapped lazily: on every user edit, before
63
+ // the application handles it, and on every value write.
64
+ const wrapBridge = () => {
65
+ const bridge = scope.__runicBridge;
66
+ if (typeof bridge !== "object" || bridge === null || unwrappable.has(bridge))
67
+ return;
68
+ const request = bridge.request;
69
+ if (typeof request !== "function")
70
+ return;
71
+ if (bridge === wrappedBridge && wrappers.has(request))
72
+ return;
73
+ if (wrappers.has(request)) {
74
+ wrappedBridge = bridge;
75
+ return;
76
+ }
77
+ const original = request;
78
+ const wrapper = function (...args) {
79
+ inFlight += 1;
80
+ let result;
81
+ try {
82
+ result = original.apply(this, args);
83
+ }
84
+ catch (error) {
85
+ inFlight -= 1;
86
+ throw error;
87
+ }
88
+ const settled = () => { inFlight -= 1; };
89
+ // The caller keeps the original promise; only this observer waits for it.
90
+ Promise.resolve(result).then(settled, settled);
91
+ return result;
92
+ };
93
+ wrappers.add(wrapper);
94
+ try {
95
+ bridge.request = wrapper;
96
+ }
97
+ catch { /* not writable */ }
98
+ if (bridge.request === wrapper)
99
+ wrappedBridge = bridge;
100
+ else
101
+ unwrappable.add(bridge);
102
+ };
103
+ const isField = (target) => target instanceof inputClass || target instanceof textAreaClass;
104
+ const record = (target, value) => {
105
+ const time = now();
106
+ let burst = bursts.get(target);
107
+ if (!burst || time - burst.lastInput > burstQuietPeriodMs) {
108
+ burst = { values: new Set(), latest: undefined, lastInput: time };
109
+ bursts.set(target, burst);
110
+ }
111
+ burst.values.delete(value);
112
+ burst.values.add(value);
113
+ if (burst.values.size > maximumBurstValues) {
114
+ const oldest = burst.values.values().next();
115
+ if (!oldest.done)
116
+ burst.values.delete(oldest.value);
117
+ }
118
+ burst.lastInput = time;
119
+ };
120
+ // `beforeinput` records the value before the user's edit, so overwriting the first
121
+ // typed character with the value from before it counts too.
122
+ document.addEventListener("beforeinput", (event) => {
123
+ wrapBridge();
124
+ const target = event.target;
125
+ if (isField(target))
126
+ record(target, String(target.value ?? ""));
127
+ }, true);
128
+ document.addEventListener("input", (event) => {
129
+ wrapBridge();
130
+ const target = event.target;
131
+ if (!isField(target))
132
+ return;
133
+ const value = String(target.value ?? "");
134
+ record(target, value);
135
+ const burst = bursts.get(target);
136
+ if (burst)
137
+ burst.latest = value;
138
+ }, true);
139
+ document.addEventListener("focusout", (event) => {
140
+ if (typeof event.target === "object" && event.target !== null)
141
+ bursts.delete(event.target);
142
+ }, true);
143
+ const check = (element, current, next) => {
144
+ if (scope[staleInputWarningKey] === false || inFlight <= 0 || warned.has(element))
145
+ return;
146
+ if (document.activeElement !== element || next === current)
147
+ return;
148
+ const burst = bursts.get(element);
149
+ if (!burst || burst.latest === undefined || now() - burst.lastInput > burstQuietPeriodMs)
150
+ return;
151
+ if (next === burst.latest || !burst.values.has(next))
152
+ return;
153
+ warned.add(element);
154
+ report(scope, element);
155
+ };
156
+ for (const prototype of [inputClass.prototype, textAreaClass.prototype]) {
157
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, "value");
158
+ const { get, set } = descriptor ?? {};
159
+ if (!descriptor || !get || !set || !descriptor.configurable)
160
+ continue;
161
+ Object.defineProperty(prototype, "value", {
162
+ ...descriptor,
163
+ get,
164
+ set(value) {
165
+ try {
166
+ wrapBridge();
167
+ // The setters treat null as the empty string.
168
+ check(this, String(get.call(this)), value === null ? "" : String(value));
169
+ }
170
+ catch { /* the warning never breaks a write */ }
171
+ set.call(this, value);
172
+ },
173
+ });
174
+ }
175
+ scope[installedKey] = true;
176
+ return true;
177
+ }
178
+ function describe(element) {
179
+ const field = element;
180
+ const tag = typeof field.tagName === "string" && field.tagName.toLowerCase() === "textarea" ? "textarea" : "input";
181
+ const name = typeof field.getAttribute === "function" ? field.getAttribute("name") : undefined;
182
+ for (const [attribute, value] of [["id", field.id], ["name", name]]) {
183
+ if (typeof value !== "string")
184
+ continue;
185
+ const clean = value.replace(/[^\w.:-]/gu, "").slice(0, maximumNameLength);
186
+ if (clean)
187
+ return `<${tag} ${attribute}="${clean}">`;
188
+ }
189
+ return `<${tag}>`;
190
+ }
191
+ function report(scope, element) {
192
+ const message = `A script set the focused ${describe(element)} ${staleInputMessage}`;
193
+ scope.console?.warn(message);
194
+ const listeners = (scope[viewsDiagnosticsKey] ??= new Set());
195
+ for (const listener of [...listeners]) {
196
+ try {
197
+ listener({ kind: "error", code: "stale-input", message });
198
+ }
199
+ catch { /* a listener's failure does not stop the others */ }
200
+ }
201
+ }
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@runic-artifex/vite-plugin-runic",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "description": "Vite 8 development and DevTools integration for Runic applications",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
- "packageManager": "bun@1.4.2",
7
+ "packageManager": "bun@1.4.4",
8
8
  "files": [
9
9
  "dist",
10
10
  "README.md",
@@ -61,7 +61,7 @@
61
61
  "url": "git+https://github.com/Runic-Artifex/runic-sdk.git",
62
62
  "directory": "packages/web/vite-plugin-runic"
63
63
  },
64
- "homepage": "https://github.com/Runic-Artifex/runic-sdk/tree/v0.12.0/packages/web/vite-plugin-runic#readme",
64
+ "homepage": "https://github.com/Runic-Artifex/runic-sdk/tree/v0.13.0/packages/web/vite-plugin-runic#readme",
65
65
  "bugs": {
66
66
  "url": "https://github.com/Runic-Artifex/runic-sdk/issues"
67
67
  },
@@ -72,5 +72,5 @@
72
72
  "vite-plugin",
73
73
  "devtools"
74
74
  ],
75
- "gitHead": "cb95ea2838ba61c7a24b9cda05bf5f0bd6fcc2d7"
75
+ "gitHead": "3331f81c7a2de34e209b53eb07515323d6d15cf3"
76
76
  }