@runic-artifex/vite-plugin-runic 0.13.0 → 0.15.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/dist/index.js CHANGED
@@ -1,62 +1,81 @@
1
1
  /// <reference types="@vitejs/devtools-kit" />
2
2
  import { isAbsolute, relative } from "node:path";
3
- import { sanitizeDiagnosticSummary } from "./diagnostics.js";
4
3
  import { rewriteHostScripts, webRootPrefix } from "./host-scripts.js";
5
- import { devSessionHeader, devSessionValue, devSessionVariable } from "./dev-session.js";
6
- export { runicDevSession, runicDevSessionProxy } from "./dev-session.js";
4
+ import { clientOptionsKey, connectionEvent, diagnosticEvent, diagnosticsPath, viewEvent } from "./channel.js";
5
+ import { answerClientMessage, answerState, devSessionValue, devSessionVariable, statePath } from "./dev-session.js";
6
+ import { createDevelopmentTimeline, initialDevelopmentState, timelineLimit, withoutFailures } from "./timeline.js";
7
+ export { runicDevSessionProxy } from "./dev-session.js";
7
8
  const virtualClientId = "virtual:runic/client";
8
9
  const resolvedVirtualClientId = `\0${virtualClientId}`;
9
10
  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}`;
11
+ // Sets the client's options (the HMR channel, the `stale-input` warning) on `globalThis`. A separate module, because
12
+ // the import of the client is hoisted above any statement in the virtual client module.
13
+ const clientOptionsId = "virtual:runic/client-options";
14
+ const resolvedClientOptionsId = `\0${clientOptionsId}`;
15
+ // What an import of the client resolves to where it must not run: the build, the server, `devtools: false`.
16
+ const resolvedEmptyClientId = "\0virtual:runic/client-disabled";
14
17
  const stateEvent = "runic:state";
15
- const diagnosticEvent = "runic:diagnostic";
16
- const connectionEvent = "runic:connection";
17
18
  const stateKey = "runic:state";
18
- const defaultTimelineLimit = 200;
19
- const maximumTimelineLimit = 500;
20
19
  export function runic(options = {}) {
21
20
  const maxTimelineEntries = timelineLimit(options.maxTimelineEntries);
22
21
  if (options.staleInputWarning !== undefined && typeof options.staleInputWarning !== "boolean") {
23
22
  throw new TypeError("staleInputWarning must be true or false.");
24
23
  }
24
+ if (options.html !== undefined && typeof options.html !== "boolean") {
25
+ throw new TypeError("html must be true or false.");
26
+ }
27
+ const html = options.html !== false;
28
+ const client = options.devtools !== false;
25
29
  let server;
26
30
  let sharedState;
27
31
  let jsonRenderer;
28
- let state = initialState(options);
29
- let nextDiagnosticSequence = 1;
30
32
  let resolvedRoot = process.cwd();
31
33
  let base = "/";
32
34
  const desktopBootstrapUrl = resolveDesktopBootstrapUrl(options.desktop);
33
- const publish = () => {
35
+ if (!html && desktopBootstrapUrl !== undefined) {
36
+ throw new TypeError("desktop requires html: true: the Desktop bootstrap is a script tag the plugin adds to the HTML.");
37
+ }
38
+ const timeline = createDevelopmentTimeline(initialDevelopmentState(options.contract), maxTimelineEntries, (state) => {
34
39
  sharedState?.mutate((draft) => Object.assign(draft, structuredClone(state)));
35
40
  void jsonRenderer?.updateSpec(createDevtoolsSpec(state));
36
41
  server?.ws.send({ type: "custom", event: stateEvent, data: state });
42
+ });
43
+ const deliver = (event, data) => {
44
+ if (event === connectionEvent)
45
+ timeline.applyConnection(data);
46
+ else if (event === diagnosticEvent)
47
+ timeline.appendDiagnostic(data);
48
+ else if (event === viewEvent)
49
+ timeline.applyView(data);
37
50
  };
38
- const applyConnection = (candidate) => {
39
- const next = connectionState(isRecord(candidate) ? candidate.state : undefined);
40
- if (next === state.connection.state)
41
- return;
42
- state = { ...state, connection: { state: next } };
43
- publish();
44
- };
45
- const appendDiagnostic = (candidate, defaultSource) => {
46
- const summary = sanitizeDiagnosticSummary(candidate, defaultSource);
47
- if (!summary)
48
- return;
49
- const entry = {
50
- ...summary,
51
- id: `diagnostic-${nextDiagnosticSequence}`,
52
- timestamp: new Date().toISOString(),
53
- };
54
- nextDiagnosticSequence += 1;
55
- state = {
56
- ...state,
57
- timeline: [...state.timeline, entry].slice(-maxTimelineEntries),
58
- };
59
- publish();
51
+ const command = () => timeline.state.vite.command;
52
+ const transformIndexHtml = {
53
+ order: "post",
54
+ handler: (document, context) => {
55
+ const prefix = webRootPrefix(context.path);
56
+ const tags = [
57
+ ...(desktopBootstrapUrl === undefined ? [] : [{
58
+ tag: "script",
59
+ attrs: {
60
+ src: command() === "build" || desktopBootstrapUrl === "./runic-desktop.js"
61
+ ? `${prefix}runic-desktop.js`
62
+ : desktopBootstrapUrl,
63
+ },
64
+ injectTo: "head-prepend",
65
+ }]),
66
+ // The development client forwards Views runtime failures to the
67
+ // timeline. It loads before application modules, so a missing Bridge
68
+ // at startup is reported too.
69
+ ...(command() !== "serve" || !client ? [] : [{
70
+ tag: "script",
71
+ attrs: { type: "module", src: `${base}@id/${virtualClientId}` },
72
+ injectTo: "head",
73
+ }]),
74
+ ];
75
+ return command() === "serve"
76
+ ? { html: rewriteHostScripts(document, context.path, false), tags }
77
+ : tags;
78
+ },
60
79
  };
61
80
  return {
62
81
  name: "runic",
@@ -67,7 +86,7 @@ export function runic(options = {}) {
67
86
  // which the dependency scanner cannot see. Pre-bundling it up front
68
87
  // keeps a cold optimizer cache from discovering it on the first page
69
88
  // load and reloading the page, which drops a host's Bridge connection.
70
- return options.devtools === false ? undefined : { optimizeDeps: { include: [clientPackageId] } };
89
+ return client ? { optimizeDeps: { include: [clientPackageId] } } : undefined;
71
90
  }
72
91
  if (desktopBootstrapUrl === undefined)
73
92
  return undefined;
@@ -76,49 +95,25 @@ export function runic(options = {}) {
76
95
  }
77
96
  return { base: "./" };
78
97
  },
79
- // The build parses HTML in a later transform, so host scripts are marked
80
- // vite-ignore here; the dev server has no such pass and uses the hook below.
81
- transform: {
82
- filter: { id: /\.html$/ },
83
- handler(code, id) {
84
- if (state.vite.command !== "build" || !id.endsWith(".html"))
85
- return undefined;
86
- const documentPath = relative(resolvedRoot, id);
87
- if (documentPath.startsWith("..") || isAbsolute(documentPath))
88
- return undefined;
89
- const rewritten = rewriteHostScripts(code, documentPath, true);
90
- return rewritten === code ? undefined : { code: rewritten, map: null };
98
+ // With html: false there is no transformIndexHtml property at all: SvelteKit warns about any plugin that has one.
99
+ ...(html ? {
100
+ // The build parses HTML in a later transform, so host scripts are marked
101
+ // vite-ignore here; the dev server has no such pass and uses the hook below.
102
+ transform: {
103
+ filter: { id: /\.html$/ },
104
+ handler(code, id) {
105
+ if (command() !== "build" || !id.endsWith(".html"))
106
+ return undefined;
107
+ const documentPath = relative(resolvedRoot, id);
108
+ if (documentPath.startsWith("..") || isAbsolute(documentPath))
109
+ return undefined;
110
+ const rewritten = rewriteHostScripts(code, documentPath, true);
111
+ return rewritten === code ? undefined : { code: rewritten, map: null };
112
+ },
91
113
  },
92
- },
93
- transformIndexHtml: {
94
- order: "post",
95
- handler: (html, context) => {
96
- const prefix = webRootPrefix(context.path);
97
- const tags = [
98
- ...(desktopBootstrapUrl === undefined ? [] : [{
99
- tag: "script",
100
- attrs: {
101
- src: state.vite.command === "build" || desktopBootstrapUrl === "./runic-desktop.js"
102
- ? `${prefix}runic-desktop.js`
103
- : desktopBootstrapUrl,
104
- },
105
- injectTo: "head-prepend",
106
- }]),
107
- // The development client forwards Views runtime failures to the
108
- // timeline. It loads before application modules, so a missing Bridge
109
- // at startup is reported too.
110
- ...(state.vite.command !== "serve" || options.devtools === false ? [] : [{
111
- tag: "script",
112
- attrs: { type: "module", src: `${base}@id/${virtualClientId}` },
113
- injectTo: "head",
114
- }]),
115
- ];
116
- return state.vite.command === "serve"
117
- ? { html: rewriteHostScripts(html, context.path, false), tags }
118
- : tags;
119
- },
120
- },
121
- api: { reportDiagnostic: (entry) => appendDiagnostic(entry) },
114
+ transformIndexHtml,
115
+ } : {}),
116
+ api: { reportDiagnostic: (entry) => { timeline.appendDiagnostic(entry); } },
122
117
  configResolved(resolved) {
123
118
  if (resolved.command === "build" && desktopBootstrapUrl !== undefined && resolved.base !== "./") {
124
119
  throw new TypeError("desktop: true requires the resolved Vite base to be './' for relocatable surface output.");
@@ -130,50 +125,59 @@ export function runic(options = {}) {
130
125
  resolvedRoot = resolved.root;
131
126
  const configuredBase = resolved.base || "/";
132
127
  base = configuredBase.endsWith("/") ? configuredBase : `${configuredBase}/`;
133
- state = {
128
+ timeline.configure((state) => ({
134
129
  ...state,
135
130
  vite: { command: resolved.command, mode: resolved.mode, root: resolved.root },
136
- };
131
+ }));
137
132
  },
138
133
  async configureServer(viteServer) {
139
134
  server = viteServer;
140
- viteServer.ws.on(connectionEvent, (payload) => applyConnection(payload));
141
- viteServer.ws.on(diagnosticEvent, (payload) => appendDiagnostic(payload));
135
+ viteServer.ws.on(connectionEvent, (payload) => deliver(connectionEvent, payload));
136
+ viteServer.ws.on(diagnosticEvent, (payload) => deliver(diagnosticEvent, payload));
137
+ viteServer.ws.on(viewEvent, (payload) => deliver(viewEvent, payload));
142
138
  const devSession = devSessionValue(process.env[devSessionVariable]);
143
- viteServer.middlewares.use("/__runic/state", (_request, response) => {
144
- response.statusCode = 200;
145
- response.setHeader("Content-Type", "application/json; charset=utf-8");
146
- response.setHeader("Cache-Control", "no-store");
147
- if (devSession !== undefined)
148
- response.setHeader(devSessionHeader, devSession);
149
- response.end(JSON.stringify(withoutFailures(state)));
139
+ viteServer.middlewares.use(statePath, (_request, response) => {
140
+ answerState(response, timeline.state, devSession);
141
+ });
142
+ // A client that the page loads without the HMR channel posts here (channel.ts).
143
+ viteServer.middlewares.use(diagnosticsPath, (request, response, next) => {
144
+ answerClientMessage(request, response, deliver).catch(next);
150
145
  });
151
146
  viteServer.httpServer?.once("close", () => {
152
147
  server = undefined;
153
148
  });
154
149
  },
155
- resolveId(id) {
156
- if (id === virtualClientId)
157
- return resolvedVirtualClientId;
158
- return id === staleInputOffId ? resolvedStaleInputOffId : undefined;
150
+ resolveId(id, importer, resolveOptions) {
151
+ if (id === virtualClientId || (id === clientPackageId && importer !== resolvedVirtualClientId)) {
152
+ // The client runs only in a served page. An application import of the package goes through the virtual
153
+ // module too, so that it takes this plugin's options and channel, and is empty in the build.
154
+ const served = client && command() === "serve" && resolveOptions?.ssr !== true &&
155
+ this.environment?.config.consumer !== "server";
156
+ return served ? resolvedVirtualClientId : resolvedEmptyClientId;
157
+ }
158
+ return id === clientOptionsId ? resolvedClientOptionsId : undefined;
159
159
  },
160
160
  load(id) {
161
- if (id === resolvedStaleInputOffId) {
162
- return `globalThis[Symbol.for("runic.vite.staleInputWarning")] = false;`;
161
+ if (id === resolvedEmptyClientId)
162
+ return "export {};";
163
+ if (id === resolvedClientOptionsId) {
164
+ const statements = [`globalThis[Symbol.for(${JSON.stringify(clientOptionsKey.description)})] = { channel: "hot" };`];
165
+ if (options.staleInputWarning === false) {
166
+ statements.push(`globalThis[Symbol.for("runic.vite.staleInputWarning")] = false;`);
167
+ }
168
+ return statements.join("\n");
163
169
  }
164
170
  if (id !== resolvedVirtualClientId)
165
171
  return undefined;
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)};`;
172
+ // Imports evaluate in order, so the options are set before the client reads them.
173
+ return `import ${JSON.stringify(clientOptionsId)};\nimport ${JSON.stringify(clientPackageId)};`;
170
174
  },
