@ape-egg/vibe 1.8.0 → 1.9.1

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/runtime/parse.js CHANGED
@@ -6,8 +6,69 @@ import {
6
6
  CONDITIONAL_REGEX,
7
7
  DOM_ELEMENT_PROPERTIES,
8
8
  DEHYDRATE_CLASS_OR_ATTR,
9
+ THIS_PROP_REGEX,
9
10
  } from './constants.js';
10
11
 
12
+ // Walks up the DOM for the nearest component wrapper tagged by component.js.
13
+ // Used to rewrite `this.property` in event handlers to the component's state path.
14
+ const findComponentIdForElement = (element) => {
15
+ if (!element?.closest) return null;
16
+ const wrapper = element.closest('[data-vibe-component-id]');
17
+ return wrapper ? wrapper.getAttribute('data-vibe-component-id') : null;
18
+ };
19
+
20
+ // Single source of truth for reading attribute/name bindings off an element.
21
+ // Called from both the root handler and recursive() so they can't drift. Any
22
+ // element classified as a fetched component (`<component src>` or
23
+ // `<div class="component" src>`) returns nulls — its attributes are props
24
+ // owned by processComponent and must stay raw; hydrating them would coerce
25
+ // objects to "[object Object]" or strip boolean-like attrs to empty.
26
+ const captureAttributeBindings = (element) => {
27
+ const nodeName = element.nodeName;
28
+ const isFetchedComponent =
29
+ (nodeName === 'COMPONENT' || (nodeName === 'DIV' && element.classList?.contains('component'))) &&
30
+ element.hasAttribute?.('src');
31
+
32
+ if (isFetchedComponent || !element.attributes || element.attributes.length === 0) {
33
+ return { attributes: null, nameBindings: null };
34
+ }
35
+
36
+ const attributes = {};
37
+ const nameBindings = [];
38
+
39
+ for (let j = 0; j < element.attributes.length; j++) {
40
+ const attr = element.attributes[j];
41
+ BINDING_REGEX.lastIndex = 0;
42
+
43
+ // Attribute name itself contains a binding (e.g. <icon @[section.icon]>).
44
+ if (BINDING_REGEX.test(attr.name)) {
45
+ nameBindings.push(attr.name);
46
+ continue;
47
+ }
48
+
49
+ // Rewrite `this.property` inside event handlers to the component's state path.
50
+ if (attr.name.startsWith('on') && attr.value.includes('this.')) {
51
+ const componentId = findComponentIdForElement(element);
52
+ if (componentId) {
53
+ const rewritten = attr.value.replace(THIS_PROP_REGEX, (match, prop) => {
54
+ return DOM_ELEMENT_PROPERTIES.has(prop) ? match : `$['${componentId}'].${prop}`;
55
+ });
56
+ element.setAttribute(attr.name, rewritten);
57
+ }
58
+ }
59
+
60
+ BINDING_REGEX.lastIndex = 0;
61
+ if (BINDING_REGEX.test(attr.value)) {
62
+ attributes[attr.name] = attr.value;
63
+ }
64
+ }
65
+
66
+ return {
67
+ attributes: Object.keys(attributes).length > 0 ? attributes : null,
68
+ nameBindings: nameBindings.length > 0 ? nameBindings : null,
69
+ };
70
+ };
71
+
11
72
  const parseHTML = (children, rootKey = undefined) =>
