@stacksjs/stx 0.2.784 → 0.2.787

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.
Files changed (209) hide show
  1. package/dist/{chunk-1165h1nv.js → chunk-0jp3tt5c.js} +1 -1
  2. package/dist/{chunk-cfpw4c6b.js → chunk-0r61tkfe.js} +2 -2
  3. package/dist/chunk-0s25gyy5.js +2 -0
  4. package/dist/{chunk-m4mpyq3d.js → chunk-14ft0zc7.js} +3 -3
  5. package/dist/chunk-1brkqd5f.js +2 -0
  6. package/dist/chunk-1pdaqca9.js +2 -0
  7. package/dist/{chunk-9tec9eap.js → chunk-1y9ez7nz.js} +2 -2
  8. package/dist/{chunk-k0aejzg9.js → chunk-2p4yad7w.js} +4 -4
  9. package/dist/chunk-2scyqqt3.js +2 -0
  10. package/dist/{chunk-x5a7sm43.js → chunk-2v75eyf8.js} +1 -1
  11. package/dist/chunk-2vxh8b8g.js +2 -0
  12. package/dist/chunk-33na85q2.js +2 -0
  13. package/dist/{chunk-qby3e5nm.js → chunk-3gn1t0pa.js} +29 -29
  14. package/dist/chunk-3n03m9w0.js +2 -0
  15. package/dist/chunk-3t4t655h.js +2 -0
  16. package/dist/{chunk-p9gkz451.js → chunk-40ambk0h.js} +4 -4
  17. package/dist/chunk-43ynckvh.js +2 -0
  18. package/dist/chunk-44bm0pty.js +2 -0
  19. package/dist/chunk-498286bb.js +2 -0
  20. package/dist/{chunk-e1gxykm8.js → chunk-4s5q1aea.js} +4 -4
  21. package/dist/chunk-4v22nj67.js +2 -0
  22. package/dist/chunk-549zk2p7.js +2 -0
  23. package/dist/{chunk-ra8f8sm2.js → chunk-59tbk9qj.js} +4 -4
  24. package/dist/{chunk-w9d18r1t.js → chunk-5a92srn2.js} +1 -1
  25. package/dist/{chunk-cz8mka1b.js → chunk-5j619xgb.js} +2 -2
  26. package/dist/chunk-5pgv8jh1.js +2 -0
  27. package/dist/chunk-699t603m.js +2 -0
  28. package/dist/chunk-6f6xqzhb.js +2 -0
  29. package/dist/{chunk-r1jzbqr3.js → chunk-6v4b0xc1.js} +5 -5
  30. package/dist/{chunk-ww636tcm.js → chunk-6w935vyf.js} +2 -2
  31. package/dist/{chunk-bgc2fm73.js → chunk-74rf78w8.js} +2 -2
  32. package/dist/chunk-76ngpa25.js +2 -0
  33. package/dist/{chunk-h5tjm191.js → chunk-7gvaz6ye.js} +3 -3
  34. package/dist/{chunk-et1vz3wd.js → chunk-7pk3t82j.js} +2 -2
  35. package/dist/{chunk-skn2n8jt.js → chunk-7wkz9sz5.js} +6 -6
  36. package/dist/chunk-8pphy0p1.js +2 -0
  37. package/dist/{chunk-8rn1m9d1.js → chunk-8w54jyt7.js} +2 -2
  38. package/dist/{chunk-5r1rdpeg.js → chunk-8ycz8ss9.js} +5 -5
  39. package/dist/{chunk-bq9xf8nq.js → chunk-94gyfwpz.js} +8 -8
  40. package/dist/{chunk-dqpqc5ps.js → chunk-992nsr70.js} +2 -2
  41. package/dist/chunk-9th217rf.js +2 -0
  42. package/dist/{chunk-y5f04xtb.js → chunk-9tqa8xvf.js} +2 -2
  43. package/dist/chunk-9wmjmas8.js +2 -0
  44. package/dist/{chunk-x8anspa5.js → chunk-agtvdtx4.js} +2 -2
  45. package/dist/{chunk-yzs2afn7.js → chunk-b4r7d6me.js} +3 -3
  46. package/dist/chunk-bgybw1k5.js +2 -0
  47. package/dist/chunk-bm7xr4xh.js +3 -0
  48. package/dist/{chunk-4wc5pc19.js → chunk-bwcj9z19.js} +2 -2
  49. package/dist/chunk-cagvn9tf.js +2 -0
  50. package/dist/chunk-cdsv4yrv.js +2 -0
  51. package/dist/chunk-cg5ar6y0.js +2 -0
  52. package/dist/{chunk-10az8e1m.js → chunk-d3pemcp8.js} +5 -5
  53. package/dist/chunk-d5e47gr4.js +2 -0
  54. package/dist/chunk-d910ytt2.js +2 -0
  55. package/dist/chunk-d9p7xaj7.js +2 -0
  56. package/dist/{chunk-y38swh5t.js → chunk-dhqp3z4w.js} +2 -2
  57. package/dist/chunk-dtc8expv.js +2 -0
  58. package/dist/{chunk-kf8hzvb7.js → chunk-e3wmnjz8.js} +3 -3
  59. package/dist/{chunk-7v0psycp.js → chunk-e44zheax.js} +3 -3
  60. package/dist/chunk-ebbzq4va.js +2 -0
  61. package/dist/chunk-eeqr09wt.js +2 -0
  62. package/dist/{chunk-z2m9p8xe.js → chunk-es006emk.js} +2 -2
  63. package/dist/chunk-fkkdt6sj.js +2 -0
  64. package/dist/chunk-fxy0cq7h.js +2 -0
  65. package/dist/chunk-g6smtcc0.js +2 -0
  66. package/dist/{chunk-9f6qx8b9.js → chunk-gb65t4n1.js} +2 -2
  67. package/dist/{chunk-sckd8v0d.js → chunk-gj5hjak1.js} +1 -1
  68. package/dist/{chunk-eapt899m.js → chunk-gv3bfkdm.js} +5 -5
  69. package/dist/{chunk-ady8cnpb.js → chunk-h0c6jtrj.js} +4 -4
  70. package/dist/{chunk-zxfptbac.js → chunk-h0jnatd4.js} +2 -2
  71. package/dist/{chunk-3q807nyz.js → chunk-h1cep4w8.js} +3 -3
  72. package/dist/{chunk-wphv66vs.js → chunk-hc8htggj.js} +4 -4
  73. package/dist/{chunk-k86mzdbd.js → chunk-hf2h0shz.js} +3 -3
  74. package/dist/{chunk-rn9m8bmc.js → chunk-hqmgvan6.js} +2 -2
  75. package/dist/{chunk-v4a9dv4h.js → chunk-hzmhh3k5.js} +1 -1
  76. package/dist/chunk-k7w05cjv.js +2 -0
  77. package/dist/{chunk-20afyff6.js → chunk-kce6pzmj.js} +2 -2
  78. package/dist/chunk-kk8vqwe4.js +2 -0
  79. package/dist/chunk-kn38mjpp.js +2 -0
  80. package/dist/{chunk-qbtb9pwe.js → chunk-kq1zc10a.js} +2 -2
  81. package/dist/chunk-kvmpc0sg.js +2 -0
  82. package/dist/chunk-memz2xdn.js +2 -0
  83. package/dist/{chunk-nw355jn6.js → chunk-mqr61kqn.js} +2 -2
  84. package/dist/chunk-n2cq11e3.js +2 -0
  85. package/dist/{chunk-xzb6gaq4.js → chunk-n70gbh4y.js} +9 -9
  86. package/dist/chunk-nf2bzqaw.js +2 -0
  87. package/dist/{chunk-ert36h3v.js → chunk-npfs1zyn.js} +3 -3
  88. package/dist/{chunk-n70ry0hg.js → chunk-nrnkqqmb.js} +5 -5
  89. package/dist/{chunk-wx6h1xs3.js → chunk-nzj7mkvm.js} +72 -72
  90. package/dist/{chunk-e22v0ad2.js → chunk-p0f5vygc.js} +5 -5
  91. package/dist/{chunk-9ct3gbyv.js → chunk-pa9zfbh6.js} +6 -6
  92. package/dist/{chunk-j2qv5ra2.js → chunk-q14d714d.js} +2 -2
  93. package/dist/chunk-qf86f6c5.js +2 -0
  94. package/dist/{chunk-tyjzye2d.js → chunk-qp3xd98j.js} +1 -1
  95. package/dist/chunk-qrnws56v.js +2 -0
  96. package/dist/{chunk-fs0nrg7g.js → chunk-qsqha895.js} +16 -16
  97. package/dist/{chunk-he85ksa7.js → chunk-qv85c3qy.js} +1 -1
  98. package/dist/{chunk-rtam1h61.js → chunk-qvc6d3ka.js} +4 -4
  99. package/dist/chunk-qzb0v08n.js +2 -0
  100. package/dist/{chunk-2303xycv.js → chunk-rkpd5pqc.js} +5 -5
  101. package/dist/chunk-rnaeezmp.js +2 -0
  102. package/dist/{chunk-gbx5vw81.js → chunk-rrb9m2q2.js} +5 -5
  103. package/dist/{chunk-j288z01t.js → chunk-rwbcxzw2.js} +2 -2
  104. package/dist/chunk-s18ecm80.js +2 -0
  105. package/dist/chunk-s1wdzttg.js +2 -0
  106. package/dist/{chunk-mcxk1ajm.js → chunk-t0kh3ev1.js} +5 -5
  107. package/dist/chunk-t2hscbrh.js +2 -0
  108. package/dist/chunk-tbnyx5d2.js +2 -0
  109. package/dist/chunk-th5afzmv.js +2 -0
  110. package/dist/chunk-tktkj2dc.js +2 -0
  111. package/dist/{chunk-5mng4x26.js → chunk-tnkxww7b.js} +5 -5
  112. package/dist/{chunk-td3qp5my.js → chunk-tnn0br4w.js} +3 -3
  113. package/dist/{chunk-qfcn4btf.js → chunk-v1z6n7wz.js} +1 -1
  114. package/dist/{chunk-p8185yw2.js → chunk-v6z3ak8h.js} +1 -1
  115. package/dist/{chunk-vct6dec8.js → chunk-v8rfeev5.js} +2 -2
  116. package/dist/{chunk-5hy66mfn.js → chunk-vgtbds23.js} +13 -13
  117. package/dist/chunk-vgzfsh1z.js +2 -0
  118. package/dist/{chunk-416jy1m5.js → chunk-vkn133cs.js} +2 -2
  119. package/dist/{chunk-bc91m8x8.js → chunk-vr6jccpy.js} +3 -3
  120. package/dist/{chunk-sxwgq49z.js → chunk-vrbcdds3.js} +1 -1
  121. package/dist/{chunk-wj78td69.js → chunk-w5hhqjwr.js} +1 -1
  122. package/dist/{chunk-p3t400qx.js → chunk-w6emseps.js} +5 -5
  123. package/dist/{chunk-x8js27hd.js → chunk-w9nwb8r3.js} +6 -6
  124. package/dist/chunk-wdqgf1hh.js +2 -0
  125. package/dist/chunk-wqjdzdaj.js +2 -0
  126. package/dist/chunk-wr3adhd8.js +2 -0
  127. package/dist/{chunk-64gbacyk.js → chunk-wrd3aygb.js} +1 -1
  128. package/dist/chunk-x8pehmac.js +2 -0
  129. package/dist/{chunk-wfefjm2x.js → chunk-ymb0h1b9.js} +4 -4
  130. package/dist/chunk-zdwnzq78.js +2 -0
  131. package/dist/chunk-zyf6737j.js +2 -0
  132. package/dist/cli.js +12 -12
  133. package/dist/craft-entry.js +2 -2
  134. package/dist/craft.js +2 -2
  135. package/dist/expressions.js +2 -2
  136. package/dist/native/bridge/protocol.d.ts +2 -0
  137. package/dist/native/runtime/initial-media-mutations.d.ts +3 -0
  138. package/dist/native/runtime/initial-media-mutations.js +40 -0
  139. package/dist/native/runtime/jsc-globals.js +16 -0
  140. package/dist/native/runtime/native-host.js +56 -8
  141. package/dist/native/runtime/native-media.d.ts +39 -0
  142. package/dist/native/runtime/native-media.js +144 -0
  143. package/dist/native/runtime/shared-screen.js +3 -0
  144. package/dist/native/testing.js +28 -2
  145. package/dist/native/ui.d.ts +24 -0
  146. package/dist/native/ui.js +9 -0
  147. package/dist/pwa.js +3 -3
  148. package/dist/ssg.js +3 -3
  149. package/dist/utils.d.ts +1 -8
  150. package/dist/utils.js +12 -4
  151. package/package.json +5 -5
  152. package/dist/chunk-03zdbm2r.js +0 -2
  153. package/dist/chunk-0d8vq9dz.js +0 -2
  154. package/dist/chunk-16yv309r.js +0 -2
  155. package/dist/chunk-1gt56hdz.js +0 -2
  156. package/dist/chunk-1kxj9mh7.js +0 -2
  157. package/dist/chunk-1p8rbjf9.js +0 -2
  158. package/dist/chunk-2vnhyter.js +0 -2
  159. package/dist/chunk-32s07ych.js +0 -2
  160. package/dist/chunk-47qestfz.js +0 -2
  161. package/dist/chunk-4kx7pw6x.js +0 -2
  162. package/dist/chunk-5rf2j30w.js +0 -2
  163. package/dist/chunk-713az4kg.js +0 -2
  164. package/dist/chunk-7k27y6z1.js +0 -2
  165. package/dist/chunk-7xh512ta.js +0 -2
  166. package/dist/chunk-7y2h7nfd.js +0 -2
  167. package/dist/chunk-7y6ad89y.js +0 -2
  168. package/dist/chunk-8ds59ttd.js +0 -2
  169. package/dist/chunk-8ge4x4yx.js +0 -2
  170. package/dist/chunk-8pyyqev1.js +0 -2
  171. package/dist/chunk-9896204h.js +0 -2
  172. package/dist/chunk-9j4xbeqs.js +0 -2
  173. package/dist/chunk-9qwkyt81.js +0 -2
  174. package/dist/chunk-asbpp9m0.js +0 -2
  175. package/dist/chunk-c91y14ae.js +0 -2
  176. package/dist/chunk-cpq9b0fx.js +0 -2
  177. package/dist/chunk-dxp022r0.js +0 -2
  178. package/dist/chunk-g2gk5qen.js +0 -3
  179. package/dist/chunk-gbgbhpms.js +0 -2
  180. package/dist/chunk-ghn1y4ky.js +0 -2
  181. package/dist/chunk-ghxsmeh8.js +0 -2
  182. package/dist/chunk-gt8n286r.js +0 -2
  183. package/dist/chunk-hp44x2dq.js +0 -2
  184. package/dist/chunk-jqnkcekm.js +0 -2
  185. package/dist/chunk-k9dg3nyy.js +0 -2
  186. package/dist/chunk-kcfvdw3r.js +0 -2
  187. package/dist/chunk-kv9qbqr9.js +0 -2
  188. package/dist/chunk-kzn32p5w.js +0 -2
  189. package/dist/chunk-m90wyzhd.js +0 -2
  190. package/dist/chunk-mcevnfnx.js +0 -2
  191. package/dist/chunk-ne3hamzf.js +0 -2
  192. package/dist/chunk-nx20kccb.js +0 -2
  193. package/dist/chunk-nzec39ym.js +0 -2
  194. package/dist/chunk-p43hw6ef.js +0 -2
  195. package/dist/chunk-pagra8jv.js +0 -2
  196. package/dist/chunk-q71qqjy7.js +0 -2
  197. package/dist/chunk-s2cj9jq6.js +0 -2
  198. package/dist/chunk-s53psb1j.js +0 -2
  199. package/dist/chunk-t482tgm6.js +0 -2
  200. package/dist/chunk-t619ap22.js +0 -2
  201. package/dist/chunk-tshgbpwy.js +0 -2
  202. package/dist/chunk-vasw2fn4.js +0 -2
  203. package/dist/chunk-wm8wz183.js +0 -2
  204. package/dist/chunk-x0e0pcn0.js +0 -2
  205. package/dist/chunk-x756yzrc.js +0 -2
  206. package/dist/chunk-xq2tfg4v.js +0 -2
  207. package/dist/chunk-yrdxvphr.js +0 -2
  208. package/dist/chunk-z9wzmdvp.js +0 -2
  209. package/dist/chunk-zh8w0nb6.js +0 -2