171
175
  devtools: {
172
176
  async setup(context) {
173
- if (options.devtools === false)
177
+ if (!client)
174
178
  return;
175
- sharedState = await context.rpc.sharedState.get(stateKey, { initialValue: state });
176
- const renderer = context.createJsonRenderer(createDevtoolsSpec(state));
179
+ sharedState = await context.rpc.sharedState.get(stateKey, { initialValue: timeline.state });
180
+ const renderer = context.createJsonRenderer(createDevtoolsSpec(timeline.state));
177
181
  jsonRenderer = renderer;
178
182
  context.docks.register({
179
183
  id: "runic:overview",
@@ -185,7 +189,7 @@ export function runic(options = {}) {
185
189
  context.commands.register({
186
190
  id: "runic:copy-diagnostic-state",
187
191
  title: "Runic: Copy sanitized diagnostic state",
188
- handler: () => JSON.stringify(withoutFailures(state), null, 2),
192
+ handler: () => JSON.stringify(withoutFailures(timeline.state), null, 2),
189
193
  });
190
194
  },
191
195
  },
@@ -211,18 +215,6 @@ function resolveDesktopBootstrapUrl(options) {
211
215
  }
212
216
  return url.href;
213
217
  }
214
- function initialState(options) {
215
- return {
216
- contract: {
217
- identity: cleanString(options.contract?.identity),
218
- version: cleanString(options.contract?.version),
219
- fingerprint: cleanString(options.contract?.fingerprint),
220
- },
221
- vite: { command: "serve", mode: "development", root: "" },
222
- connection: { state: "unknown" },
223
- timeline: [],
224
- };
225
- }
226
218
  function createDevtoolsSpec(current) {
227
219
  const section = (id, title, data) => ({
228
220
  [id]: { type: "Card", props: { title }, children: [`${id}-data`] },
@@ -234,7 +226,7 @@ function createDevtoolsSpec(current) {
234
226
  root: {
235
227
  type: "Stack",
236
228
  props: { direction: "column", gap: 12 },
237
- children: ["heading", "connection", "contract", "failure", "timeline"],
229
+ children: ["heading", "connection", "contract", "views", "superseded", "failure", "timeline"],
238
230
  },
239
231
  heading: { type: "Text", props: { text: "Runic", variant: "heading" } },
240
232
  ...section("connection", "Connection", {
@@ -245,6 +237,8 @@ function createDevtoolsSpec(current) {
245
237
  Version: current.contract.version || "not reported",
246
238
  Fingerprint: current.contract.fingerprint || "not reported",
247
239
  }),
240
+ ...viewsSection(current),
241
+ ...section("superseded", "Superseded commands", supersededCommands(current)),
248
242
  ...section("failure", "Last failure", lastFailure(current)),
249
243
  ...section("timeline", "Recent timeline", current.timeline.length === 0
250
244
  ? { Events: "none" }
@@ -254,14 +248,39 @@ function createDevtoolsSpec(current) {
254
248
  },
255
249
  };
256
250
  }
257
- // Failures keep file paths and stacks for the local dock only. The state
258
- // endpoint and the copied state stay path-free.
259
- function withoutFailures(current) {
251
+ // The state inspector: a card per open View with its state as a tree, the most recently changed first.
252
+ function viewsSection(current) {
253
+ const pages = new Set(current.views.map((view) => view.page));
254
+ const cards = current.views.map((view, index) => {
255
+ const revision = view.revision === undefined ? "" : ` · revision ${view.revision}`;
256
+ const epoch = view.epoch === undefined ? "" : ` · epoch ${view.epoch}`;
257
+ // Several windows can show the same route; the page tells them apart.
258
+ const page = pages.size > 1 ? ` · page ${view.page.slice(0, 6)}` : "";
259
+ return [`views-${index}`, {
260
+ card: { type: "Card", props: { title: `${view.route}${revision}${epoch}${page}` }, children: [`views-${index}-state`] },
261
+ state: { type: "Tree", props: { data: view.state, defaultExpanded: index === 0 } },
262
+ }];
263
+ });
260
264
  return {
261
- ...current,
262
- timeline: current.timeline.map(({ failure: _failure, ...entry }) => entry),
265
+ views: {
266
+ type: "Card",
267
+ props: { title: "Views" },
268
+ children: cards.length === 0 ? ["views-none"] : cards.map(([id]) => id),
269
+ },
270
+ ...(cards.length === 0 ? { "views-none": { type: "Text", props: { text: "No View connected" } } } : {}),
271
+ ...Object.fromEntries(cards.flatMap(([id, { card, state }]) => [[id, card], [`${id}-state`, state]])),
263
272
  };
264
273
  }
274
+ // Command replies the producer answered `superseded` (presentation-epoch/1): the call resolved without running.
275
+ function supersededCommands(current) {
276
+ const entries = current.timeline.filter((entry) => entry.kind === "command" && entry.detail.code === "superseded");
277
+ if (entries.length === 0)
278
+ return { Commands: "none" };
279
+ return Object.fromEntries(entries.slice(-12).reverse().map((entry) => [
280
+ `${entry.id} · ${entry.timestamp}`,
281
+ `${entry.detail.route ?? "?"}.${entry.detail.member ?? "?"} from epoch ${entry.detail.epoch ?? "?"}`,
282
+ ]));
283
+ }
265
284
  function lastFailure(current) {
266
285
  const entry = [...current.timeline].reverse().find((candidate) => candidate.failure !== undefined);
267
286
  if (!entry?.failure)
@@ -274,19 +293,3 @@ function lastFailure(current) {
274
293
  ...(entry.failure.stack ? { Stack: entry.failure.stack } : {}),
275
294
  };
276
295
  }
277
- function connectionState(value) {
278
- return value === "connecting" || value === "connected" || value === "reconnecting" || value === "lost"
279
- ? value
280
- : "unknown";
281
- }
282
- function timelineLimit(value) {
283
- if (typeof value !== "number" || !Number.isFinite(value))
284
- return defaultTimelineLimit;
285
- return Math.min(maximumTimelineLimit, Math.max(1, Math.floor(value)));
286
- }
287
- function cleanString(value) {
288
- return typeof value === "string" ? value.slice(0, 512) : "";
289
- }
290
- function isRecord(value) {
291
- return typeof value === "object" && value !== null && !Array.isArray(value);
292
- }
@@ -34,7 +34,8 @@ export const staleInputMessage = "to a value it had before the user's last edit
34
34
  "typed characters. Bind text inputs with the text-field binding of your framework package " +
35
35
  "(`injectTextField` in @runic-artifex/angular, `useTextField` in @runic-artifex/react, vue or svelte) " +
36
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 }).";
37
+ "in development; turn it off with runic({ staleInputWarning: false }) or, without runic(), by setting " +
38
+ "globalThis[Symbol.for(\"runic.vite.staleInputWarning\")] = false.";
38
39
  /**
39
40
  * Installs the warning on `host` (normally `globalThis`) once. Does nothing without a DOM,
40
41
  * when it is already installed, or when `host[staleInputWarningKey]` is `false`.
@@ -0,0 +1,70 @@
1
+ import type { RunicDiagnosticDetail, RunicDiagnosticEntry, RunicDiagnosticFailure, RunicDiagnosticSource, RunicViewStateValue } from "./diagnostics.js";
2
+ export interface RunicDevelopmentState {
3
+ readonly contract: Readonly<{
4
+ identity: string;
5
+ version: string;
6
+ fingerprint: string;
7
+ }>;
8
+ readonly vite: Readonly<{
9
+ command: string;
10
+ mode: string;
11
+ root: string;
12
+ }>;
13
+ /**
14
+ * The page's connection to its .NET host, as `@runic-artifex/views` reports it
15
+ * (`BridgeConnectionState`), or `unknown` until a View connects.
16
+ */
17
+ readonly connection: Readonly<{
18
+ state: "connecting" | "connected" | "reconnecting" | "lost" | "closed" | "unknown";
19
+ }>;
20
+ /**
21
+ * The state inspector: each open View's current state, as the development client last reported it, the most
22
+ * recently changed first. Command replies that the producer answered `superseded` are timeline entries
23
+ * (`kind: "command"`, `detail.code: "superseded"`).
24
+ */
25
+ readonly views: readonly RunicViewSnapshot[];
26
+ readonly timeline: readonly RunicTimelineEntry[];
27
+ }
28
+ /** One View in the state inspector. */
29
+ export interface RunicViewSnapshot {
30
+ /** The page the View is open in: a random identifier per page load, as several windows share one server. */
31
+ readonly page: string;
32
+ /** The View's route, such as `editor`. */
33
+ readonly route: string;
34
+ /** The revision of `state`, and its presentation epoch on a connection with `presentation-epoch/1`. */
35
+ readonly revision?: number;
36
+ readonly epoch?: number;
37
+ /** How many presentations of the page show the route. */
38
+ readonly presentations: number;
39
+ readonly updatedAt: string;
40
+ /** The state the page shows, bounded and redacted like timeline details. */
41
+ readonly state: RunicViewStateValue;
42
+ }
43
+ export type RunicTimelineEntry = Readonly<Required<Pick<RunicDiagnosticEntry, "id" | "timestamp" | "kind" | "label">> & {
44
+ source?: RunicDiagnosticSource;
45
+ detail: RunicDiagnosticDetail;
46
+ failure?: RunicDiagnosticFailure;
47
+ }>;
48
+ export interface DevelopmentTimeline {
49
+ readonly state: RunicDevelopmentState;
50
+ /** Replaces the state without notifying, for configuration such as the resolved Vite command. */
51
+ configure(update: (current: RunicDevelopmentState) => RunicDevelopmentState): void;
52
+ /** Sanitizes and appends an entry; returns it, or `undefined` for a candidate that is not a diagnostic. */
53
+ appendDiagnostic(candidate: unknown, defaultSource?: RunicDiagnosticSource): RunicTimelineEntry | undefined;
54
+ /** Applies a `{ state }` connection report; returns whether the state changed. */
55
+ applyConnection(candidate: unknown): boolean;
56
+ /**
57
+ * Applies a state inspector report: `{ page, route, revision?, epoch?, presentations, state }` for a View's state,
58
+ * `{ page, route, closed: true }` for a closed View, `{ page, closed: true }` for a page that went away. Returns
59
+ * whether the report was valid.
60
+ */
61
+ applyView(candidate: unknown): boolean;
62
+ }
63
+ export declare function createDevelopmentTimeline(initial: RunicDevelopmentState, maxTimelineEntries: number, changed: (state: RunicDevelopmentState) => void): DevelopmentTimeline;
64
+ export declare function initialDevelopmentState(contract: Readonly<{
65
+ identity?: string;
66
+ version?: string;
67
+ fingerprint?: string;
68
+ }> | undefined, vite?: RunicDevelopmentState["vite"]): RunicDevelopmentState;
69
+ export declare function withoutFailures(current: RunicDevelopmentState): RunicDevelopmentState;
70
+ export declare function timelineLimit(value: number | undefined): number;
@@ -0,0 +1,112 @@
1
+ import { sanitizeDiagnosticSummary, sanitizeViewState } from "./diagnostics.js";
2
+ const defaultTimelineLimit = 200;
3
+ const maximumTimelineLimit = 500;
4
+ // The state inspector keeps the Views that changed most recently, over every page of the server.
5
+ const maximumInspectedViews = 32;
6
+ export function createDevelopmentTimeline(initial, maxTimelineEntries, changed) {
7
+ let state = initial;
8
+ let nextSequence = 1;
9
+ return {
10
+ get state() { return state; },
11
+ configure(update) { state = update(state); },
12
+ appendDiagnostic(candidate, defaultSource) {
13
+ const summary = sanitizeDiagnosticSummary(candidate, defaultSource);
14
+ if (!summary)
15
+ return undefined;
16
+ const entry = {
17
+ ...summary,
18
+ id: `diagnostic-${nextSequence}`,
19
+ timestamp: new Date().toISOString(),
20
+ };
21
+ nextSequence += 1;
22
+ state = { ...state, timeline: [...state.timeline, entry].slice(-maxTimelineEntries) };
23
+ changed(state);
24
+ return entry;
25
+ },
26
+ applyConnection(candidate) {
27
+ const next = connectionState(isRecord(candidate) ? candidate.state : undefined);
28
+ if (next === state.connection.state)
29
+ return false;
30
+ state = { ...state, connection: { state: next } };
31
+ changed(state);
32
+ return true;
33
+ },
34
+ applyView(candidate) {
35
+ if (!isRecord(candidate) || typeof candidate.page !== "string" || !pagePattern.test(candidate.page))
36
+ return false;
37
+ const page = candidate.page;
38
+ const route = typeof candidate.route === "string" && routePattern.test(candidate.route) ? candidate.route : undefined;
39
+ // An invalid route never stands for the whole page.
40
+ if (candidate.route !== undefined && route === undefined)
41
+ return false;
42
+ if (candidate.closed === true) {
43
+ const views = state.views.filter((view) => view.page !== page || (route !== undefined && view.route !== route));
44
+ if (views.length !== state.views.length) {
45
+ state = { ...state, views };
46
+ changed(state);
47
+ }
48
+ return true;
49
+ }
50
+ if (route === undefined || !Object.hasOwn(candidate, "state"))
51
+ return false;
52
+ const revision = counter(candidate.revision);
53
+ const epoch = counter(candidate.epoch);
54
+ const snapshot = {
55
+ page,
56
+ route,
57
+ ...(revision === undefined ? {} : { revision }),
58
+ ...(epoch === undefined ? {} : { epoch }),
59
+ presentations: counter(candidate.presentations) ?? 0,
60
+ updatedAt: new Date().toISOString(),
61
+ state: sanitizeViewState(candidate.state),
62
+ };
63
+ const others = state.views.filter((view) => view.page !== page || view.route !== route);
64
+ state = { ...state, views: [snapshot, ...others].slice(0, maximumInspectedViews) };
65
+ changed(state);
66
+ return true;
67
+ },
68
+ };
69
+ }
70
+ // The development client's page identifier, and a route name (specs/application, "Route names").
71
+ const pagePattern = /^[a-z0-9]{1,32}$/u;
72
+ const routePattern = /^[A-Za-z0-9_.-]{1,128}$/u;
73
+ function counter(value) {
74
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
75
+ }
76
+ export function initialDevelopmentState(contract, vite = { command: "serve", mode: "development", root: "" }) {
77
+ return {
78
+ contract: {
79
+ identity: cleanString(contract?.identity),
80
+ version: cleanString(contract?.version),
81
+ fingerprint: cleanString(contract?.fingerprint),
82
+ },
83
+ vite,
84
+ connection: { state: "unknown" },
85
+ views: [],
86
+ timeline: [],
87
+ };
88
+ }
89
+ // Failures keep file paths and stacks for local display only (the dock, the development server's terminal). The
90
+ // state endpoint and the copied state stay path-free.
91
+ export function withoutFailures(current) {
92
+ return {
93
+ ...current,
94
+ timeline: current.timeline.map(({ failure: _failure, ...entry }) => entry),
95
+ };
96
+ }
97
+ export function timelineLimit(value) {
98
+ if (typeof value !== "number" || !Number.isFinite(value))
99
+ return defaultTimelineLimit;
100
+ return Math.min(maximumTimelineLimit, Math.max(1, Math.floor(value)));
101
+ }
102
+ function connectionState(value) {
103
+ return value === "connecting" || value === "connected" || value === "reconnecting" || value === "lost" || value === "closed"
104
+ ? value
105
+ : "unknown";
106
+ }
107
+ function cleanString(value) {
108
+ return typeof value === "string" ? value.slice(0, 512) : "";
109
+ }
110
+ function isRecord(value) {
111
+ return typeof value === "object" && value !== null && !Array.isArray(value);
112
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runic-artifex/vite-plugin-runic",
3
- "version": "0.13.0",
3
+ "version": "0.15.0",
4
4
  "description": "Vite 8 development and DevTools integration for Runic applications",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -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.13.0/packages/web/vite-plugin-runic#readme",
64
+ "homepage": "https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.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": "3331f81c7a2de34e209b53eb07515323d6d15cf3"
75
+ "gitHead": "c94bda07cf363bad056eda86ae77c514b66e61dd"
76
76
  }