12
73
  children.reduce((s, element, i) => {
13
74
  const { nodeName, textContent } = element;
@@ -196,59 +257,7 @@ const recursive = (children, rootKey = undefined, skipIndices = new Set(), stats
196
257
  const elementForBindings = isTextNode ? element.parentElement : element;
197
258
  const textNodeRef = isTextNode ? element : null; // Store reference to actual text node
198
259
 
199
- // Check for attribute bindings
200
- const attributes = {};
201
- const nameBindings = [];
202
-
203
- // Skip hydrating attributes on fetched components - they need to be passed raw
204
- const isFetchedComponent =
205
- (nodeName === 'COMPONENT' || (nodeName === 'DIV' && element.classList?.contains('component'))) &&
206
- element.hasAttribute('src');
207
-
208
- if (element.attributes && !isFetchedComponent) {
209
- for (let j = 0; j < element.attributes.length; j++) {
210
- const attr = element.attributes[j];
211
- // Reset lastIndex before test - BINDING_REGEX has 'g' flag which persists state
212
- BINDING_REGEX.lastIndex = 0;
213
-
214
- // Check if attribute name contains binding (e.g., @[section.icon])
215
- if (BINDING_REGEX.test(attr.name)) {
216
- nameBindings.push(attr.name);
217
- continue; // Don't process as regular attribute
218
- }
219
-
220
- // Rewrite event handlers with this. to use component state
221
- if (attr.name.startsWith('on') && attr.value.includes('this.')) {
222
- const componentId = findComponentIdForElement(element);
223
- if (componentId) {
224
- // Rewrite this.property to $['componentId'].property, but skip DOM properties
225
- const rewritten = attr.value.replace(/\bthis\.(\w+)/g, (match, prop) => {
226
- return DOM_ELEMENT_PROPERTIES.has(prop) ? match : `$['${componentId}'].${prop}`;
227
- });
228
- element.setAttribute(attr.name, rewritten);
229
- }
230
- }
231
-
232
- // Check if attribute value contains binding
233
- BINDING_REGEX.lastIndex = 0;
234
- if (BINDING_REGEX.test(attr.value)) {
235
- attributes[attr.name] = attr.value;
236
- }
237
- }
238
- }
239
-
240
- // Helper to find component ID for an element
241
- // Looks for nearest ancestor with data-vibe-component-id
242
- function findComponentIdForElement(element) {
243
- if (!element) return null;
244
-
245
- // Find nearest component wrapper (tagged by component.js)
246
- const wrapper = element.closest('[data-vibe-component-id]');
247
- return wrapper ? wrapper.getAttribute('data-vibe-component-id') : null;
248
- }
249
- const hasAttributeBindings = Object.keys(attributes).length > 0;
250
- const hasNameBindings = nameBindings.length > 0;
251
-
260
+ const { attributes, nameBindings } = captureAttributeBindings(element);
252
261
  const hasChildren = childNodes.length;
253
262
 
254
263
  if (hasChildren) {
@@ -259,8 +268,8 @@ const recursive = (children, rootKey = undefined, skipIndices = new Set(), stats
259
268
  parsed,
260
269
  element: elementForBindings,
261
270
  children: recursive(iteratableChildren, undefined, new Set(), stats),
262
- ...(hasAttributeBindings && { attributes }),
263
- ...(hasNameBindings && { nameBindings }),
271
+ ...(attributes && { attributes }),
272
+ ...(nameBindings && { nameBindings }),
264
273
  ...(textNodeRef && { textNode: textNodeRef }),
265
274
  };
266
275
  } else {
@@ -268,8 +277,8 @@ const recursive = (children, rootKey = undefined, skipIndices = new Set(), stats
268
277
  parsed: innerHTML || textContent,
269
278
  element: elementForBindings,
270
279
  children: {},
271
- ...(hasAttributeBindings && { attributes }),
272
- ...(hasNameBindings && { nameBindings }),
280
+ ...(attributes && { attributes }),
281
+ ...(nameBindings && { nameBindings }),
273
282
  ...(textNodeRef && { textNode: textNodeRef }),
274
283
  };
275
284
  }
@@ -282,29 +291,7 @@ export default (root, rootKey = undefined) => {
282
291
  const { childNodes } = root;
283
292
  const stats = { skipped: 0 };
284
293
 
285
- // Check for attribute bindings on the root element itself (only if element has attributes)
286
- let attributes = null;
287
- let nameBindings = null;
288
- if (root.attributes && root.attributes.length > 0) {
289
- for (let j = 0; j < root.attributes.length; j++) {
290
- const attr = root.attributes[j];
291
- BINDING_REGEX.lastIndex = 0;
292
-
293
- // Check if attribute name contains binding
294
- if (BINDING_REGEX.test(attr.name)) {
295
- if (!nameBindings) nameBindings = [];
296
- nameBindings.push(attr.name);
297
- continue;
298
- }
299
-
300
- // Check if attribute value contains binding
301
- BINDING_REGEX.lastIndex = 0;
302
- if (BINDING_REGEX.test(attr.value)) {
303
- if (!attributes) attributes = {};
304
- attributes[attr.name] = attr.value;
305
- }
306
- }
307
- }
294
+ const { attributes, nameBindings } = captureAttributeBindings(root);
308
295
 
309
296
  return {
310
297
  // html: root.outerHTML,
@@ -134,6 +134,14 @@ const detectHyperspeed = async () => {
134
134
  if (hyperspeedDetectionAttempted) return hyperspeedData;
135
135
  hyperspeedDetectionAttempted = true;
136
136
 
137
+ // Runtime-mode pages still have [vibe-fouc] / .vibe-fouc on their vibe root
138
+ // at this point — the compiler strips it at build time, and the runtime only
139
+ // clears it after hydration (PHASE_READY). Vibe can latch to any element, so
140
+ // search the whole document. If any fouc marker is still here, we're in
141
+ // runtime mode and no hyperspeed manifest will exist — skip the network
142
+ // fetches and avoid the 404 devtools noise.
143
+ const skipNetwork = !!document.querySelector("[vibe-fouc], .vibe-fouc");
144
+
137
145
  try {
138
146
  let pagePath = window.location.pathname;
139
147
 
@@ -185,21 +193,38 @@ const detectHyperspeed = async () => {
185
193
  );
186
194
  }
187
195
 
188
- // Try each possible path
189
- for (const manifestPath of possiblePaths) {
190
- try {
191
- const module = await import(manifestPath);
192
- hyperspeedData = {
193
- manifest: module.default,
194
- path: manifestPath,
195
- };
196
- return hyperspeedData;
197
- } catch (e) {
198
- // Try next path
199
- continue;
196
+ if (!skipNetwork) {
197
+ // Fully-runtime dynamic import. Hidden behind `new Function` so any
198
+ // bundler's static-analysis can't read into it — there's nothing we
199
+ // could or should tell it about these manifest paths, which are decided
200
+ // at runtime by searching a list.
201
+ const dynamicImport = new Function('p', 'return import(p)');
202
+ // Try each possible path
203
+ for (const manifestPath of possiblePaths) {
204
+ try {
205
+ const module = await dynamicImport(manifestPath);
206
+ hyperspeedData = {
207
+ manifest: module.default,
208
+ path: manifestPath,
209
+ };
210
+ return hyperspeedData;
211
+ } catch (e) {
212
+ // Try next path
213
+ continue;
214
+ }
200
215
  }
201
216
  }
202
217
 
218
+ // When skipping network, yield a macrotask so module-graph timing matches
219
+ // the old behavior where `await import()` on a missing manifest resolved
220
+ // via a network 404 (macrotask), not a microtask. Without this yield, the
221
+ // vibe module-graph resolves too fast and the post-boot microtask fires
222
+ // before sibling `<script type="module">` tags (e.g. component scripts)
223
+ // have had a chance to register their state.
224
+ if (skipNetwork) {
225
+ await new Promise((resolve) => setTimeout(resolve, 0));
226
+ }
227
+
203
228
  // No manifest found
204
229
  return null;
205
230
  } catch {
@@ -468,7 +493,7 @@ export const restoreMarkersFromManifest = (
468
493
  if (text.startsWith("if")) {
469
494
  if (!startComment) {
470
495
  const expression = childTree.meta?.expression;
471
- const expectedText = expression ? 'if ' + expression : null;
496
+ const expectedText = expression ? "if " + expression : null;
472
497
  if (expectedText && text === expectedText) {
473
498
  startComment = comment;
474
499
  conditionalDepth = 1;