@sigil-dev/grimoire 0.9.25 → 0.9.27

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.
@@ -1,202 +1,229 @@
1
- export const HMR_CLIENT_SOURCE = `
2
- (function() {
3
- let version = 0;
4
-
5
- const moduleUrl = (entry) =>
6
- '/__grimoire__/m/' + entry.modUrl + '?v=' + entry.version;
7
-
8
- /**
9
- * Apply one server batch. Route and layout modules are re-imported at
10
- * their new versions; the module the browser fetches carries version
11
- * stamps on its own imports, so an edited component two levels down comes
12
- * back fresh instead of out of the module cache.
13
- */
14
- async function applyBatch(payloads) {
15
- const css = [];
16
- const routes = [];
17
- const layouts = [];
18
- let invalidate = false;
19
-
20
- for (const p of payloads) {
21
- if (p.kind === 'reload') { location.reload(); return; }
22
- if (p.kind === 'css') css.push(p);
23
- if (p.kind === 'routes') routes.push(...p.entries);
24
- if (p.kind === 'layouts') layouts.push(...p.entries);
25
- if (p.kind === 'invalidate') invalidate = true;
26
- }
27
-
28
- for (const p of css) applyCss(p.hash, p.text);
29
-
30
- const hmr = window.__grimoire_hmr__;
31
- if (!hmr) { location.reload(); return; }
32
-
33
- const current = window.__grimoire_current_pattern__;
34
- captureSignals();
35
- try {
36
- // layouts wrap every page: always needed, so import eagerly
37
- for (const entry of layouts) {
38
- const mod = await import(moduleUrl(entry));
39
- if (!mod.default) throw new Error('layout ' + entry.path + ' has no default export');
40
- hmr.setLayout(entry.path, mod.default);
41
- }
42
-
43
- let touchesCurrent = layouts.length > 0;
44
- for (const entry of routes) {
45
- if (entry.pattern === current) {
46
- const mod = await import(moduleUrl(entry));
47
- if (!mod.default) throw new Error('route ' + entry.pattern + ' has no default export');
48
- hmr.setRoute(entry.pattern, mod.default);
49
- touchesCurrent = true;
50
- } else {
51
- // not on screen — re-register lazily so the next
52
- // navigation picks up the new version
53
- const url = moduleUrl(entry);
54
- hmr.setRoute(entry.pattern, { __lazy: () => import(url) });
55
- }
56
- }
57
-
58
- // a changed load()/action means the rendered data is stale too:
59
- // refetch instead of re-rendering against the old payload
60
- if (invalidate) await refetchCurrent();
61
- else if (touchesCurrent) await hmr.rerender();
62
- } catch (e) {
63
- console.error('[sigil hmr] swap failed, reloading:', e);
64
- location.reload();
65
- } finally {
66
- clearCapture();
67
- }
68
- }
69
-
70
- async function refetchCurrent() {
71
- if (window.__grimoire_navigate__) {
72
- await window.__grimoire_navigate__(location.pathname, true);
73
- } else {
74
- location.reload();
75
- }
76
- }
77
-
78
- function applyCss(hash, text) {
79
- let el = document.getElementById('sigil-' + hash);
80
- if (!el) {
81
- el = document.createElement('style');
82
- el.id = 'sigil-' + hash;
83
- document.head.appendChild(el);
84
- }
85
- el.textContent = text;
86
- }
87
-
88
- const __hmrRegistry__ = new Map(); // key -> signal getter fn
89
-
90
- window.__hmrAdopt__ = function(key, initial) {
91
- if (!window.__hmrCapture__) return initial;
92
- if (!window.__hmrCapture__.has(key)) return initial;
93
- const stored = window.__hmrCapture__.get(key);
94
- // shape guard — only adopt if same type and array-ness
95
- if (typeof stored !== typeof initial) return initial;
96
- if (Array.isArray(stored) !== Array.isArray(initial)) return initial;
97
- return stored;
98
- };
99
-
100
- window.__hmrRegister__ = function(key, signal) {
101
- __hmrRegistry__.set(key, signal);
102
- };
103
-
104
- function captureSignals() {
105
- window.__hmrCapture__ = new Map();
106
- for (const [key, signal] of __hmrRegistry__) {
107
- try { window.__hmrCapture__.set(key, signal()); } catch {}
108
- }
109
- }
110
-
111
- function clearCapture() {
112
- window.__hmrCapture__ = null;
113
- }
114
-
115
- function connect() {
116
- const ws = new WebSocket(
117
- (location.protocol === 'https:' ? 'wss' : 'ws') +
118
- '://' + location.host + '/__grimoire__/hmr'
119
- );
120
-
121
- ws.onopen = () => {
122
- console.log('[sigil hmr] connected');
123
- document.getElementById('__grimoire_overlay__')?.remove();
124
- };
125
-
126
- ws.onmessage = async (ev) => {
127
- const msg = JSON.parse(ev.data);
128
- if (msg.type === 'error') { showOverlay(msg.message, msg.loc); return; }
129
- if (msg.v !== undefined && msg.v <= version) return;
130
- if (msg.v !== undefined) version = msg.v;
131
-
132
- if (msg.type === 'batch') {
133
- document.getElementById('__grimoire_overlay__')?.remove();
134
- await applyBatch(msg.payloads);
135
- }
136
- };
137
-
138
- ws.onclose = () => {
139
- console.log('[sigil hmr] disconnected, reconnecting...');
140
- const retry = setInterval(async () => {
141
- try {
142
- await fetch('/', { method: 'HEAD' });
143
- clearInterval(retry);
144
- location.reload();
145
- } catch {}
146
- }, 300);
147
- };
148
- }
149
-
150
- function stripAnsi(str) {
151
- return str.replace(/\u001b[[0-9;]*m/g, '');
152
- }
153
-
154
- function unescapeHtml(str) {
155
- let result = str;
156
- // run twice to handle double-escaped entities
157
- for (let i = 0; i < 2; i++) {
158
- result = result
159
- .replace(/&amp;/g, '&')
160
- .replace(/&lt;/g, '<')
161
- .replace(/&gt;/g, '>')
162
- .replace(/&quot;/g, '"')
163
- .replace(/&#39;/g, "'");
164
- }
165
- return result;
166
- }
167
-
168
- function showOverlay(message, loc) {
169
- document.getElementById('__grimoire_overlay__')?.remove();
170
- const clean = unescapeHtml(stripAnsi(message));
171
- const d = document.createElement('div');
172
- d.id = '__grimoire_overlay__';
173
- d.style.cssText = [
174
- 'position:fixed;inset:0;z-index:99999',
175
- 'background:rgba(15,15,20,.94)',
176
- 'color:#ff8a8a',
177
- 'font:13px/1.6 monospace',
178
- 'padding:40px',
179
- 'overflow:auto',
180
- 'white-space:pre-wrap',
181
- ].join(';');
182
-
183
- d.textContent = '[sigil] compile error\\n\\n' + clean;
184
-
185
- if (loc) {
186
- const link = document.createElement('a');
187
- link.href = '/__grimoire__/open?file=' + encodeURIComponent(loc.file) +
188
- '&line=' + loc.line + '&col=' + loc.col;
189
- link.style.cssText = 'color:#88aaff;text-decoration:underline;cursor:pointer;display:block;margin:8px 0 16px';
190
- link.textContent = loc.file + ':' + loc.line + ':' + loc.col;
191
- link.onclick = (e) => { e.preventDefault(); fetch(link.href); };
192
- d.appendChild(link);
193
- }
194
-
195
- d.title = 'Click anywhere to dismiss';
196
- d.onclick = (ev) => { if (ev.target === d) d.remove(); };
197
- document.body.appendChild(d);
198
- }
199
-
200
- connect();
201
- })();
202
- `;
1
+ export const HMR_CLIENT_SOURCE = `
2
+ (function() {
3
+ let version = 0;
4
+
5
+ // The router turns off the browser's scroll restoration, so a full reload
6
+ // would land at the top. Stash the offset and put it back after the reload.
7
+ const SCROLL_KEY = '__sigil_hmr_scroll__';
8
+
9
+ function reload() {
10
+ try {
11
+ sessionStorage.setItem(SCROLL_KEY, JSON.stringify({
12
+ path: location.pathname + location.search,
13
+ y: window.scrollY,
14
+ }));
15
+ } catch {}
16
+ location.reload();
17
+ }
18
+
19
+ (function restoreScroll() {
20
+ let saved = null;
21
+ try {
22
+ saved = JSON.parse(sessionStorage.getItem(SCROLL_KEY) || 'null');
23
+ sessionStorage.removeItem(SCROLL_KEY);
24
+ } catch {}
25
+ if (!saved || saved.path !== location.pathname + location.search) return;
26
+ const apply = () => window.scrollTo(0, saved.y);
27
+ apply();
28
+ requestAnimationFrame(apply);
29
+ window.addEventListener('load', apply, { once: true });
30
+ })();
31
+
32
+ const moduleUrl = (entry) =>
33
+ '/__grimoire__/m/' + entry.modUrl + '?v=' + entry.version;
34
+
35
+ /**
36
+ * Apply one server batch. Route and layout modules are re-imported at
37
+ * their new versions; the module the browser fetches carries version
38
+ * stamps on its own imports, so an edited component two levels down comes
39
+ * back fresh instead of out of the module cache.
40
+ */
41
+ async function applyBatch(payloads) {
42
+ const css = [];
43
+ const routes = [];
44
+ const layouts = [];
45
+ let invalidate = false;
46
+
47
+ for (const p of payloads) {
48
+ if (p.kind === 'reload') { reload(); return; }
49
+ if (p.kind === 'css') css.push(p);
50
+ if (p.kind === 'routes') routes.push(...p.entries);
51
+ if (p.kind === 'layouts') layouts.push(...p.entries);
52
+ if (p.kind === 'invalidate') invalidate = true;
53
+ }
54
+
55
+ for (const p of css) applyCss(p.hash, p.text);
56
+
57
+ const hmr = window.__grimoire_hmr__;
58
+ if (!hmr) { reload(); return; }
59
+
60
+ const current = window.__grimoire_current_pattern__;
61
+ captureSignals();
62
+ try {
63
+ // layouts wrap every page: always needed, so import eagerly
64
+ for (const entry of layouts) {
65
+ const mod = await import(moduleUrl(entry));
66
+ if (!mod.default) throw new Error('layout ' + entry.path + ' has no default export');
67
+ hmr.setLayout(entry.path, mod.default);
68
+ }
69
+
70
+ let touchesCurrent = layouts.length > 0;
71
+ for (const entry of routes) {
72
+ if (entry.pattern === current) {
73
+ const mod = await import(moduleUrl(entry));
74
+ if (!mod.default) throw new Error('route ' + entry.pattern + ' has no default export');
75
+ hmr.setRoute(entry.pattern, mod.default);
76
+ touchesCurrent = true;
77
+ } else {
78
+ // not on screen — re-register lazily so the next
79
+ // navigation picks up the new version
80
+ const url = moduleUrl(entry);
81
+ hmr.setRoute(entry.pattern, { __lazy: () => import(url) });
82
+ }
83
+ }
84
+
85
+ // a changed load()/action means the rendered data is stale too:
86
+ // refetch instead of re-rendering against the old payload
87
+ if (invalidate) await refetchCurrent();
88
+ else if (touchesCurrent) await hmr.rerender();
89
+ } catch (e) {
90
+ console.error('[sigil hmr] swap failed, reloading:', e);
91
+ reload();
92
+ } finally {
93
+ clearCapture();
94
+ }
95
+ }
96
+
97
+ async function refetchCurrent() {
98
+ if (window.__grimoire_navigate__) {
99
+ await window.__grimoire_navigate__(location.pathname, true);
100
+ } else {
101
+ reload();
102
+ }
103
+ }
104
+
105
+ function applyCss(hash, text) {
106
+ let el = document.getElementById('sigil-' + hash);
107
+ if (!el) {
108
+ el = document.createElement('style');
109
+ el.id = 'sigil-' + hash;
110
+ document.head.appendChild(el);
111
+ }
112
+ el.textContent = text;
113
+ }
114
+
115
+ const __hmrRegistry__ = new Map(); // key -> signal getter fn
116
+
117
+ window.__hmrAdopt__ = function(key, initial) {
118
+ if (!window.__hmrCapture__) return initial;
119
+ if (!window.__hmrCapture__.has(key)) return initial;
120
+ const stored = window.__hmrCapture__.get(key);
121
+ // shape guard — only adopt if same type and array-ness
122
+ if (typeof stored !== typeof initial) return initial;
123
+ if (Array.isArray(stored) !== Array.isArray(initial)) return initial;
124
+ return stored;
125
+ };
126
+
127
+ window.__hmrRegister__ = function(key, signal) {
128
+ __hmrRegistry__.set(key, signal);
129
+ };
130
+
131
+ function captureSignals() {
132
+ window.__hmrCapture__ = new Map();
133
+ for (const [key, signal] of __hmrRegistry__) {
134
+ try { window.__hmrCapture__.set(key, signal()); } catch {}
135
+ }
136
+ }
137
+
138
+ function clearCapture() {
139
+ window.__hmrCapture__ = null;
140
+ }
141
+
142
+ function connect() {
143
+ const ws = new WebSocket(
144
+ (location.protocol === 'https:' ? 'wss' : 'ws') +
145
+ '://' + location.host + '/__grimoire__/hmr'
146
+ );
147
+
148
+ ws.onopen = () => {
149
+ console.log('[sigil hmr] connected');
150
+ document.getElementById('__grimoire_overlay__')?.remove();
151
+ };
152
+
153
+ ws.onmessage = async (ev) => {
154
+ const msg = JSON.parse(ev.data);
155
+ if (msg.type === 'error') { showOverlay(msg.message, msg.loc); return; }
156
+ if (msg.v !== undefined && msg.v <= version) return;
157
+ if (msg.v !== undefined) version = msg.v;
158
+
159
+ if (msg.type === 'batch') {
160
+ document.getElementById('__grimoire_overlay__')?.remove();
161
+ await applyBatch(msg.payloads);
162
+ }
163
+ };
164
+
165
+ ws.onclose = () => {
166
+ console.log('[sigil hmr] disconnected, reconnecting...');
167
+ const retry = setInterval(async () => {
168
+ try {
169
+ await fetch('/', { method: 'HEAD' });
170
+ clearInterval(retry);
171
+ reload();
172
+ } catch {}
173
+ }, 300);
174
+ };
175
+ }
176
+
177
+ function stripAnsi(str) {
178
+ return str.replace(/\u001b[[0-9;]*m/g, '');
179
+ }
180
+
181
+ function unescapeHtml(str) {
182
+ let result = str;
183
+ // run twice to handle double-escaped entities
184
+ for (let i = 0; i < 2; i++) {
185
+ result = result
186
+ .replace(/&amp;/g, '&')
187
+ .replace(/&lt;/g, '<')
188
+ .replace(/&gt;/g, '>')
189
+ .replace(/&quot;/g, '"')
190
+ .replace(/&#39;/g, "'");
191
+ }
192
+ return result;
193
+ }
194
+
195
+ function showOverlay(message, loc) {
196
+ document.getElementById('__grimoire_overlay__')?.remove();
197
+ const clean = unescapeHtml(stripAnsi(message));
198
+ const d = document.createElement('div');
199
+ d.id = '__grimoire_overlay__';
200
+ d.style.cssText = [
201
+ 'position:fixed;inset:0;z-index:99999',
202
+ 'background:rgba(15,15,20,.94)',
203
+ 'color:#ff8a8a',
204
+ 'font:13px/1.6 monospace',
205
+ 'padding:40px',
206
+ 'overflow:auto',
207
+ 'white-space:pre-wrap',
208
+ ].join(';');
209
+
210
+ d.textContent = '[sigil] compile error\\n\\n' + clean;
211
+
212
+ if (loc) {
213
+ const link = document.createElement('a');
214
+ link.href = '/__grimoire__/open?file=' + encodeURIComponent(loc.file) +
215
+ '&line=' + loc.line + '&col=' + loc.col;
216
+ link.style.cssText = 'color:#88aaff;text-decoration:underline;cursor:pointer;display:block;margin:8px 0 16px';
217
+ link.textContent = loc.file + ':' + loc.line + ':' + loc.col;
218
+ link.onclick = (e) => { e.preventDefault(); fetch(link.href); };
219
+ d.appendChild(link);
220
+ }
221
+
222
+ d.title = 'Click anywhere to dismiss';
223
+ d.onclick = (ev) => { if (ev.target === d) d.remove(); };
224
+ document.body.appendChild(d);
225
+ }
226
+
227
+ connect();
228
+ })();
229
+ `;
@@ -167,7 +167,12 @@ export async function handleChange(
167
167
  // the edit may have added imports — pick them up before propagating
168
168
  await crawlFrom([filePath], { graph, projectRoot, aliases: ctx.aliases });
169
169
 
170
- const isClient = !isServerOnly(filePath);
170
+ // error pages render on the server only: compiling one for the browser can
171
+ // fail on code that never ships there, and a failure would throw the edit
172
+ // away before the SSR loader ever saw the new version
173
+ const reaches = graph.affectedRoutes(key);
174
+ const isClient =
175
+ !isServerOnly(filePath) && reaches.some((r) => r.type !== "error");
171
176
  let css: { hash: string; text: string } | null = null;
172
177
  let compiled: string | null = null;
173
178
 
@@ -206,7 +211,7 @@ export async function handleChange(
206
211
  );
207
212
  }
208
213
 
209
- const affected = graph.affectedRoutes(key);
214
+ const affected = reaches;
210
215
  if (affected.length === 0) {
211
216
  logger.info("no route reaches this module, reloading:", filePath);
212
217
  await fullReload(ctx);