@@ -10,6 +10,7 @@ import { authoredTextEntryProps, projectTextEntry, TEXT_ENTRY_SOURCES, textEntry
10
10
  import { cloneNativeBindingNode } from "./binding-tree.js";
11
11
  import { NATIVE_FORM_ENTRIES } from "./jsc-globals.js";
12
12
  import { createNativeOverlayPresenter } from "./overlay-presenter.js";
13
+ import { prepareInitialMedia } from "./initial-media-mutations.js";
13
14
  import { nativeViewError } from "./view-operations.js";
14
15
  function isHiddenInput(record) {
15
16
  return record.type === "View" && record.props.type === "hidden";
@@ -61,7 +62,17 @@ export const HOST_METHODS = [
61
62
  function followsHref() {}
62
63
  export function createNativeHost(options) {
63
64
  const records = new Map, attributeObservers = new WeakMap, childObservers = new WeakMap, handlers = new Map, eventRegistrations = new WeakMap, componentListeners = new WeakMap, controlsWithDefaultListeners = new WeakSet, implicitSubmitListeners = new WeakMap, formResetCallbacks = new WeakMap;
64
- let queue = [], scheduled = !1, counter = 0, colorScheme = options.colorScheme ?? "light", viewportWidth = Number.isFinite(options.viewportWidth) ? Math.max(0, options.viewportWidth) : 0, stylesheetVariables = createStyleVariables(options.stylesheetTheme?.[colorScheme] ?? []).computed(), disposed = !1;
65
+ let queue = [], mediaFlushTimer, scheduled = !1, counter = 0, colorScheme = options.colorScheme ?? "light", viewportWidth = Number.isFinite(options.viewportWidth) ? Math.max(0, options.viewportWidth) : 0;
66
+ const widthBounds = { min: new Set, max: new Set }, crossesWidthBound = (from, to) => {
67
+ for (const min of widthBounds.min)
68
+ if (from >= min !== to >= min)
69
+ return !0;
70
+ for (const max of widthBounds.max)
71
+ if (from <= max !== to <= max)
72
+ return !0;
73
+ return !1;
74
+ };
75
+ let stylesheetVariables = createStyleVariables(options.stylesheetTheme?.[colorScheme] ?? []).computed(), disposed = !1;
65
76
  const schedule = options.schedule ?? ((flush) => queueMicrotask(flush)), { followLink, linkState } = options, nextId = (prefix) => `${prefix}${++counter}`;
66
77
  function notifyAttributes(node, name) {
67
78
  for (const observer of attributeObservers.get(node) ?? [])
@@ -74,6 +85,10 @@ export function createNativeHost(options) {
74
85
  refreshDividersOf(record);
75
86
  }
76
87
  function refreshDividersOf(record) {
88
+ if (!record.divide && !record.hadDividers)
89
+ return;
90
+ if (record.divide)
91
+ record.hadDividers = !0;
77
92
  let first = !0;
78
93
  for (const child of record.children) {
79
94
  if (child.__stxAnchor !== void 0)
@@ -97,12 +112,21 @@ export function createNativeHost(options) {
97
112
  notify();
98
113
  }
99
114
  function flush() {
115
+ if (mediaFlushTimer !== void 0)
116
+ clearTimeout(mediaFlushTimer);
117
+ mediaFlushTimer = void 0;
100
118
  scheduled = !1;
101
119
  if (queue.length === 0)
102
120
  return;
103
121
  const batch = queue;
104
122
  queue = [];
105
- options.send(batch);
123
+ options.send(prepareInitialMedia(batch));
124
+ }
125
+ function scheduledFlush() {
126
+ if (typeof setTimeout === "function" && typeof clearTimeout === "function" && queue.some((op) => op.op === "createNode" && (op.node.type === "Image" || op.node.type === "Video")))
127
+ mediaFlushTimer = setTimeout(flush, 0);
128
+ else
129
+ flush();
106
130
  }
107
131
  function emit(operation) {
108
132
  if (disposed)
@@ -110,7 +134,7 @@ export function createNativeHost(options) {
110
134
  queue.push(operation);
111
135
  if (!scheduled) {
112
136
  scheduled = !0;
113
- schedule(flush);
137
+ schedule(scheduledFlush);
114
138
  }
115
139
  }
116
140
  function recordOf(node) {
@@ -367,7 +391,13 @@ export function createNativeHost(options) {
367
391
  inherited = parseNativeStyleLayers([source], inherited, report).variables;
368
392
  const resolved = parseNativeStyleLayers([record.styleSource, record.boundStyle, record.forwardedStyle], inherited, report);
369
393
  record.variables = resolved.variables;
370
- const classes = compileClassStyles(`${record.classes} ${record.forwardedClasses ?? ""}`, record.variables, { focus: record.type === "TextInput", focusWithin: !0, rules: options.stylesheetRules, appearance: colorScheme, pointer: options.pointer === !0 }), classStyle = { ...classes.style }, responsive = (classes.responsive ?? []).filter((layer) => viewportWidth >= layer.min && (layer.max === void 0 || viewportWidth <= layer.max));
394
+ const classes = compileClassStyles(`${record.classes} ${record.forwardedClasses ?? ""}`, record.variables, { focus: record.type === "TextInput", focusWithin: !0, rules: options.stylesheetRules, appearance: colorScheme, pointer: options.pointer === !0 }), classStyle = { ...classes.style };
395
+ for (const layer of classes.responsive ?? []) {
396
+ widthBounds.min.add(layer.min);
397
+ if (layer.max !== void 0)
398
+ widthBounds.max.add(layer.max);
399
+ }
400
+ const responsive = (classes.responsive ?? []).filter((layer) => viewportWidth >= layer.min && (layer.max === void 0 || viewportWidth <= layer.max));
371
401
  for (const layer of responsive)
372
402
  Object.assign(classStyle, layer.style);
373
403
  if (colorScheme === "dark") {
@@ -439,6 +469,15 @@ export function createNativeHost(options) {
439
469
  };
440
470
  return find(node);
441
471
  }
472
+ function callerBindingOnWrapper(node, name) {
473
+ if (!isBindingNode(node) || !node.hasAttribute("data-stx-component-wrapper"))
474
+ return !1;
475
+ const bindings = node.getAttribute("data-stx-parent-bindings");
476
+ if (!bindings)
477
+ return !1;
478
+ const flat = (text) => text.replace(/-/g, "").toLowerCase(), wanted = flat(name);
479
+ return bindings.split(/\s+/).some((binding) => binding && flat(binding) === wanted);
480
+ }
442
481
  function applyForwardedStyle(node, name, value) {
443
482
  const record = recordOf(node);
444
483
  if (name === "class" || name === "class-name" || name === "className")
@@ -614,8 +653,10 @@ export function createNativeHost(options) {
614
653
  controlDefaults: { value: descriptor?.props.value ?? "", checked: descriptor?.props.checked ?? descriptor?.props.value ?? !1 },
615
654
  divide: compiledClasses.divide
616
655
  }, ownerRecord = owner ? descriptorOf(owner) : void 0;
617
- if (ownerRecord?.divide && ownerRecord.children.some((child) => child.__stxAnchor === void 0 && descriptorOf(child)?.visible))
656
+ if (ownerRecord?.divide && ownerRecord.children.some((child) => child.__stxAnchor === void 0 && descriptorOf(child)?.visible)) {
618
657
  record.dividerStyle = { ...ownerRecord.divide.style, ...colorScheme === "dark" ? ownerRecord.divide.dark : {} };
658
+ ownerRecord.hadDividers = !0;
659
+ }
619
660
  record.style = resolveStyle(record, node.__stxId);
620
661
  if (descriptor)
621
662
  descriptor.style = { ...record.style };
@@ -706,7 +747,10 @@ export function createNativeHost(options) {
706
747
  const next = Number.isFinite(width) ? Math.max(0, width) : 0;
707
748
  if (next === viewportWidth)
708
749
  return;
750
+ const crossed = crossesWidthBound(viewportWidth, next);
709
751
  viewportWidth = next;
752
+ if (!crossed)
753
+ return;
710
754
  const children = new Set([...records.values()].flatMap((record) => record.children.map((child) => child.__stxId)));
711
755
  for (const id of records.keys())
712
756
  if (!children.has(id))
@@ -715,6 +759,9 @@ export function createNativeHost(options) {
715
759
  pending: () => queue.length,
716
760
  flush,
717
761
  dispose() {
762
+ if (mediaFlushTimer !== void 0)
763
+ clearTimeout(mediaFlushTimer);
764
+ mediaFlushTimer = void 0;
718
765
  overlayPresenter.dispose();
719
766
  disposed = !0;
720
767
  queue = [];
@@ -775,7 +822,8 @@ export function createNativeHost(options) {
775
822
  if (applyForwardedStyle(forwarded, name, value))
776
823
  return;
777
824
  node = forwarded;
778
- }
825
+ } else if (callerBindingOnWrapper(node, name))
826
+ return;
779
827
  if (name === "class" || name === "className") {
780
828
  const record = recordOf(node);
781
829
  record.classes = String(value ?? "");
@@ -1162,10 +1210,10 @@ export function createNativeHost(options) {
1162
1210
  return copy;
1163
1211
  },
1164
1212
  insert(parent, node, before) {
1165
- const record = recordOf(parent), oldOwner = node.__stxOwner, existing = record.children.findIndex((child) => child.__stxId === node.__stxId);
1213
+ const record = recordOf(parent), oldOwner = node.__stxOwner, existing = oldOwner === parent ? record.children.findIndex((child) => child.__stxId === node.__stxId) : -1;
1166
1214
  if (existing !== -1)
1167
1215
  record.children.splice(existing, 1);
1168
- else if (oldOwner) {
1216
+ else if (oldOwner && oldOwner !== parent) {
1169
1217
  const oldRecord = recordOf(oldOwner), oldIndex = oldRecord.children.findIndex((child) => child.__stxId === node.__stxId);
1170
1218
  if (oldIndex !== -1)
1171
1219
  oldRecord.children.splice(oldIndex, 1);
@@ -0,0 +1,39 @@
1
+ /** Whether a whole media query holds: a comma list of `[not|only] [type] [and (feature)]...`. */
2
+ export declare function evaluateMediaQuery(query: string, state: NativeMediaState): boolean;
3
+ export declare function createNativeMedia(initial?: Partial<NativeMediaState>): NativeMedia;
4
+ /**
5
+ * `matchMedia` for a native screen, where there is no CSS engine to ask.
6
+ *
7
+ * The answers come from what the host tells the screen: its width and height
8
+ * (the bridge's `viewportWidth`, then VIEWPORT), its appearance (APPEARANCE),
9
+ * whether it has a pointer (a Mac), and reduced motion. So the same component
10
+ * reads `useMediaQuery('(min-width: 768px)')` on the web, on a phone, on a
11
+ * tablet and in a Mac window, and gets the answer the `md:` classes get.
12
+ *
13
+ * The media features a layout decides on are understood: width and height
14
+ * (`min-`/`max-`, px, em and rem), orientation, `prefers-color-scheme`,
15
+ * `prefers-reduced-motion`, `hover`, `pointer` and their `any-` forms, media
16
+ * types, `and`, `not`, `only` and comma lists. A feature it does not know
17
+ * never matches, as a browser treats one it does not support.
18
+ */
19
+ export declare interface NativeMediaState {
20
+ width: number
21
+ height: number
22
+ colorScheme: 'light' | 'dark'
23
+ reducedMotion: boolean
24
+ pointer: boolean
25
+ }
26
+ export declare interface NativeMediaQueryList {
27
+ readonly media: string
28
+ readonly matches: boolean
29
+ onchange: ((event: { matches: boolean, media: string }) => void) | null
30
+ addEventListener: (type: string, listener: (event: { matches: boolean, media: string }) => void) => void
31
+ removeEventListener: (type: string, listener: (event: { matches: boolean, media: string }) => void) => void
32
+ addListener: (listener: (event: { matches: boolean, media: string }) => void) => void
33
+ removeListener: (listener: (event: { matches: boolean, media: string }) => void) => void
34
+ }
35
+ export declare interface NativeMedia {
36
+ matchMedia: (query: string) => NativeMediaQueryList
37
+ update: (changes: Partial<NativeMediaState>) => void
38
+ readonly state: Readonly<NativeMediaState>
39
+ }
@@ -0,0 +1,144 @@
1
+ function length(value) {
2
+ const match = /^(-?\d*\.?\d+)(px|em|rem)?$/.exec(value.trim());
3
+ if (!match)
4
+ return null;
5
+ const amount = Number(match[1]);
6
+ return match[2] === "em" || match[2] === "rem" ? amount * 16 : amount;
7
+ }
8
+ function feature(text, state) {
9
+ const [rawName, rawValue] = text.split(":", 2), name = rawName.trim().toLowerCase(), value = rawValue?.trim().toLowerCase(), size = (dimension, bound) => {
10
+ const actual = dimension === "width" ? state.width : state.height;
11
+ if (value === void 0)
12
+ return actual > 0;
13
+ const wanted = length(value);
14
+ if (wanted === null)
15
+ return !1;
16
+ if (bound === "min")
17
+ return actual >= wanted;
18
+ if (bound === "max")
19
+ return actual <= wanted;
20
+ return actual === wanted;
21
+ };
22
+ switch (name) {
23
+ case "width":
24
+ return size("width", null);
25
+ case "min-width":
26
+ return size("width", "min");
27
+ case "max-width":
28
+ return size("width", "max");
29
+ case "height":
30
+ return size("height", null);
31
+ case "min-height":
32
+ return size("height", "min");
33
+ case "max-height":
34
+ return size("height", "max");
35
+ case "orientation": {
36
+ const landscape = state.width > state.height && state.height > 0;
37
+ return value === (landscape ? "landscape" : "portrait");
38
+ }
39
+ case "prefers-color-scheme":
40
+ return value === state.colorScheme;
41
+ case "prefers-reduced-motion":
42
+ return value === void 0 ? state.reducedMotion : value === (state.reducedMotion ? "reduce" : "no-preference");
43
+ case "hover":
44
+ case "any-hover":
45
+ return value === void 0 ? state.pointer : value === (state.pointer ? "hover" : "none");
46
+ case "pointer":
47
+ case "any-pointer":
48
+ return value === void 0 ? !0 : value === (state.pointer ? "fine" : "coarse");
49
+ default:
50
+ return !1;
51
+ }
52
+ }
53
+ export function evaluateMediaQuery(query, state) {
54
+ return query.split(",").some((part) => {
55
+ let text = part.trim().toLowerCase();
56
+ if (!text)
57
+ return !1;
58
+ let negate = !1;
59
+ if (text.startsWith("not ")) {
60
+ negate = !0;
61
+ text = text.slice(4).trim();
62
+ } else if (text.startsWith("only "))
63
+ text = text.slice(5).trim();
64
+ const holds = text.split(/\s+and\s+/).every((term) => {
65
+ const trimmed = term.trim();
66
+ if (trimmed.startsWith("(") && trimmed.endsWith(")"))
67
+ return feature(trimmed.slice(1, -1), state);
68
+ return trimmed === "all" || trimmed === "screen";
69
+ });
70
+ return negate ? !holds : holds;
71
+ });
72
+ }
73
+ export function createNativeMedia(initial = {}) {
74
+ const state = {
75
+ width: Math.max(0, Number(initial.width) || 0),
76
+ height: Math.max(0, Number(initial.height) || 0),
77
+ colorScheme: initial.colorScheme === "dark" ? "dark" : "light",
78
+ reducedMotion: initial.reducedMotion === !0,
79
+ pointer: initial.pointer === !0
80
+ }, watched = new Set;
81
+ function matchMedia(query) {
82
+ const media = String(query), entry = { list: null, matches: evaluateMediaQuery(media, state), listeners: new Set }, listen = (listener) => {
83
+ if (typeof listener !== "function")
84
+ return;
85
+ entry.listeners.add(listener);
86
+ watched.add(entry);
87
+ }, forget = (listener) => {
88
+ entry.listeners.delete(listener);
89
+ if (!entry.listeners.size && !entry.list.onchange)
90
+ watched.delete(entry);
91
+ };
92
+ let onchange = null;
93
+ entry.list = {
94
+ media,
95
+ get matches() {
96
+ return evaluateMediaQuery(media, state);
97
+ },
98
+ get onchange() {
99
+ return onchange;
100
+ },
101
+ set onchange(value) {
102
+ onchange = typeof value === "function" ? value : null;
103
+ if (onchange)
104
+ watched.add(entry);
105
+ else if (!entry.listeners.size)
106
+ watched.delete(entry);
107
+ },
108
+ addEventListener: (type, listener) => {
109
+ if (type === "change")
110
+ listen(listener);
111
+ },
112
+ removeEventListener: (type, listener) => {
113
+ if (type === "change")
114
+ forget(listener);
115
+ },
116
+ addListener: listen,
117
+ removeListener: forget
118
+ };
119
+ return entry.list;
120
+ }
121
+ function update(changes) {
122
+ if (changes.width !== void 0 && Number.isFinite(changes.width))
123
+ state.width = Math.max(0, changes.width);
124
+ if (changes.height !== void 0 && Number.isFinite(changes.height))
125
+ state.height = Math.max(0, changes.height);
126
+ if (changes.colorScheme === "light" || changes.colorScheme === "dark")
127
+ state.colorScheme = changes.colorScheme;
128
+ if (typeof changes.reducedMotion === "boolean")
129
+ state.reducedMotion = changes.reducedMotion;
130
+ if (typeof changes.pointer === "boolean")
131
+ state.pointer = changes.pointer;
132
+ for (const entry of [...watched]) {
133
+ const matches = evaluateMediaQuery(entry.list.media, state);
134
+ if (matches === entry.matches)
135
+ continue;
136
+ entry.matches = matches;
137
+ const event = { matches, media: entry.list.media };
138
+ entry.list.onchange?.(event);
139
+ for (const listener of [...entry.listeners])
140
+ listener(event);
141
+ }
142
+ }
143
+ return { matchMedia, update, state };
144
+ }
@@ -45,6 +45,7 @@ export function prepareSharedNativeScreen(document, manifest, bridge, options =
45
45
  if (scheme === "light" || scheme === "dark") {
46
46
  bridge.colorScheme = scheme;
47
47
  host.setColorScheme(scheme);
48
+ globalThis.__stxNativeMedia?.update({ colorScheme: scheme });
48
49
  }
49
50
  });
50
51
  protocol.on("VIEWPORT", (message) => {
@@ -52,6 +53,8 @@ export function prepareSharedNativeScreen(document, manifest, bridge, options =
52
53
  if (!Number.isFinite(width) || width < 0)
53
54
  return;
54
55
  bridge.viewportWidth = width;
56
+ const height = Number(message.payload?.height);
57
+ globalThis.__stxNativeMedia?.update({ width, ...Number.isFinite(height) && height >= 0 ? { height } : {} });
55
58
  host.setViewportWidth(width);
56
59
  });
57
60
  if (manifest.entries.find((entry) => entry.id === document.root.bindingId)?.bindings.some((binding) => binding.kind === "if" || binding.kind === "for"))
@@ -4,6 +4,16 @@ import { compileSharedScreenBundle } from "./compiler/bundle.js";
4
4
  import { NativeFormData } from "./runtime/jsc-globals.js";
5
5
  import { validateTestMutations } from "./testing-mutations.js";
6
6
  import { createTempDir } from "../temp-dir.js";
7
+ function nativeTapAction(node) {
8
+ if (node.props.disabled === !0)
9
+ return { kind: "blocked" };
10
+ if (["Link", "TouchableOpacity", "TouchableHighlight", "Pressable"].includes(node.type)) {
11
+ for (const value of [node.props.href, node.props.to])
12
+ if (typeof value === "string" && value.trim())
13
+ return { kind: "navigate", target: value.trim() };
14
+ }
15
+ return { kind: "event" };
16
+ }
7
17
 
8
18
  export class StatusAnswer {
9
19
  status;
@@ -66,20 +76,24 @@ function answered(status, body) {
66
76
  }
67
77
  export function mountNativeScreen(code, screen, options = {}) {
68
78
  let ended = !1, online = !0;
69
- const timeouts = new Set, intervals = new Set, timers = {
79
+ const timeouts = new Set, immediateTimeouts = new Set, intervals = new Set, timers = {
70
80
  setTimeout: (run, ms, ...args) => {
71
81
  if (ended)
72
82
  return 0;
73
83
  const id = setTimeout((...rest) => {
74
84
  timeouts.delete(id);
85
+ immediateTimeouts.delete(id);
75
86
  if (!ended)
76
87
  run(...rest);
77
88
  }, ms, ...args);
78
89
  timeouts.add(id);
90
+ if ((ms ?? 0) <= 0)
91
+ immediateTimeouts.add(id);
79
92
  return id;
80
93
  },
81
94
  clearTimeout: (id) => {
82
95
  timeouts.delete(id);
96
+ immediateTimeouts.delete(id);
83
97
  clearTimeout(id);
84
98
  },
85
99
  setInterval: (run, ms, ...args) => {
@@ -402,6 +416,7 @@ export function mountNativeScreen(code, screen, options = {}) {
402
416
  for (const id of intervals)
403
417
  clearInterval(id);
404
418
  timeouts.clear();
419
+ immediateTimeouts.clear();
405
420
  intervals.clear();
406
421
  streams.forEach((stream) => stream.end());
407
422
  }
@@ -410,6 +425,17 @@ export function mountNativeScreen(code, screen, options = {}) {
410
425
  const send = (type, payload = {}) => receive(JSON.stringify({ type, payload })), all = () => [...nodes.values()], press = (node, event = "onPress", nativeEvent = {}) => {
411
426
  if (!node)
412
427
  throw Error(`nothing to ${event}`);
428
+ if (event === "onPress" || event === "onClick") {
429
+ if (ended || nodes.get(node.id) !== node)
430
+ return;
431
+ const action = nativeTapAction(node);
432
+ if (action.kind === "blocked")
433
+ return;
434
+ if (action.kind === "navigate") {
435
+ opened.push(action.target);
436
+ return;
437
+ }
438
+ }
413
439
  if (!node.events[event])
414
440
  throw Error(`${node.type} has no ${event}`);
415
441
  send("EVENT", { handlerId: node.events[event], nativeEvent });
@@ -483,7 +509,7 @@ export function mountNativeScreen(code, screen, options = {}) {
483
509
  settle: async (ms = 30) => {
484
510
  const started = performance.now();
485
511
  await Bun.sleep(ms);
486
- while (performance.now() - started < 5000 && (fetching > 0 || performance.now() - answeredAt < ms))
512
+ while (!ended && performance.now() - started < 5000 && (fetching > 0 || performance.now() - answeredAt < ms || immediateTimeouts.size > 0))
487
513
  await Bun.sleep(5);
488
514
  if (mutationErrors.length) {
489
515
  const error = mutationErrors[0];
@@ -1,3 +1,14 @@
1
+ /**
2
+ * Native lineHeight is a length; CSS's bare number is a font-size multiplier.
3
+ * Adapt explicitly when a shared view binds native typography through :style.
4
+ * Other style properties, including unitless font weights, keep their meaning.
5
+ *
6
+ * nativeTextStyle({ fontFamily: 'Signature', fontSize: 48, lineHeight: 60 }, 'web')
7
+ * // { fontFamily: 'Signature', fontSize: '48px', lineHeight: '60px' }
8
+ */
9
+ export declare function nativeTextStyle<T extends NativeTextMetrics>(style: T, target: 'native'): T;
10
+ export declare function nativeTextStyle<T extends NativeTextMetrics>(style: T, target: 'web'): WebTextStyle<T>;
11
+ export declare function nativeTextStyle<T extends NativeTextMetrics>(style: T, target: NativeTextTarget): T | WebTextStyle<T>;
1
12
  /**
2
13
  * The grouped look a native screen is built from, in role classes.
3
14
  *
@@ -93,4 +104,17 @@ export declare const nativeUi: {
93
104
  noticeDanger: 'p-3 rounded-panel bg-danger-soft';
94
105
  noticeDangerText: 'text-[15px] text-danger-soft-ink'
95
106
  };
107
+ /** Typography authored in native points, shared with an ordinary browser view. */
108
+ export declare interface NativeTextMetrics {
109
+ [property: string]: unknown
110
+ fontFamily?: string
111
+ fontSize?: number
112
+ lineHeight?: number
113
+ letterSpacing?: number
114
+ }
96
115
  export type NativeUiClass = keyof typeof nativeUi;
116
+ export type NativeTextTarget = 'native' | 'web';
117
+ declare type WebTextMetric<Value> = Value extends number ? string : Value;
118
+ export type WebTextStyle<T> = {
119
+ [K in keyof T]: K extends 'fontSize' | 'lineHeight' | 'letterSpacing' ? WebTextMetric<T[K]> : T[K]
120
+ }
package/dist/native/ui.js CHANGED
@@ -36,3 +36,12 @@ export const nativeUi = {
36
36
  noticeDanger: "p-3 rounded-panel bg-danger-soft",
37
37
  noticeDangerText: "text-[15px] text-danger-soft-ink"
38
38
  };
39
+ export function nativeTextStyle(style, target) {
40
+ if (target === "native")
41
+ return { ...style };
42
+ const css = { ...style };
43
+ for (const metric of ["fontSize", "lineHeight", "letterSpacing"])
44
+ if (typeof css[metric] === "number")
45
+ css[metric] = `${css[metric]}px`;
46
+ return css;
47
+ }
package/dist/pwa.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // @bun
2
- import{Zs,Ht,wl,Sg}from"./chunk-4wc5pc19.js";import{Ys,Ai,wg,vg,xg}from"./chunk-e1gxykm8.js";import{hl,yl,bl,yg,bg}from"./chunk-y38swh5t.js";import{Ue,Tn,Pi}from"./chunk-k4bdf0dw.js";import{kg,_g,Cg,Eg,Qs,cy}from"./chunk-et1vz3wd.js";import B from"fs";import w from"path";import O from"fs";import u from"path";var v=[72,96,128,144,152,192,384,512],S=[120,152,167,180],P=[16,32];async function M(n,t){let e={success:!0,generatedFiles:[],errors:[],warnings:[]},r=n.pwa?.icons;if(!r?.src)return e.errors.push("No source icon specified in pwa.icons.src"),e.success=!1,e;let o=u.isAbsolute(r.src)?r.src:u.resolve(process.cwd(),r.src);if(!await Bun.file(o).exists())return e.errors.push(`Source icon not found: ${o}`),e.success=!1,e;let a=u.resolve(t,r.outputDir||"pwa-icons");try{O.mkdirSync(a,{recursive:!0})}catch{return e.errors.push(`Failed to create output directory: ${a}`),e.success=!1,e}let s=r.sizes||v,l=r.generateWebP??!0,p=r.generateAppleIcons??!0;try{let c;try{c=await import("sharp")}catch{return e.errors.push(`sharp is not installed. Install it with: bun add sharp
3
- Icon generation requires the sharp package for image processing.`),e.success=!1,e}let g=await c.default(o).metadata();if(g.width&&g.width<512)e.warnings.push(`Source icon is ${g.width}x${g.height}. Recommend using at least 512x512 for best quality.`);for(let i of s){let d=u.join(a,`icon-${i}x${i}.png`);if(await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d),l){let x=u.join(a,`icon-${i}x${i}.webp`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).webp({quality:90}).toFile(x),e.generatedFiles.push(x)}}if(p){for(let d of S){let x=u.join(a,`apple-touch-icon-${d}x${d}.png`);await c.default(o).resize(d,d,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(x),e.generatedFiles.push(x)}let i=u.join(a,"apple-touch-icon.png");await c.default(o).resize(180,180,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(i),e.generatedFiles.push(i)}for(let i of P){let d=u.join(a,`favicon-${i}x${i}.png`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d)}let f=512,y=u.join(a,`icon-maskable-${f}x${f}.png`),m=Math.floor(f*0.1),k=f-m*2;await c.default(o).resize(k,k,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).extend({top:m,bottom:m,left:m,right:m,background:{r:255,g:255,b:255,alpha:1}}).png().toFile(y),e.generatedFiles.push(y)}catch(c){let h=c instanceof Error?c.message:String(c);e.errors.push(`Icon generation failed: ${h}`),e.success=!1}return e}function N(n){let t=n.sizes||v,e=n.outputDir?`/${n.outputDir}`:"/pwa-icons",r=n.generateWebP??!0,o=n.generateAppleIcons??!0,a=[];for(let s of t)if(a.push(`${e}/icon-${s}x${s}.png`),r)a.push(`${e}/icon-${s}x${s}.webp`);if(o){a.push(`${e}/apple-touch-icon.png`);for(let s of S)a.push(`${e}/apple-touch-icon-${s}x${s}.png`)}for(let s of P)a.push(`${e}/favicon-${s}x${s}.png`);return a.push(`${e}/icon-maskable-512x512.png`),a}async function I(){try{return await import("sharp"),!0}catch{return!1}}function A(n,t,e,r){let o=[],a=r.join(" ");for(let s of n)if(o.push({src:`${t}/icon-${s}x${s}.png`,sizes:`${s}x${s}`,type:"image/png",purpose:a}),e)o.push({src:`${t}/icon-${s}x${s}.webp`,sizes:`${s}x${s}`,type:"image/webp",purpose:a});return o}function C(n){return n.map((t)=>({name:t.name,short_name:t.shortName,description:t.description,url:t.url,icons:t.icons?.map((e)=>({src:e.src,sizes:e.sizes,type:e.type}))}))}function T(n){let t=n.pwa?.shareTarget;if(!t?.enabled)return;let e={action:t.action||"/share",method:t.method||"POST",enctype:t.enctype||"multipart/form-data",params:{title:t.params?.title||"title",text:t.params?.text||"text",url:t.params?.url||"url"}};if(t.acceptFiles&&t.acceptFiles.length>0)e.params.files=t.acceptFiles.map((r)=>({name:r.name,accept:r.accept}));return e}function H(n){let t=n.pwa?.fileHandlers;if(!t?.enabled||!t.accept)return;let e=[{action:t.action||"/",accept:t.accept,launch_type:t.launchType||"single-client"}];if(t.icons)e[0].icons=t.icons.map((r)=>({src:r.src,sizes:r.sizes,type:r.type}));return e}function W(n){let t=n.pwa?.protocolHandlers;if(!t||t.length===0)return;return t.map((e)=>({protocol:e.protocol,url:e.url}))}function j(n){let t=n.pwa;if(!t?.enabled||!t.manifest)return null;let{manifest:e,icons:r}=t,o=r?.sizes||[72,96,128,144,152,192,384,512],a=r?.outputDir?`/${r.outputDir}`:"/pwa-icons",s=r?.generateWebP??!0,l=r?.purpose||["any","maskable"],p={name:e.name,short_name:e.shortName||e.name,description:e.description,start_url:e.startUrl||"/",display:e.display||"standalone",display_override:e.displayOverride,orientation:e.orientation,theme_color:e.themeColor,background_color:e.backgroundColor,scope:e.scope||"/",lang:e.lang,dir:e.dir,id:e.id,categories:e.categories,icons:A(o,a,s,l)};if(e.shortcuts&&e.shortcuts.length>0)p.shortcuts=C(e.shortcuts);if(e.screenshots&&e.screenshots.length>0)p.screenshots=e.screenshots.map((f)=>({src:f.src,sizes:f.sizes,type:f.type,label:f.label,form_factor:f.platform}));let c=T(n);if(c)p.share_target=c;let h=H(n);if(h)p.file_handlers=h;let g=W(n);if(g)p.protocol_handlers=g;if(e.launchHandler)p.launch_handler={client_mode:e.launchHandler};if(e.handleLinks)p.handle_links=e.handleLinks;if(e.edgeSidePanel?.enabled)p.edge_side_panel={preferred_width:e.edgeSidePanel.preferredWidth};return p}function _(n){let t=j(n);if(!t)return"";let e=JSON.parse(JSON.stringify(t));return JSON.stringify(e,null,2)}function q(n,t){return{...t,...n,shortcuts:n.shortcuts||t.shortcuts,screenshots:n.screenshots||t.screenshots,categories:n.categories||t.categories}}function D(n){let t=[],e=n.pwa;if(!e?.enabled)return t;let r=e.manifest;if(!r)return t.push("PWA manifest configuration is missing"),t;if(!r.name)t.push("Manifest name is required");let o=["fullscreen","standalone","minimal-ui","browser"];if(r.display&&!o.includes(r.display))t.push(`Invalid display mode: ${r.display}. Must be one of: ${o.join(", ")}`);let a=["any","natural","landscape","landscape-primary","landscape-secondary","portrait","portrait-primary","portrait-secondary"];if(r.orientation&&!a.includes(r.orientation))t.push(`Invalid orientation: ${r.orientation}`);let s=/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;if(r.themeColor&&!s.test(r.themeColor))t.push(`Invalid theme color: ${r.themeColor}. Must be a valid hex color.`);if(r.backgroundColor&&!s.test(r.backgroundColor))t.push(`Invalid background color: ${r.backgroundColor}. Must be a valid hex color.`);if(e.shareTarget?.enabled){if(!e.shareTarget.action)t.push("Share target action URL is required")}if(e.fileHandlers?.enabled){if(!e.fileHandlers.accept||Object.keys(e.fileHandlers.accept).length===0)t.push("File handlers must specify accepted MIME types")}if(e.protocolHandlers)for(let l of e.protocolHandlers){if(!l.protocol)t.push("Protocol handler missing protocol");if(!l.url||!l.url.includes("%s"))t.push(`Protocol handler URL must contain %s placeholder: ${l.protocol}`)}return t}import z from"path";async function F(n){let t=n.pwa?.offline;if(!t?.enabled)return"";if(t.page){let e=z.isAbsolute(t.page)?t.page:z.resolve(process.cwd(),t.page);if(await Bun.file(e).exists())try{let{processDirectives:r}=await import("./chunk-hp44x2dq.js"),o=await Bun.file(e).text();return await r(o,{},e,n,new Set)}catch(r){console.warn(`[PWA] Failed to process custom offline page: ${r}`)}else console.warn(`[PWA] Custom offline page not found: ${e}`)}return E(n)}function E(n){let t=n.pwa?.offline,e=n.pwa?.manifest,r=t?.fallbackTitle||"You are offline",o=t?.fallbackMessage||"Please check your internet connection and try again.",a=e?.themeColor||"#4f46e5",s=e?.shortName||e?.name||"App";return`<!DOCTYPE html>
2
+ import{Zs,Ht,vl,kg}from"./chunk-bwcj9z19.js";import{Ys,Ai,vg,xg,Sg}from"./chunk-4s5q1aea.js";import{yl,bl,wl,bg,wg}from"./chunk-dhqp3z4w.js";import{Ue,Tn,Pi}from"./chunk-k4bdf0dw.js";import{_g,Cg,Eg,Tg,Qs,ly}from"./chunk-7pk3t82j.js";import B from"fs";import w from"path";import O from"fs";import u from"path";var v=[72,96,128,144,152,192,384,512],S=[120,152,167,180],P=[16,32];async function M(n,t){let e={success:!0,generatedFiles:[],errors:[],warnings:[]},r=n.pwa?.icons;if(!r?.src)return e.errors.push("No source icon specified in pwa.icons.src"),e.success=!1,e;let o=u.isAbsolute(r.src)?r.src:u.resolve(process.cwd(),r.src);if(!await Bun.file(o).exists())return e.errors.push(`Source icon not found: ${o}`),e.success=!1,e;let a=u.resolve(t,r.outputDir||"pwa-icons");try{O.mkdirSync(a,{recursive:!0})}catch{return e.errors.push(`Failed to create output directory: ${a}`),e.success=!1,e}let s=r.sizes||v,l=r.generateWebP??!0,p=r.generateAppleIcons??!0;try{let c;try{c=await import("sharp")}catch{return e.errors.push(`sharp is not installed. Install it with: bun add sharp
3
+ Icon generation requires the sharp package for image processing.`),e.success=!1,e}let g=await c.default(o).metadata();if(g.width&&g.width<512)e.warnings.push(`Source icon is ${g.width}x${g.height}. Recommend using at least 512x512 for best quality.`);for(let i of s){let d=u.join(a,`icon-${i}x${i}.png`);if(await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d),l){let x=u.join(a,`icon-${i}x${i}.webp`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).webp({quality:90}).toFile(x),e.generatedFiles.push(x)}}if(p){for(let d of S){let x=u.join(a,`apple-touch-icon-${d}x${d}.png`);await c.default(o).resize(d,d,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(x),e.generatedFiles.push(x)}let i=u.join(a,"apple-touch-icon.png");await c.default(o).resize(180,180,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(i),e.generatedFiles.push(i)}for(let i of P){let d=u.join(a,`favicon-${i}x${i}.png`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d)}let f=512,y=u.join(a,`icon-maskable-${f}x${f}.png`),m=Math.floor(f*0.1),k=f-m*2;await c.default(o).resize(k,k,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).extend({top:m,bottom:m,left:m,right:m,background:{r:255,g:255,b:255,alpha:1}}).png().toFile(y),e.generatedFiles.push(y)}catch(c){let h=c instanceof Error?c.message:String(c);e.errors.push(`Icon generation failed: ${h}`),e.success=!1}return e}function N(n){let t=n.sizes||v,e=n.outputDir?`/${n.outputDir}`:"/pwa-icons",r=n.generateWebP??!0,o=n.generateAppleIcons??!0,a=[];for(let s of t)if(a.push(`${e}/icon-${s}x${s}.png`),r)a.push(`${e}/icon-${s}x${s}.webp`);if(o){a.push(`${e}/apple-touch-icon.png`);for(let s of S)a.push(`${e}/apple-touch-icon-${s}x${s}.png`)}for(let s of P)a.push(`${e}/favicon-${s}x${s}.png`);return a.push(`${e}/icon-maskable-512x512.png`),a}async function I(){try{return await import("sharp"),!0}catch{return!1}}function A(n,t,e,r){let o=[],a=r.join(" ");for(let s of n)if(o.push({src:`${t}/icon-${s}x${s}.png`,sizes:`${s}x${s}`,type:"image/png",purpose:a}),e)o.push({src:`${t}/icon-${s}x${s}.webp`,sizes:`${s}x${s}`,type:"image/webp",purpose:a});return o}function C(n){return n.map((t)=>({name:t.name,short_name:t.shortName,description:t.description,url:t.url,icons:t.icons?.map((e)=>({src:e.src,sizes:e.sizes,type:e.type}))}))}function T(n){let t=n.pwa?.shareTarget;if(!t?.enabled)return;let e={action:t.action||"/share",method:t.method||"POST",enctype:t.enctype||"multipart/form-data",params:{title:t.params?.title||"title",text:t.params?.text||"text",url:t.params?.url||"url"}};if(t.acceptFiles&&t.acceptFiles.length>0)e.params.files=t.acceptFiles.map((r)=>({name:r.name,accept:r.accept}));return e}function H(n){let t=n.pwa?.fileHandlers;if(!t?.enabled||!t.accept)return;let e=[{action:t.action||"/",accept:t.accept,launch_type:t.launchType||"single-client"}];if(t.icons)e[0].icons=t.icons.map((r)=>({src:r.src,sizes:r.sizes,type:r.type}));return e}function W(n){let t=n.pwa?.protocolHandlers;if(!t||t.length===0)return;return t.map((e)=>({protocol:e.protocol,url:e.url}))}function j(n){let t=n.pwa;if(!t?.enabled||!t.manifest)return null;let{manifest:e,icons:r}=t,o=r?.sizes||[72,96,128,144,152,192,384,512],a=r?.outputDir?`/${r.outputDir}`:"/pwa-icons",s=r?.generateWebP??!0,l=r?.purpose||["any","maskable"],p={name:e.name,short_name:e.shortName||e.name,description:e.description,start_url:e.startUrl||"/",display:e.display||"standalone",display_override:e.displayOverride,orientation:e.orientation,theme_color:e.themeColor,background_color:e.backgroundColor,scope:e.scope||"/",lang:e.lang,dir:e.dir,id:e.id,categories:e.categories,icons:A(o,a,s,l)};if(e.shortcuts&&e.shortcuts.length>0)p.shortcuts=C(e.shortcuts);if(e.screenshots&&e.screenshots.length>0)p.screenshots=e.screenshots.map((f)=>({src:f.src,sizes:f.sizes,type:f.type,label:f.label,form_factor:f.platform}));let c=T(n);if(c)p.share_target=c;let h=H(n);if(h)p.file_handlers=h;let g=W(n);if(g)p.protocol_handlers=g;if(e.launchHandler)p.launch_handler={client_mode:e.launchHandler};if(e.handleLinks)p.handle_links=e.handleLinks;if(e.edgeSidePanel?.enabled)p.edge_side_panel={preferred_width:e.edgeSidePanel.preferredWidth};return p}function _(n){let t=j(n);if(!t)return"";let e=JSON.parse(JSON.stringify(t));return JSON.stringify(e,null,2)}function q(n,t){return{...t,...n,shortcuts:n.shortcuts||t.shortcuts,screenshots:n.screenshots||t.screenshots,categories:n.categories||t.categories}}function D(n){let t=[],e=n.pwa;if(!e?.enabled)return t;let r=e.manifest;if(!r)return t.push("PWA manifest configuration is missing"),t;if(!r.name)t.push("Manifest name is required");let o=["fullscreen","standalone","minimal-ui","browser"];if(r.display&&!o.includes(r.display))t.push(`Invalid display mode: ${r.display}. Must be one of: ${o.join(", ")}`);let a=["any","natural","landscape","landscape-primary","landscape-secondary","portrait","portrait-primary","portrait-secondary"];if(r.orientation&&!a.includes(r.orientation))t.push(`Invalid orientation: ${r.orientation}`);let s=/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;if(r.themeColor&&!s.test(r.themeColor))t.push(`Invalid theme color: ${r.themeColor}. Must be a valid hex color.`);if(r.backgroundColor&&!s.test(r.backgroundColor))t.push(`Invalid background color: ${r.backgroundColor}. Must be a valid hex color.`);if(e.shareTarget?.enabled){if(!e.shareTarget.action)t.push("Share target action URL is required")}if(e.fileHandlers?.enabled){if(!e.fileHandlers.accept||Object.keys(e.fileHandlers.accept).length===0)t.push("File handlers must specify accepted MIME types")}if(e.protocolHandlers)for(let l of e.protocolHandlers){if(!l.protocol)t.push("Protocol handler missing protocol");if(!l.url||!l.url.includes("%s"))t.push(`Protocol handler URL must contain %s placeholder: ${l.protocol}`)}return t}import z from"path";async function F(n){let t=n.pwa?.offline;if(!t?.enabled)return"";if(t.page){let e=z.isAbsolute(t.page)?t.page:z.resolve(process.cwd(),t.page);if(await Bun.file(e).exists())try{let{processDirectives:r}=await import("./chunk-498286bb.js"),o=await Bun.file(e).text();return await r(o,{},e,n,new Set)}catch(r){console.warn(`[PWA] Failed to process custom offline page: ${r}`)}else console.warn(`[PWA] Custom offline page not found: ${e}`)}return E(n)}function E(n){let t=n.pwa?.offline,e=n.pwa?.manifest,r=t?.fallbackTitle||"You are offline",o=t?.fallbackMessage||"Please check your internet connection and try again.",a=e?.themeColor||"#4f46e5",s=e?.shortName||e?.name||"App";return`<!DOCTYPE html>
4
4
  <html lang="en">
5
5
  <head>
6
6
  <meta charset="UTF-8">
@@ -233,4 +233,4 @@ Icon generation requires the sharp package for image processing.`),e.success=!1,
233
233
  }, 5000);
234
234
  </script>
235
235
  </body>
236
- </html>`}function b(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}async function re(n,t){let e={success:!0,files:{icons:[]},errors:[],warnings:[]},r=n.pwa;if(!r?.enabled)return e;try{B.mkdirSync(t,{recursive:!0})}catch{return e.errors.push(`Failed to create output directory: ${t}`),e.success=!1,e}try{let a=_(n);if(a){let s=w.join(t,"manifest.json");await Bun.write(s,a),e.files.manifest=s}}catch(a){let s=a instanceof Error?a.message:String(a);e.errors.push(`Failed to generate manifest.json: ${s}`),e.success=!1}if(r.icons?.src)if(await I()){let s=await M(n,t);if(e.files.icons=s.generatedFiles,e.warnings.push(...s.warnings),!s.success)e.errors.push(...s.errors),e.success=!1}else e.warnings.push("sharp is not installed. Skipping icon generation. Install with: bun add sharp");if(r.offline?.enabled)try{let a=await F(n);if(a){let s=w.join(t,"offline.html");await Bun.write(s,a),e.files.offlinePage=s}}catch(a){let s=a instanceof Error?a.message:String(a);e.errors.push(`Failed to generate offline page: ${s}`),e.success=!1}let o;if(r.precache?.enabled){let a=Ue(t,n);o={fileCount:a.fileCount,totalSize:a.totalSize},e.precacheStats=o}try{let a=Zs(n,t);if(a){let s=Ht(n),l=w.join(t,s);await Bun.write(l,a),e.files.serviceWorker=l}}catch(a){let s=a instanceof Error?a.message:String(a);e.errors.push(`Failed to generate service worker: ${s}`),e.success=!1}return e}function ae(n,t){return Ai(n,t)}function se(n){return n.pwa?.enabled===!0}export{S as APPLE_TOUCH_ICON_SIZES,v as DEFAULT_ICON_SIZES,P as FAVICON_SIZES,yl as auditBuildOutput,hl as auditConfig,re as buildPwaAssets,bl as calculateAuditResult,bg as formatAuditResult,Pi as formatSize,j as generateManifest,_ as generateManifestJson,vg as generateManifestLink,F as generateOfflinePage,Ue as generatePrecacheManifest,Tn as generatePrecacheManifestJs,M as generatePwaIcons,Ys as generatePwaTags,Zs as generateServiceWorker,Sg as generateServiceWorkerAuto,wg as generateSwRegistrationScript,xg as generateThemeColorMeta,N as getExpectedIconPaths,Ht as getServiceWorkerFileName,Ai as injectPwaTags,se as isPwaEnabled,I as isSharpAvailable,wl as isWorkboxEnabled,q as mergeManifestConfig,ae as processPwaHtml,Qs as pwaDirectives,kg as pwaInstallDirective,Cg as pwaOfflineDirective,Eg as pwaPushDirective,_g as pwaUpdateDirective,cy as registerPwaDirectives,yg as runPwaAudit,D as validateManifest};
236
+ </html>`}function b(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}async function re(n,t){let e={success:!0,files:{icons:[]},errors:[],warnings:[]},r=n.pwa;if(!r?.enabled)return e;try{B.mkdirSync(t,{recursive:!0})}catch{return e.errors.push(`Failed to create output directory: ${t}`),e.success=!1,e}try{let a=_(n);if(a){let s=w.join(t,"manifest.json");await Bun.write(s,a),e.files.manifest=s}}catch(a){let s=a instanceof Error?a.message:String(a);e.errors.push(`Failed to generate manifest.json: ${s}`),e.success=!1}if(r.icons?.src)if(await I()){let s=await M(n,t);if(e.files.icons=s.generatedFiles,e.warnings.push(...s.warnings),!s.success)e.errors.push(...s.errors),e.success=!1}else e.warnings.push("sharp is not installed. Skipping icon generation. Install with: bun add sharp");if(r.offline?.enabled)try{let a=await F(n);if(a){let s=w.join(t,"offline.html");await Bun.write(s,a),e.files.offlinePage=s}}catch(a){let s=a instanceof Error?a.message:String(a);e.errors.push(`Failed to generate offline page: ${s}`),e.success=!1}let o;if(r.precache?.enabled){let a=Ue(t,n);o={fileCount:a.fileCount,totalSize:a.totalSize},e.precacheStats=o}try{let a=Zs(n,t);if(a){let s=Ht(n),l=w.join(t,s);await Bun.write(l,a),e.files.serviceWorker=l}}catch(a){let s=a instanceof Error?a.message:String(a);e.errors.push(`Failed to generate service worker: ${s}`),e.success=!1}return e}function ae(n,t){return Ai(n,t)}function se(n){return n.pwa?.enabled===!0}export{S as APPLE_TOUCH_ICON_SIZES,v as DEFAULT_ICON_SIZES,P as FAVICON_SIZES,bl as auditBuildOutput,yl as auditConfig,re as buildPwaAssets,wl as calculateAuditResult,wg as formatAuditResult,Pi as formatSize,j as generateManifest,_ as generateManifestJson,xg as generateManifestLink,F as generateOfflinePage,Ue as generatePrecacheManifest,Tn as generatePrecacheManifestJs,M as generatePwaIcons,Ys as generatePwaTags,Zs as generateServiceWorker,kg as generateServiceWorkerAuto,vg as generateSwRegistrationScript,Sg as generateThemeColorMeta,N as getExpectedIconPaths,Ht as getServiceWorkerFileName,Ai as injectPwaTags,se as isPwaEnabled,I as isSharpAvailable,vl as isWorkboxEnabled,q as mergeManifestConfig,ae as processPwaHtml,Qs as pwaDirectives,_g as pwaInstallDirective,Eg as pwaOfflineDirective,Tg as pwaPushDirective,Cg as pwaUpdateDirective,ly as registerPwaDirectives,bg as runPwaAudit,D as validateManifest};
package/dist/ssg.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // @bun
2
- import"./chunk-7sh9fa3q.js";import{w,el}from"./chunk-bq9xf8nq.js";import"./chunk-9f6qx8b9.js";import"./chunk-2yxva96k.js";import{Rt,S}from"./chunk-wx6h1xs3.js";import"./chunk-27rzdq3n.js";import"./chunk-64gbacyk.js";import"./chunk-zxfptbac.js";import{kt,_t,Ct,Et,Tt,$t}from"./chunk-j2qv5ra2.js";import{a}from"./chunk-skn2n8jt.js";import{Cs}from"./chunk-x8js27hd.js";import"./chunk-605b93pe.js";import"./chunk-ert36h3v.js";import{he,en,tn}from"./chunk-7v0psycp.js";import"./chunk-nw355jn6.js";import{y}from"./chunk-10az8e1m.js";import{yt,i}from"./chunk-5hy66mfn.js";import"./chunk-bc91m8x8.js";import"./chunk-n70ry0hg.js";import{ds}from"./chunk-5r1rdpeg.js";import"./chunk-dqpqc5ps.js";import"./chunk-2gqhfge6.js";import{Ga,Ja,Ya}from"./chunk-d18xd9x5.js";import{Zt,Yn,Zn}from"./chunk-ndjmt3vg.js";import{Qt}from"./chunk-p8185yw2.js";import"./chunk-g2gk5qen.js";import"./chunk-he85ksa7.js";import{X,we}from"./chunk-p9gkz451.js";import"./chunk-wj78td69.js";import"./chunk-1165h1nv.js";import{l}from"./chunk-jdj1358b.js";import{s,ge}from"./chunk-m4mpyq3d.js";import D from"fs";import f from"path";import{createHash as vt}from"crypto";function Pt(t){try{return new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(t).replace(/\}(var |let |const |function )/g,"};$1").trim()}catch{return t}}var Dt=/<script\s+type="stx\/island"\s+data-stx-island="([^"]+)"([^>]*)>([\s\S]*?)<\/script>/g;function It(t){return Bun.hash(t).toString(16)}function ot(t,r={}){if(!t.includes('type="stx/island"'))return{html:t,chunks:[]};let n=new Map,o=t.replace(Dt,(e,u,g,v)=>{let x=v.trim();if(!x)return e;if(/\bdata-stx-src=/.test(g))return e;if(r.minify)x=Pt(x);let p=It(x);if(!n.has(p))n.set(p,x);let P=r.integrity?` data-stx-integrity="sha384-${vt("sha384").update(x).digest("base64")}"`:"";return`<script type="stx/island" data-stx-island="${u}" data-stx-src="/_stx/islands/${p}.js"${P}${g}></script>`}),c=Array.from(n,([e,u])=>({hash:e,code:u}));return{html:o,chunks:c}}var Bt=new Set(["visible","idle"]);function ct(t){if(!t.includes("data-stx-src="))return t;let r=new Map,n=/data-stx-scope="([^"]+)"[^>]*?stx-hydrate="([^"]+)"/g,o;while((o=n.exec(t))!==null)r.set(o[1],o[2]);let c=new Set,e=/data-stx-island="([^"]+)"[^>]*?data-stx-src="([^"]+)"/g,u;while((u=e.exec(t))!==null)if(Bt.has(r.get(u[1])||""))c.add(u[2]);let g=/<\/head\s*>/iy,v=S(t,(p,P)=>(g.lastIndex=P,g.exec(p)?g.lastIndex:-1))[0]?.start??-1;if(c.size===0||v===-1)return t;let x=Array.from(c).filter((p)=>!t.includes(`rel="prefetch" href="${p}"`)).map((p)=>`<link rel="prefetch" href="${p}" as="script">`).join("");if(!x)return t;return t.slice(0,v)+x+t.slice(v)}var jt=["STX_SITE_URL","SITE_URL","URL","VERCEL_URL","CF_PAGES_URL"];function K(t){let r=t.trim();if(!r)return null;let n=/^https?:\/\//i.test(r)?r:`https://${r}`;try{return new URL(n).origin+new URL(n).pathname.replace(/\/$/,"")}catch{return null}}function Ft(t){for(let r of jt){let n=t[r];if(!n)continue;let o=K(n);if(o)return{url:o,source:"env",via:r}}return null}function lt(t){if(!t||typeof t!=="object")return null;let r=t,n=r.site?.url??r.url??r.app?.url;return typeof n==="string"?K(n):null}async function At(t){let{existsSync:r}=await import("fs"),n=await import("path");for(let o of["site.config.ts","site.config.js",".config/site.config.ts"]){let c=n.resolve(t,o);if(!r(c))continue;try{let e=await import(c),u=lt(e.default??e);if(u)return u}catch{}}return null}async function ut(t={}){let r=t.cwd??process.cwd(),n=t.env??process.env;if(t.explicit){let u=K(t.explicit);if(u)return{url:u,source:"option"}}let o=lt(t.stxConfig);if(o)return{url:o,source:"stx.config",via:"site.url"};let c=await At(r);if(c)return{url:c,source:"site.config",via:"url"};let e=Ft(n);if(e)return e;return{url:"http://localhost",source:"fallback"}}function dt(){return["No site URL configured \u2014 sitemap.xml and robots.txt will point at http://localhost."," Set one in stx.config.ts (site: { url: 'https://example.com' }), in site.config.ts,"," via --domain, or with SITE_URL in the build environment."].join(`
3
- `)}function q(t){return async()=>({paths:await t(),fallback:!1})}var Ot;function Lt(t){let r=s(t),{depths:n}=ge(r),o=/\b(?:async\s+)?function\s+getStaticPaths\s*\(/g,c;while((c=o.exec(r))!==null){if(n[c.index]!==0)continue;let u=w(r,"(",")",o.lastIndex-1),g=r.indexOf("{",u+1),v=w(r,"{","}",g);if(u<0||g<0||v<0)break;return t.slice(c.index,v+1)}let e=/\b(?:const|let|var)\s+getStaticPaths\s*=/g;while((c=e.exec(r))!==null){if(n[c.index]!==0)continue;let u=el(r,e.lastIndex).endPos;return t.slice(e.lastIndex,u).trim()}throw SyntaxError("Could not extract getStaticPaths; use a top-level function or const declaration")}async function gt(t){let r="read";try{let n=await Bun.file(t).text();r="parse";let o=Qt(n),c=[...o.server,...o.client,...o.signals].filter((e)=>/(?:^|\s)server(?:\s|=|$)/i.test(s(e.attrs))).sort((e,u)=>n.indexOf(e.fullTag)-n.indexOf(u.fullTag));for(let e of c){if(!/\bgetStaticPaths\b/.test(s(e.content)))continue;let u=(Ot??=new Bun.Transpiler({loader:"ts",target:"bun"})).transformSync(e.content);if(!/\bgetStaticPaths\b/.test(s(u)))continue;let g=Lt(u);if(/\bdefineStaticPaths\b/.test(s(g))&&Rt(u,"defineStaticPaths"))throw SyntaxError("Cannot evaluate a module-local defineStaticPaths binding during isolated hook extraction");r="execute";let v=Function("defineStaticPaths",`return (${g})`)(q);if(typeof v!=="function")throw TypeError("getStaticPaths must be a function");let x=await v();r="result";let p=Array.isArray(x)?{paths:x}:x;if(!p||typeof p!=="object"||!("paths"in p)||!Array.isArray(p.paths))throw TypeError("getStaticPaths must return { paths: [...] } or an array of paths");for(let P of p.paths)if(!P||typeof P!=="object"||!P.params||typeof P.params!=="object"||Array.isArray(P.params))throw TypeError("Each getStaticPaths path must contain a params object");return{kind:"ok",value:p}}return{kind:"absent"}}catch(n){return{kind:"error",phase:r,error:n instanceof Error?n:Error(String(n))}}}class pt{cacheDir;cache=new Map;loaded=!1;salt;constructor(t,r=""){this.cacheDir=t,this.salt=r}async load(){if(this.loaded)return;let t=f.join(this.cacheDir,"build-cache.json");if(await Bun.file(t).exists())try{let r=JSON.parse(await Bun.file(t).text());for(let[n,o]of Object.entries(r))this.cache.set(n,o)}catch{}this.loaded=!0}async save(){await D.promises.mkdir(this.cacheDir,{recursive:!0});let t=f.join(this.cacheDir,"build-cache.json"),r={};for(let[n,o]of this.cache)r[n]=o;await Bun.write(t,JSON.stringify(r))}getHash(t,r){let n=D.statSync(t),o=`${this.salt}|${t}:${n.mtimeMs}`;for(let e of r)if(D.existsSync(e)){let u=D.statSync(e);o+=`:${e}:${u.mtimeMs}`}let c=0;for(let e=0;e<o.length;e++){let u=o.charCodeAt(e);c=(c<<5)-c+u,c=c&c}return Math.abs(c).toString(36)}get(t,r){let n=this.cache.get(t);if(!n)return null;let o=ft(r).some((u)=>D.existsSync(u)),c=[r,...n.dependencies??[]].some((u)=>u.endsWith(".stx")&&D.existsSync(u)&&ds(D.readFileSync(u,"utf8")).some((g)=>/\bserver\b/.test(g.attrs)));if(o||c)return this.cache.delete(t),null;let e=this.getHash(r,n.dependencies??[]);if(n.hash!==e)return this.cache.delete(t),null;return n.html}set(t,r,n,o){let c=this.getHash(r,n);this.cache.set(t,{hash:c,html:o,generatedAt:Date.now(),dependencies:n})}}class ht{cacheDir;constructor(t){this.cacheDir=t}getFilePath(t){let r=t.replace(/[^a-zA-Z0-9]/g,"_")+".json";return f.join(this.cacheDir,"isr",r)}async get(t){let r=this.getFilePath(t);if(!await Bun.file(r).exists())return null;try{return JSON.parse(await Bun.file(r).text())}catch{return null}}async set(t,r){let n=this.getFilePath(t);await D.promises.mkdir(f.dirname(n),{recursive:!0}),await Bun.write(n,JSON.stringify(r))}async invalidate(t){let r=this.getFilePath(t);if(await Bun.file(r).exists())await D.promises.unlink(r)}async invalidatePattern(t){let r=f.join(this.cacheDir,"isr");if(!D.existsSync(r))return;let n=await D.promises.readdir(r);for(let o of n){let c=o.replace(/_/g,"/").replace(".json","");if(t.test(c))await D.promises.unlink(f.join(r,o))}}async needsRevalidation(t){let r=await this.get(t);if(!r)return!0;return Date.now()>r.revalidateAfter}}async function Ut(t){let r=[];if(!t.isDynamic)r.push({url:t.pattern,params:{}});else{let n=await gt(t.filePath);if(n.kind==="error")throw Error(`getStaticPaths ${n.phase} failed for ${t.pattern} (${t.filePath}): ${n.error.message}`,{cause:n.error});if(n.kind==="absent")return console.warn(`Warning: Dynamic route ${t.pattern} (${t.filePath}) has no getStaticPaths`),r;let o=n.value;if(o.paths.length===0)return console.info(`getStaticPaths returned no paths for dynamic route ${t.pattern} (${t.filePath})`),r;for(let c of o.paths){let e=t.pattern;for(let[u,g]of Object.entries(c.params))e=e.replace(`:${u}`,g).replace(`:${u}*`,g);r.push({url:e,params:c.params,props:c.props,revalidate:c.revalidate})}}return r}function ft(t){return[t.replace(/\.stx$/,".data.ts"),t.replace(/\.stx$/,".data.js"),t+".data.ts",t+".data.js"]}async function Mt(t){for(let r of ft(t))if(await Bun.file(r).exists())try{let n=await import(r);if(typeof n.default==="function")return await n.default();else if(typeof n.default==="object")return n.default;else if(typeof n.getData==="function")return await n.getData();else{let{default:o,...c}=n;return c}}catch(n){console.error(`Error loading data file ${r}:`,n)}return null}async function Gt(t,r,n){let o=t.match(/<script\s+server\b[^>]*>([\s\S]*?)<\/script>/i);if(!o)return null;let c=o[1];if(!c.includes("getStaticProps"))return null;try{let e=c.match(/(?:export\s+)?(?:async\s+)?function\s+getStaticProps\s*\([^)]*\)\s*\{([\s\S]*?)\n\}/);if(!e)return null;return await Function("params",`
2
+ import"./chunk-7sh9fa3q.js";import{w,tl}from"./chunk-94gyfwpz.js";import"./chunk-gb65t4n1.js";import"./chunk-2yxva96k.js";import{Rt,S}from"./chunk-nzj7mkvm.js";import"./chunk-27rzdq3n.js";import"./chunk-wrd3aygb.js";import"./chunk-h0jnatd4.js";import{kt,_t,Ct,Et,Tt,$t}from"./chunk-q14d714d.js";import{a}from"./chunk-7wkz9sz5.js";import{Cs}from"./chunk-w9nwb8r3.js";import"./chunk-605b93pe.js";import"./chunk-npfs1zyn.js";import{he,en,tn}from"./chunk-e44zheax.js";import"./chunk-mqr61kqn.js";import{y}from"./chunk-d3pemcp8.js";import{yt,i}from"./chunk-vgtbds23.js";import"./chunk-vr6jccpy.js";import"./chunk-nrnkqqmb.js";import{ds}from"./chunk-8ycz8ss9.js";import"./chunk-992nsr70.js";import"./chunk-2gqhfge6.js";import{Ga,Ja,Ya}from"./chunk-d18xd9x5.js";import{Zt,Yn,Zn}from"./chunk-ndjmt3vg.js";import{Qt}from"./chunk-v6z3ak8h.js";import"./chunk-bm7xr4xh.js";import"./chunk-qv85c3qy.js";import{X,we}from"./chunk-40ambk0h.js";import"./chunk-w5hhqjwr.js";import"./chunk-0jp3tt5c.js";import{l}from"./chunk-jdj1358b.js";import{s,ge}from"./chunk-14ft0zc7.js";import D from"fs";import f from"path";import{createHash as vt}from"crypto";function Pt(t){try{return new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(t).replace(/\}(var |let |const |function )/g,"};$1").trim()}catch{return t}}var Dt=/<script\s+type="stx\/island"\s+data-stx-island="([^"]+)"([^>]*)>([\s\S]*?)<\/script>/g;function It(t){return Bun.hash(t).toString(16)}function ot(t,r={}){if(!t.includes('type="stx/island"'))return{html:t,chunks:[]};let n=new Map,o=t.replace(Dt,(e,u,g,v)=>{let x=v.trim();if(!x)return e;if(/\bdata-stx-src=/.test(g))return e;if(r.minify)x=Pt(x);let p=It(x);if(!n.has(p))n.set(p,x);let P=r.integrity?` data-stx-integrity="sha384-${vt("sha384").update(x).digest("base64")}"`:"";return`<script type="stx/island" data-stx-island="${u}" data-stx-src="/_stx/islands/${p}.js"${P}${g}></script>`}),c=Array.from(n,([e,u])=>({hash:e,code:u}));return{html:o,chunks:c}}var Bt=new Set(["visible","idle"]);function ct(t){if(!t.includes("data-stx-src="))return t;let r=new Map,n=/data-stx-scope="([^"]+)"[^>]*?stx-hydrate="([^"]+)"/g,o;while((o=n.exec(t))!==null)r.set(o[1],o[2]);let c=new Set,e=/data-stx-island="([^"]+)"[^>]*?data-stx-src="([^"]+)"/g,u;while((u=e.exec(t))!==null)if(Bt.has(r.get(u[1])||""))c.add(u[2]);let g=/<\/head\s*>/iy,v=S(t,(p,P)=>(g.lastIndex=P,g.exec(p)?g.lastIndex:-1))[0]?.start??-1;if(c.size===0||v===-1)return t;let x=Array.from(c).filter((p)=>!t.includes(`rel="prefetch" href="${p}"`)).map((p)=>`<link rel="prefetch" href="${p}" as="script">`).join("");if(!x)return t;return t.slice(0,v)+x+t.slice(v)}var jt=["STX_SITE_URL","SITE_URL","URL","VERCEL_URL","CF_PAGES_URL"];function K(t){let r=t.trim();if(!r)return null;let n=/^https?:\/\//i.test(r)?r:`https://${r}`;try{return new URL(n).origin+new URL(n).pathname.replace(/\/$/,"")}catch{return null}}function Ft(t){for(let r of jt){let n=t[r];if(!n)continue;let o=K(n);if(o)return{url:o,source:"env",via:r}}return null}function lt(t){if(!t||typeof t!=="object")return null;let r=t,n=r.site?.url??r.url??r.app?.url;return typeof n==="string"?K(n):null}async function At(t){let{existsSync:r}=await import("fs"),n=await import("path");for(let o of["site.config.ts","site.config.js",".config/site.config.ts"]){let c=n.resolve(t,o);if(!r(c))continue;try{let e=await import(c),u=lt(e.default??e);if(u)return u}catch{}}return null}async function ut(t={}){let r=t.cwd??process.cwd(),n=t.env??process.env;if(t.explicit){let u=K(t.explicit);if(u)return{url:u,source:"option"}}let o=lt(t.stxConfig);if(o)return{url:o,source:"stx.config",via:"site.url"};let c=await At(r);if(c)return{url:c,source:"site.config",via:"url"};let e=Ft(n);if(e)return e;return{url:"http://localhost",source:"fallback"}}function dt(){return["No site URL configured \u2014 sitemap.xml and robots.txt will point at http://localhost."," Set one in stx.config.ts (site: { url: 'https://example.com' }), in site.config.ts,"," via --domain, or with SITE_URL in the build environment."].join(`
3
+ `)}function q(t){return async()=>({paths:await t(),fallback:!1})}var Ot;function Lt(t){let r=s(t),{depths:n}=ge(r),o=/\b(?:async\s+)?function\s+getStaticPaths\s*\(/g,c;while((c=o.exec(r))!==null){if(n[c.index]!==0)continue;let u=w(r,"(",")",o.lastIndex-1),g=r.indexOf("{",u+1),v=w(r,"{","}",g);if(u<0||g<0||v<0)break;return t.slice(c.index,v+1)}let e=/\b(?:const|let|var)\s+getStaticPaths\s*=/g;while((c=e.exec(r))!==null){if(n[c.index]!==0)continue;let u=tl(r,e.lastIndex).endPos;return t.slice(e.lastIndex,u).trim()}throw SyntaxError("Could not extract getStaticPaths; use a top-level function or const declaration")}async function gt(t){let r="read";try{let n=await Bun.file(t).text();r="parse";let o=Qt(n),c=[...o.server,...o.client,...o.signals].filter((e)=>/(?:^|\s)server(?:\s|=|$)/i.test(s(e.attrs))).sort((e,u)=>n.indexOf(e.fullTag)-n.indexOf(u.fullTag));for(let e of c){if(!/\bgetStaticPaths\b/.test(s(e.content)))continue;let u=(Ot??=new Bun.Transpiler({loader:"ts",target:"bun"})).transformSync(e.content);if(!/\bgetStaticPaths\b/.test(s(u)))continue;let g=Lt(u);if(/\bdefineStaticPaths\b/.test(s(g))&&Rt(u,"defineStaticPaths"))throw SyntaxError("Cannot evaluate a module-local defineStaticPaths binding during isolated hook extraction");r="execute";let v=Function("defineStaticPaths",`return (${g})`)(q);if(typeof v!=="function")throw TypeError("getStaticPaths must be a function");let x=await v();r="result";let p=Array.isArray(x)?{paths:x}:x;if(!p||typeof p!=="object"||!("paths"in p)||!Array.isArray(p.paths))throw TypeError("getStaticPaths must return { paths: [...] } or an array of paths");for(let P of p.paths)if(!P||typeof P!=="object"||!P.params||typeof P.params!=="object"||Array.isArray(P.params))throw TypeError("Each getStaticPaths path must contain a params object");return{kind:"ok",value:p}}return{kind:"absent"}}catch(n){return{kind:"error",phase:r,error:n instanceof Error?n:Error(String(n))}}}class pt{cacheDir;cache=new Map;loaded=!1;salt;constructor(t,r=""){this.cacheDir=t,this.salt=r}async load(){if(this.loaded)return;let t=f.join(this.cacheDir,"build-cache.json");if(await Bun.file(t).exists())try{let r=JSON.parse(await Bun.file(t).text());for(let[n,o]of Object.entries(r))this.cache.set(n,o)}catch{}this.loaded=!0}async save(){await D.promises.mkdir(this.cacheDir,{recursive:!0});let t=f.join(this.cacheDir,"build-cache.json"),r={};for(let[n,o]of this.cache)r[n]=o;await Bun.write(t,JSON.stringify(r))}getHash(t,r){let n=D.statSync(t),o=`${this.salt}|${t}:${n.mtimeMs}`;for(let e of r)if(D.existsSync(e)){let u=D.statSync(e);o+=`:${e}:${u.mtimeMs}`}let c=0;for(let e=0;e<o.length;e++){let u=o.charCodeAt(e);c=(c<<5)-c+u,c=c&c}return Math.abs(c).toString(36)}get(t,r){let n=this.cache.get(t);if(!n)return null;let o=ft(r).some((u)=>D.existsSync(u)),c=[r,...n.dependencies??[]].some((u)=>u.endsWith(".stx")&&D.existsSync(u)&&ds(D.readFileSync(u,"utf8")).some((g)=>/\bserver\b/.test(g.attrs)));if(o||c)return this.cache.delete(t),null;let e=this.getHash(r,n.dependencies??[]);if(n.hash!==e)return this.cache.delete(t),null;return n.html}set(t,r,n,o){let c=this.getHash(r,n);this.cache.set(t,{hash:c,html:o,generatedAt:Date.now(),dependencies:n})}}class ht{cacheDir;constructor(t){this.cacheDir=t}getFilePath(t){let r=t.replace(/[^a-zA-Z0-9]/g,"_")+".json";return f.join(this.cacheDir,"isr",r)}async get(t){let r=this.getFilePath(t);if(!await Bun.file(r).exists())return null;try{return JSON.parse(await Bun.file(r).text())}catch{return null}}async set(t,r){let n=this.getFilePath(t);await D.promises.mkdir(f.dirname(n),{recursive:!0}),await Bun.write(n,JSON.stringify(r))}async invalidate(t){let r=this.getFilePath(t);if(await Bun.file(r).exists())await D.promises.unlink(r)}async invalidatePattern(t){let r=f.join(this.cacheDir,"isr");if(!D.existsSync(r))return;let n=await D.promises.readdir(r);for(let o of n){let c=o.replace(/_/g,"/").replace(".json","");if(t.test(c))await D.promises.unlink(f.join(r,o))}}async needsRevalidation(t){let r=await this.get(t);if(!r)return!0;return Date.now()>r.revalidateAfter}}async function Ut(t){let r=[];if(!t.isDynamic)r.push({url:t.pattern,params:{}});else{let n=await gt(t.filePath);if(n.kind==="error")throw Error(`getStaticPaths ${n.phase} failed for ${t.pattern} (${t.filePath}): ${n.error.message}`,{cause:n.error});if(n.kind==="absent")return console.warn(`Warning: Dynamic route ${t.pattern} (${t.filePath}) has no getStaticPaths`),r;let o=n.value;if(o.paths.length===0)return console.info(`getStaticPaths returned no paths for dynamic route ${t.pattern} (${t.filePath})`),r;for(let c of o.paths){let e=t.pattern;for(let[u,g]of Object.entries(c.params))e=e.replace(`:${u}`,g).replace(`:${u}*`,g);r.push({url:e,params:c.params,props:c.props,revalidate:c.revalidate})}}return r}function ft(t){return[t.replace(/\.stx$/,".data.ts"),t.replace(/\.stx$/,".data.js"),t+".data.ts",t+".data.js"]}async function Mt(t){for(let r of ft(t))if(await Bun.file(r).exists())try{let n=await import(r);if(typeof n.default==="function")return await n.default();else if(typeof n.default==="object")return n.default;else if(typeof n.getData==="function")return await n.getData();else{let{default:o,...c}=n;return c}}catch(n){console.error(`Error loading data file ${r}:`,n)}return null}async function Gt(t,r,n){let o=t.match(/<script\s+server\b[^>]*>([\s\S]*?)<\/script>/i);if(!o)return null;let c=o[1];if(!c.includes("getStaticProps"))return null;try{let e=c.match(/(?:export\s+)?(?:async\s+)?function\s+getStaticProps\s*\([^)]*\)\s*\{([\s\S]*?)\n\}/);if(!e)return null;return await Function("params",`
4
4
  return (async function getStaticProps() {
5
5
  ${e[1]}
6
6
  })()
@@ -37,7 +37,7 @@ ${t.map((o)=>{let c=new URL(o.loc,r).href,e=` <url>
37
37
  ${n.join(`
38
38
  `)}
39
39
  </channel>
40
- </rss>`}async function Vt(t={}){let r=Date.now();tn();let n=await a(process.cwd()),o=n.build||{},c=await ut({explicit:t.domain||o.domain,stxConfig:n});if(c.source==="fallback"&&(t.sitemap??o.sitemap??!0))console.warn(dt());let e={router:t.router??n?.router??{},pagesDir:t.pagesDir||o.pagesDir||"pages",outputDir:t.outputDir||o.outputDir||"dist",baseUrl:t.baseUrl||o.baseUrl||"/",domain:c.url,revalidate:t.revalidate??o.revalidate??!1,sitemap:t.sitemap??o.sitemap??!0,sitemapExclude:t.sitemapExclude||o.sitemapExclude||[],robots:t.robots??o.robots??!0,rss:t.rss??o.rss??!1,concurrency:t.concurrency||o.concurrency||10,cache:t.cache??o.cache??!0,cacheDir:t.cacheDir||o.cacheDir||l(process.cwd(),"ssg-cache"),contentLoaders:t.contentLoaders||[],hooks:t.hooks||{},minify:t.minify??o.minify??!0,generate404:t.generate404??o.generate404??!0,publicDir:t.publicDir||o.publicDir||"public",trailingSlash:t.trailingSlash??o.trailingSlash??!1,cleanOutput:t.cleanOutput??o.cleanOutput??!0,cacheSalt:t.cacheSalt??"",partialsDir:t.partialsDir||n?.partialsDir||"",componentsDir:t.componentsDir||n?.componentsDir||"",failOnIncludeError:t.failOnIncludeError??!0,failOnServerScriptError:t.failOnServerScriptError??!0,chunkIslands:t.chunkIslands===!0,prefetchIslands:t.prefetchIslands===!0,integrityIslands:t.integrityIslands===!0},u={totalPages:0,successCount:0,failedCount:0,cachedCount:0,buildTime:0,pages:[],errors:[]},g=new Set,v=0,x={},p={};await e.hooks.onBuildStart?.();try{if(e.cleanOutput&&D.existsSync(e.outputDir))await D.promises.rm(e.outputDir,{recursive:!0});await D.promises.mkdir(e.outputDir,{recursive:!0});let E=e.cacheSalt;if(!E){let{resolveUserCssConfig:d,fingerprintConfig:m}=await import("./chunk-7k27y6z1.js");try{E=m(await d(process.cwd()))}catch{}}let{prepareImageDelivery:b}=await import("./chunk-kzn32p5w.js"),R=await b(e.publicDir,e.outputDir);if(R.count>0)console.log(`Optimized ${R.count} image(s) for responsive delivery`),E=[E,R.fingerprint].filter(Boolean).join(":");let T=new pt(e.cacheDir,E);if(e.cache)await T.load();try{let{generateCss:d}=await import("./chunk-7k27y6z1.js");await d('<div class="bg-black"></div>')}catch{}kt();let wt=n?.routeMiddleware?.dir||"middleware";await Ct(process.cwd(),wt);let J=_t();if(J.length>0)console.log(`Loaded ${J.length} middleware: ${J.join(", ")}`);let St=n?.routeMiddleware?.global||[];Ya(n?.layoutsDir,l(process.cwd()));let Z=X(".",{pagesDir:e.pagesDir,pagesDirs:n?._layerPageDirs});console.log(`Found ${Z.length} routes`);let M=[];for(let d of Z)try{let m=await Ut(d);for(let k of m)M.push({route:d,url:k.url,params:k.params,props:k.props,revalidate:k.revalidate??e.revalidate})}catch(m){let k=m instanceof Error?m:Error(String(m));u.failedCount++,u.errors.push({route:d.pattern,error:k}),await e.hooks.onError?.(k,d.pattern),console.error(`Error discovering paths for ${d.pattern}:`,k)}u.totalPages=M.length+u.failedCount,console.log(`Generating ${M.length} pages...`);let _=[],Q=[];for(let d=0;d<M.length;d+=e.concurrency)Q.push(M.slice(d,d+e.concurrency));for(let d of Q)await Promise.all(d.map(async(m)=>{let{route:k,url:h,params:G,props:xt,revalidate:rt}=m;try{await e.hooks.onPageStart?.(h);let A=await Bun.file(k.filePath).text(),O=Yt(A),bt=O?.middleware?Array.isArray(O.middleware)?O.middleware:[O.middleware]:[],nt=[...St,...bt];if(nt.length>0){let B=Et(h,G,O||{}),L=Tt(B,null,void 0,{isServer:!0}),j=await $t(nt,L);if(j.redirect){let C=typeof j.redirect==="string"?j.redirect:j.redirect.path||j.redirect,H=te(String(C),h),U=ee(h,e);await D.promises.mkdir(f.dirname(U),{recursive:!0}),await Bun.write(U,H),u.successCount++,u.pages.push({route:h,outputPath:U,size:Buffer.byteLength(H),cached:!1}),_.push({loc:h,lastmod:new Date().toISOString()}),console.log(` \u21B3 ${h} \u2192 redirect to ${C}`);return}if(j.abort){let C=typeof j.abort==="string"?j.abort:j.abort?.error?.message||"aborted";console.warn(` \u21B3 ${h} \u2014 middleware aborted: ${C}`);return}}let it=A.match(/definePageMeta\s*\(\s*\{[\s\S]*?validate\s*:\s*((?:\([^)]*\)|[^,}])*(?:\{[\s\S]*?\})?)/m);if(it)try{if(!await Function("route",`
40
+ </rss>`}async function Vt(t={}){let r=Date.now();tn();let n=await a(process.cwd()),o=n.build||{},c=await ut({explicit:t.domain||o.domain,stxConfig:n});if(c.source==="fallback"&&(t.sitemap??o.sitemap??!0))console.warn(dt());let e={router:t.router??n?.router??{},pagesDir:t.pagesDir||o.pagesDir||"pages",outputDir:t.outputDir||o.outputDir||"dist",baseUrl:t.baseUrl||o.baseUrl||"/",domain:c.url,revalidate:t.revalidate??o.revalidate??!1,sitemap:t.sitemap??o.sitemap??!0,sitemapExclude:t.sitemapExclude||o.sitemapExclude||[],robots:t.robots??o.robots??!0,rss:t.rss??o.rss??!1,concurrency:t.concurrency||o.concurrency||10,cache:t.cache??o.cache??!0,cacheDir:t.cacheDir||o.cacheDir||l(process.cwd(),"ssg-cache"),contentLoaders:t.contentLoaders||[],hooks:t.hooks||{},minify:t.minify??o.minify??!0,generate404:t.generate404??o.generate404??!0,publicDir:t.publicDir||o.publicDir||"public",trailingSlash:t.trailingSlash??o.trailingSlash??!1,cleanOutput:t.cleanOutput??o.cleanOutput??!0,cacheSalt:t.cacheSalt??"",partialsDir:t.partialsDir||n?.partialsDir||"",componentsDir:t.componentsDir||n?.componentsDir||"",failOnIncludeError:t.failOnIncludeError??!0,failOnServerScriptError:t.failOnServerScriptError??!0,chunkIslands:t.chunkIslands===!0,prefetchIslands:t.prefetchIslands===!0,integrityIslands:t.integrityIslands===!0},u={totalPages:0,successCount:0,failedCount:0,cachedCount:0,buildTime:0,pages:[],errors:[]},g=new Set,v=0,x={},p={};await e.hooks.onBuildStart?.();try{if(e.cleanOutput&&D.existsSync(e.outputDir))await D.promises.rm(e.outputDir,{recursive:!0});await D.promises.mkdir(e.outputDir,{recursive:!0});let E=e.cacheSalt;if(!E){let{resolveUserCssConfig:d,fingerprintConfig:m}=await import("./chunk-9th217rf.js");try{E=m(await d(process.cwd()))}catch{}}let{prepareImageDelivery:b}=await import("./chunk-k7w05cjv.js"),R=await b(e.publicDir,e.outputDir);if(R.count>0)console.log(`Optimized ${R.count} image(s) for responsive delivery`),E=[E,R.fingerprint].filter(Boolean).join(":");let T=new pt(e.cacheDir,E);if(e.cache)await T.load();try{let{generateCss:d}=await import("./chunk-9th217rf.js");await d('<div class="bg-black"></div>')}catch{}kt();let wt=n?.routeMiddleware?.dir||"middleware";await Ct(process.cwd(),wt);let J=_t();if(J.length>0)console.log(`Loaded ${J.length} middleware: ${J.join(", ")}`);let St=n?.routeMiddleware?.global||[];Ya(n?.layoutsDir,l(process.cwd()));let Z=X(".",{pagesDir:e.pagesDir,pagesDirs:n?._layerPageDirs});console.log(`Found ${Z.length} routes`);let M=[];for(let d of Z)try{let m=await Ut(d);for(let k of m)M.push({route:d,url:k.url,params:k.params,props:k.props,revalidate:k.revalidate??e.revalidate})}catch(m){let k=m instanceof Error?m:Error(String(m));u.failedCount++,u.errors.push({route:d.pattern,error:k}),await e.hooks.onError?.(k,d.pattern),console.error(`Error discovering paths for ${d.pattern}:`,k)}u.totalPages=M.length+u.failedCount,console.log(`Generating ${M.length} pages...`);let _=[],Q=[];for(let d=0;d<M.length;d+=e.concurrency)Q.push(M.slice(d,d+e.concurrency));for(let d of Q)await Promise.all(d.map(async(m)=>{let{route:k,url:h,params:G,props:xt,revalidate:rt}=m;try{await e.hooks.onPageStart?.(h);let A=await Bun.file(k.filePath).text(),O=Yt(A),bt=O?.middleware?Array.isArray(O.middleware)?O.middleware:[O.middleware]:[],nt=[...St,...bt];if(nt.length>0){let B=Et(h,G,O||{}),L=Tt(B,null,void 0,{isServer:!0}),j=await $t(nt,L);if(j.redirect){let C=typeof j.redirect==="string"?j.redirect:j.redirect.path||j.redirect,H=te(String(C),h),U=ee(h,e);await D.promises.mkdir(f.dirname(U),{recursive:!0}),await Bun.write(U,H),u.successCount++,u.pages.push({route:h,outputPath:U,size:Buffer.byteLength(H),cached:!1}),_.push({loc:h,lastmod:new Date().toISOString()}),console.log(` \u21B3 ${h} \u2192 redirect to ${C}`);return}if(j.abort){let C=typeof j.abort==="string"?j.abort:j.abort?.error?.message||"aborted";console.warn(` \u21B3 ${h} \u2014 middleware aborted: ${C}`);return}}let it=A.match(/definePageMeta\s*\(\s*\{[\s\S]*?validate\s*:\s*((?:\([^)]*\)|[^,}])*(?:\{[\s\S]*?\})?)/m);if(it)try{if(!await Function("route",`
41
41
  const validate = ${it[1]};
42
42
  return validate(route);
43
43
  `)({params:G})){console.warn(`Validation failed for ${h}, skipping...`);return}}catch{}let I=null,st=!1;if(e.cache){if(I=T.get(h,k.filePath),I)st=!0,u.cachedCount++}if(!I){let B=await mt(k,G,xt,e,n);if(I=B.html,e.failOnIncludeError&&B.includeFailures.length>0)throw Error(`${B.includeFailures.length} include(s) failed to resolve, so this page would have shipped with an error banner where the markup should be: