@absolutejs/absolute 0.19.0-beta.807 → 0.19.0-beta.809

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 (260) hide show
  1. package/dist/angular/browser.js +9801 -57
  2. package/dist/angular/browser.js.map +246 -4
  3. package/dist/angular/components/core/streamingSlotRegistrar.js +1 -1
  4. package/dist/angular/components/core/streamingSlotRegistry.js +2 -2
  5. package/dist/angular/index.js +14877 -60
  6. package/dist/angular/index.js.map +281 -4
  7. package/dist/angular/server.js +5610 -45
  8. package/dist/angular/server.js.map +51 -3
  9. package/dist/build.js +18092 -45
  10. package/dist/build.js.map +99 -3
  11. package/dist/cli/index.js +317 -86
  12. package/dist/client/index.js +1091 -70
  13. package/dist/client/index.js.map +24 -4
  14. package/dist/core/streamingSlotRegistrar.js +108 -11
  15. package/dist/core/streamingSlotRegistrar.js.map +4 -3
  16. package/dist/core/streamingSlotRegistry.js +169 -7
  17. package/dist/core/streamingSlotRegistry.js.map +5 -3
  18. package/dist/index.js +19957 -547
  19. package/dist/index.js.map +116 -3
  20. package/dist/islands/browser.js +228 -9
  21. package/dist/islands/browser.js.map +9 -4
  22. package/dist/islands/index.js +1908 -17
  23. package/dist/islands/index.js.map +27 -3
  24. package/dist/react/browser.js +328 -12
  25. package/dist/react/browser.js.map +12 -4
  26. package/dist/react/components/index.js +167 -16
  27. package/dist/react/components/index.js.map +6 -3
  28. package/dist/react/hooks/index.js +183 -8
  29. package/dist/react/hooks/index.js.map +7 -3
  30. package/dist/react/index.js +3627 -36
  31. package/dist/react/index.js.map +45 -4
  32. package/dist/react/jsxDevRuntimeCompat.js +61 -2
  33. package/dist/react/jsxDevRuntimeCompat.js.map +2 -2
  34. package/dist/react/server.js +1789 -18
  35. package/dist/react/server.js.map +21 -3
  36. package/dist/src/angular/injectorPatch.d.ts +1 -0
  37. package/dist/src/angular/islands.d.ts +1 -0
  38. package/dist/src/client/hydrators/react.d.ts +3 -0
  39. package/dist/src/client/hydrators/svelte.d.ts +2 -0
  40. package/dist/src/client/hydrators/vue.d.ts +2 -0
  41. package/dist/src/index.d.ts +1 -0
  42. package/dist/svelte/browser.js +247 -12
  43. package/dist/svelte/browser.js.map +10 -3
  44. package/dist/svelte/index.js +3732 -37
  45. package/dist/svelte/index.js.map +47 -4
  46. package/dist/svelte/server.js +2794 -21
  47. package/dist/svelte/server.js.map +27 -3
  48. package/dist/vue/browser.js +348 -12
  49. package/dist/vue/browser.js.map +12 -4
  50. package/dist/vue/components/Image.js +240 -7
  51. package/dist/vue/components/Image.js.map +6 -3
  52. package/dist/vue/components/index.js +544 -11
  53. package/dist/vue/components/index.js.map +9 -3
  54. package/dist/vue/index.js +4212 -52
  55. package/dist/vue/index.js.map +50 -4
  56. package/dist/vue/server.js +1849 -18
  57. package/dist/vue/server.js.map +21 -3
  58. package/package.json +1 -1
  59. package/dist/chunk-0867j0r0.js +0 -136
  60. package/dist/chunk-0867j0r0.js.map +0 -10
  61. package/dist/chunk-102fp7xe.js +0 -63
  62. package/dist/chunk-102fp7xe.js.map +0 -10
  63. package/dist/chunk-11zpfqz6.js +0 -19
  64. package/dist/chunk-11zpfqz6.js.map +0 -10
  65. package/dist/chunk-1rfh7hw9.js +0 -319
  66. package/dist/chunk-1rfh7hw9.js.map +0 -11
  67. package/dist/chunk-1x4fxm57.js +0 -51
  68. package/dist/chunk-1x4fxm57.js.map +0 -9
  69. package/dist/chunk-25v9t56f.js +0 -29
  70. package/dist/chunk-25v9t56f.js.map +0 -11
  71. package/dist/chunk-2f21eenc.js +0 -21
  72. package/dist/chunk-2f21eenc.js.map +0 -10
  73. package/dist/chunk-2ga2znex.js +0 -13
  74. package/dist/chunk-2ga2znex.js.map +0 -9
  75. package/dist/chunk-30yrw0f6.js +0 -33
  76. package/dist/chunk-30yrw0f6.js.map +0 -10
  77. package/dist/chunk-3g91wb4f.js +0 -358
  78. package/dist/chunk-3g91wb4f.js.map +0 -10
  79. package/dist/chunk-3rea1gam.js +0 -4403
  80. package/dist/chunk-3rea1gam.js.map +0 -28
  81. package/dist/chunk-3yjzpcne.js +0 -34
  82. package/dist/chunk-3yjzpcne.js.map +0 -10
  83. package/dist/chunk-41bf6aqt.js +0 -17
  84. package/dist/chunk-41bf6aqt.js.map +0 -9
  85. package/dist/chunk-4d39r92n.js +0 -81
  86. package/dist/chunk-4d39r92n.js.map +0 -10
  87. package/dist/chunk-5003emhv.js +0 -17
  88. package/dist/chunk-5003emhv.js.map +0 -10
  89. package/dist/chunk-5f67rsed.js +0 -466
  90. package/dist/chunk-5f67rsed.js.map +0 -10
  91. package/dist/chunk-5fhp1jap.js +0 -9169
  92. package/dist/chunk-5fhp1jap.js.map +0 -236
  93. package/dist/chunk-629x0yh4.js +0 -20
  94. package/dist/chunk-629x0yh4.js.map +0 -9
  95. package/dist/chunk-6pdj08z3.js +0 -73
  96. package/dist/chunk-6pdj08z3.js.map +0 -12
  97. package/dist/chunk-6qjbrt0k.js +0 -13
  98. package/dist/chunk-6qjbrt0k.js.map +0 -9
  99. package/dist/chunk-6sccb4jr.js +0 -14
  100. package/dist/chunk-6sccb4jr.js.map +0 -9
  101. package/dist/chunk-798spvzv.js +0 -50
  102. package/dist/chunk-798spvzv.js.map +0 -10
  103. package/dist/chunk-7fw6x3js.js +0 -131
  104. package/dist/chunk-7fw6x3js.js.map +0 -11
  105. package/dist/chunk-7kjj42xm.js +0 -11
  106. package/dist/chunk-7kjj42xm.js.map +0 -10
  107. package/dist/chunk-7mtstdqn.js +0 -90
  108. package/dist/chunk-7mtstdqn.js.map +0 -10
  109. package/dist/chunk-851whwc7.js +0 -17
  110. package/dist/chunk-851whwc7.js.map +0 -10
  111. package/dist/chunk-85n68sy6.js +0 -103
  112. package/dist/chunk-85n68sy6.js.map +0 -10
  113. package/dist/chunk-8kcfffry.js +0 -35
  114. package/dist/chunk-8kcfffry.js.map +0 -10
  115. package/dist/chunk-92fsjfpp.js +0 -1731
  116. package/dist/chunk-92fsjfpp.js.map +0 -11
  117. package/dist/chunk-93sqk7be.js +0 -139
  118. package/dist/chunk-93sqk7be.js.map +0 -12
  119. package/dist/chunk-9c5tj4k3.js +0 -130
  120. package/dist/chunk-9c5tj4k3.js.map +0 -10
  121. package/dist/chunk-9j59emg3.js +0 -184
  122. package/dist/chunk-9j59emg3.js.map +0 -11
  123. package/dist/chunk-9ve9jq72.js +0 -203
  124. package/dist/chunk-9ve9jq72.js.map +0 -10
  125. package/dist/chunk-9xrsjeem.js +0 -12
  126. package/dist/chunk-9xrsjeem.js.map +0 -9
  127. package/dist/chunk-a9mvyp04.js +0 -87
  128. package/dist/chunk-a9mvyp04.js.map +0 -10
  129. package/dist/chunk-b3gbnrwe.js +0 -21
  130. package/dist/chunk-b3gbnrwe.js.map +0 -10
  131. package/dist/chunk-bgb8k1qs.js +0 -672
  132. package/dist/chunk-bgb8k1qs.js.map +0 -15
  133. package/dist/chunk-bmgqm774.js +0 -65
  134. package/dist/chunk-bmgqm774.js.map +0 -9
  135. package/dist/chunk-bxfghpma.js +0 -69
  136. package/dist/chunk-bxfghpma.js.map +0 -10
  137. package/dist/chunk-c1jfjnka.js +0 -74
  138. package/dist/chunk-c1jfjnka.js.map +0 -10
  139. package/dist/chunk-cbkrwmvh.js +0 -80
  140. package/dist/chunk-cbkrwmvh.js.map +0 -10
  141. package/dist/chunk-cdxd7sy2.js +0 -71
  142. package/dist/chunk-cdxd7sy2.js.map +0 -10
  143. package/dist/chunk-cg95827x.js +0 -21
  144. package/dist/chunk-cg95827x.js.map +0 -10
  145. package/dist/chunk-cm0g4q6w.js +0 -149
  146. package/dist/chunk-cm0g4q6w.js.map +0 -10
  147. package/dist/chunk-d7mwkzry.js +0 -261
  148. package/dist/chunk-d7mwkzry.js.map +0 -10
  149. package/dist/chunk-d9c0am65.js +0 -12
  150. package/dist/chunk-d9c0am65.js.map +0 -10
  151. package/dist/chunk-daqghmg8.js +0 -12
  152. package/dist/chunk-daqghmg8.js.map +0 -9
  153. package/dist/chunk-e3r9fxaa.js +0 -149
  154. package/dist/chunk-e3r9fxaa.js.map +0 -10
  155. package/dist/chunk-e8eecyrq.js +0 -244
  156. package/dist/chunk-e8eecyrq.js.map +0 -10
  157. package/dist/chunk-ex2hxe0v.js +0 -160
  158. package/dist/chunk-ex2hxe0v.js.map +0 -11
  159. package/dist/chunk-fak944et.js +0 -91
  160. package/dist/chunk-fak944et.js.map +0 -10
  161. package/dist/chunk-fygx2ymm.js +0 -118
  162. package/dist/chunk-fygx2ymm.js.map +0 -12
  163. package/dist/chunk-g15qj669.js +0 -271
  164. package/dist/chunk-g15qj669.js.map +0 -11
  165. package/dist/chunk-gd6wmknh.js +0 -121
  166. package/dist/chunk-gd6wmknh.js.map +0 -11
  167. package/dist/chunk-gf0ygptk.js +0 -85
  168. package/dist/chunk-gf0ygptk.js.map +0 -11
  169. package/dist/chunk-gytkmthr.js +0 -220
  170. package/dist/chunk-gytkmthr.js.map +0 -10
  171. package/dist/chunk-h5bbfn3n.js +0 -28
  172. package/dist/chunk-h5bbfn3n.js.map +0 -11
  173. package/dist/chunk-h6mye9r3.js +0 -93
  174. package/dist/chunk-h6mye9r3.js.map +0 -10
  175. package/dist/chunk-hcsmxw1v.js +0 -85
  176. package/dist/chunk-hcsmxw1v.js.map +0 -10
  177. package/dist/chunk-hyjs4bqs.js +0 -8
  178. package/dist/chunk-hyjs4bqs.js.map +0 -10
  179. package/dist/chunk-jn91vzkh.js +0 -66
  180. package/dist/chunk-jn91vzkh.js.map +0 -10
  181. package/dist/chunk-jpkjdgsk.js +0 -167
  182. package/dist/chunk-jpkjdgsk.js.map +0 -11
  183. package/dist/chunk-jwxt8gnp.js +0 -13
  184. package/dist/chunk-jwxt8gnp.js.map +0 -9
  185. package/dist/chunk-kk8w9rh5.js +0 -195
  186. package/dist/chunk-kk8w9rh5.js.map +0 -10
  187. package/dist/chunk-kwgh8rmg.js +0 -426
  188. package/dist/chunk-kwgh8rmg.js.map +0 -14
  189. package/dist/chunk-m97ze5hz.js +0 -46
  190. package/dist/chunk-m97ze5hz.js.map +0 -10
  191. package/dist/chunk-mbazhahf.js +0 -60
  192. package/dist/chunk-mbazhahf.js.map +0 -10
  193. package/dist/chunk-mgfwq18r.js +0 -15
  194. package/dist/chunk-mgfwq18r.js.map +0 -9
  195. package/dist/chunk-mtgf69xn.js +0 -88
  196. package/dist/chunk-mtgf69xn.js.map +0 -10
  197. package/dist/chunk-mtxzyxpg.js +0 -102
  198. package/dist/chunk-mtxzyxpg.js.map +0 -10
  199. package/dist/chunk-nehhtthw.js +0 -225
  200. package/dist/chunk-nehhtthw.js.map +0 -10
  201. package/dist/chunk-p5504p14.js +0 -16
  202. package/dist/chunk-p5504p14.js.map +0 -10
  203. package/dist/chunk-p5zgj77m.js +0 -184
  204. package/dist/chunk-p5zgj77m.js.map +0 -10
  205. package/dist/chunk-pnscgw95.js +0 -90
  206. package/dist/chunk-pnscgw95.js.map +0 -10
  207. package/dist/chunk-pvpp4pvs.js +0 -17
  208. package/dist/chunk-pvpp4pvs.js.map +0 -10
  209. package/dist/chunk-qh75agse.js +0 -95
  210. package/dist/chunk-qh75agse.js.map +0 -10
  211. package/dist/chunk-qxq2zcty.js +0 -52
  212. package/dist/chunk-qxq2zcty.js.map +0 -10
  213. package/dist/chunk-r6e8pytx.js +0 -22
  214. package/dist/chunk-r6e8pytx.js.map +0 -9
  215. package/dist/chunk-r7jmgqnw.js +0 -114
  216. package/dist/chunk-r7jmgqnw.js.map +0 -10
  217. package/dist/chunk-s6defjk2.js +0 -116
  218. package/dist/chunk-s6defjk2.js.map +0 -10
  219. package/dist/chunk-sd39p726.js +0 -619
  220. package/dist/chunk-sd39p726.js.map +0 -10
  221. package/dist/chunk-swrnzs4c.js +0 -63
  222. package/dist/chunk-swrnzs4c.js.map +0 -10
  223. package/dist/chunk-tfe3sb44.js +0 -33
  224. package/dist/chunk-tfe3sb44.js.map +0 -10
  225. package/dist/chunk-tjr0kcev.js +0 -41
  226. package/dist/chunk-tjr0kcev.js.map +0 -9
  227. package/dist/chunk-tx9edm1x.js +0 -34
  228. package/dist/chunk-tx9edm1x.js.map +0 -10
  229. package/dist/chunk-txhm2vb5.js +0 -18
  230. package/dist/chunk-txhm2vb5.js.map +0 -9
  231. package/dist/chunk-v5vmsxmy.js +0 -526
  232. package/dist/chunk-v5vmsxmy.js.map +0 -12
  233. package/dist/chunk-vjhxm8n2.js +0 -29
  234. package/dist/chunk-vjhxm8n2.js.map +0 -9
  235. package/dist/chunk-vkrpm7kc.js +0 -247
  236. package/dist/chunk-vkrpm7kc.js.map +0 -12
  237. package/dist/chunk-w3m4m5we.js +0 -4925
  238. package/dist/chunk-w3m4m5we.js.map +0 -12
  239. package/dist/chunk-wrxtn9ve.js +0 -18
  240. package/dist/chunk-wrxtn9ve.js.map +0 -10
  241. package/dist/chunk-x09cskqd.js +0 -377
  242. package/dist/chunk-x09cskqd.js.map +0 -10
  243. package/dist/chunk-xnt8c6h2.js +0 -576
  244. package/dist/chunk-xnt8c6h2.js.map +0 -10
  245. package/dist/chunk-xw0tx842.js +0 -13
  246. package/dist/chunk-xw0tx842.js.map +0 -9
  247. package/dist/chunk-xx5b6b9m.js +0 -69
  248. package/dist/chunk-xx5b6b9m.js.map +0 -10
  249. package/dist/chunk-xz1kdswj.js +0 -21
  250. package/dist/chunk-xz1kdswj.js.map +0 -9
  251. package/dist/chunk-y84qnsd3.js +0 -32
  252. package/dist/chunk-y84qnsd3.js.map +0 -10
  253. package/dist/chunk-ywjn0rad.js +0 -14
  254. package/dist/chunk-ywjn0rad.js.map +0 -9
  255. package/dist/chunk-z9nvhm6r.js +0 -13
  256. package/dist/chunk-z9nvhm6r.js.map +0 -9
  257. package/dist/chunk-zhmvdpk6.js +0 -15
  258. package/dist/chunk-zhmvdpk6.js.map +0 -9
  259. package/dist/chunk-zrg9d4zw.js +0 -784
  260. package/dist/chunk-zrg9d4zw.js.map +0 -10
package/dist/vue/index.js CHANGED
@@ -1,54 +1,4074 @@
1
1
  // @bun
2
+ var __create = Object.create;
3
+ var __getProtoOf = Object.getPrototypeOf;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ function __accessProp(key) {
8
+ return this[key];
9
+ }
10
+ var __toESMCache_node;
11
+ var __toESMCache_esm;
12
+ var __toESM = (mod, isNodeMode, target) => {
13
+ var canCache = mod != null && typeof mod === "object";
14
+ if (canCache) {
15
+ var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
16
+ var cached = cache.get(mod);
17
+ if (cached)
18
+ return cached;
19
+ }
20
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
21
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
22
+ for (let key of __getOwnPropNames(mod))
23
+ if (!__hasOwnProp.call(to, key))
24
+ __defProp(to, key, {
25
+ get: __accessProp.bind(mod, key),
26
+ enumerable: true
27
+ });
28
+ if (canCache)
29
+ cache.set(mod, to);
30
+ return to;
31
+ };
32
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
33
+ var __returnValue = (v) => v;
34
+ function __exportSetter(name, newValue) {
35
+ this[name] = __returnValue.bind(null, newValue);
36
+ }
37
+ var __export = (target, all) => {
38
+ for (var name in all)
39
+ __defProp(target, name, {
40
+ get: all[name],
41
+ enumerable: true,
42
+ configurable: true,
43
+ set: __exportSetter.bind(all, name)
44
+ });
45
+ };
46
+ var __legacyDecorateClassTS = function(decorators, target, key, desc) {
47
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
48
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
49
+ r = Reflect.decorate(decorators, target, key, desc);
50
+ else
51
+ for (var i = decorators.length - 1;i >= 0; i--)
52
+ if (d = decorators[i])
53
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
54
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
55
+ };
56
+ var __legacyMetadataTS = (k, v) => {
57
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
58
+ return Reflect.metadata(k, v);
59
+ };
60
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
61
+ var __require = import.meta.require;
62
+
63
+ // src/constants.ts
64
+ var ANGULAR_INIT_TIMEOUT_MS = 500, ANSI_ESCAPE_CODE = 27, ANSI_ESCAPE_LENGTH = 3, ASCII_SPACE = 32, BASE_36_RADIX = 36, BUN_BUILD_WARNING_SUPPRESSION = "wildcard sideEffects are not supported yet", BODY_SLICE_LENGTH = 2000, BYTES_PER_KILOBYTE = 1024, CLI_ARGS_OFFSET = 3, CSS_ERROR_RESOLVE_DELAY_MS = 50, CSS_MAX_CHECK_ATTEMPTS = 10, CSS_MAX_PARSE_TIMEOUT_MS = 500, CSS_SHEET_READY_TIMEOUT_MS = 100, DEFAULT_CHUNK_SIZE = 16384, DEFAULT_DEBOUNCE_MS = 15, DEFAULT_PORT = 3000, DEV_SERVER_RESTART_DEBOUNCE_MS = 100, DOM_UPDATE_DELAY_MS = 50, FILE_PROTOCOL_PREFIX_LENGTH = 7, FOCUS_ID_PREFIX_LENGTH = 3, FOCUS_IDX_PREFIX_LENGTH = 4, FOCUS_NAME_PREFIX_LENGTH = 5, HMR_UPDATE_TIMEOUT_MS = 2000, HOOK_SIGNATURE_LENGTH = 12, EXCLUDE_LAST_OFFSET = -1, HTTP_STATUS_OK = 200, HTTP_STATUS_BAD_REQUEST = 400, HTTP_STATUS_NOT_FOUND = 404, HOURS_IN_DAY = 24, HOURS_IN_HALF_DAY = 12, IMAGE_DEFAULT_DEVICE_SIZES, IMAGE_DEFAULT_IMAGE_SIZES, IMAGE_DEFAULT_QUALITY = 75, IMAGE_GLOB_SUFFIX_LENGTH = 2, MAX_ERROR_LENGTH = 200, MAX_RECONNECT_ATTEMPTS = 60, MILLISECONDS_IN_A_SECOND = 1000, MINUTES_IN_AN_HOUR = 60, SECONDS_IN_A_MINUTE = 60, MILLISECONDS_IN_A_MINUTE, MILLISECONDS_IN_A_DAY, OVERLAY_FADE_DURATION_MS = 150, PING_INTERVAL_MS = 30000, RAF_BATCH_COUNT = 3, RANDOM_ID_END_INDEX = 11, REBUILD_BATCH_DELAY_MS = 10, REBUILD_RELOAD_DELAY_MS = 200, RECONNECT_INITIAL_DELAY_MS = 500, RECONNECT_POLL_INTERVAL_MS = 300, REACT_STREAM_SLOT_FAST_DELAY_MS = 5, REACT_STREAM_SLOT_SLOW_DELAY_MS = 20, SIGINT_EXIT_CODE = 130, SIGTERM_EXIT_CODE = 143, SVELTE_CSS_LOAD_TIMEOUT_MS = 500, TIME_PRECISION = 2, TWO_THIRDS, UNFOUND_INDEX = -1, WEBSOCKET_NORMAL_CLOSURE = 1000, WORKSPACE_COMMAND_ARGS_OFFSET = 3, WORKSPACE_FAILURE_LOG_PRINT_LIMIT = 30, WORKSPACE_FAILURE_RECENT_LOG_LIMIT = 60, WORKSPACE_READY_ATTEMPT_TIMEOUT_MS = 5000, WORKSPACE_READY_PROBE_INTERVAL_MS = 250, WORKSPACE_READY_TIMEOUT_MS = 30000, WORKSPACE_SHUTDOWN_TIMEOUT_MS = 1e4, WORKSPACE_TUI_DEFAULT_HEIGHT = 28, WORKSPACE_TUI_DEFAULT_WIDTH = 100, WORKSPACE_TUI_ESCAPE_SEQUENCE_TIMEOUT_MS = 30, WORKSPACE_TUI_FOOTER_LINE_COUNT = 3, WORKSPACE_TUI_MIN_LOG_HEIGHT = 3, WORKSPACE_TUI_MIN_SERVICE_NAME_WIDTH = 7, WORKSPACE_TUI_MIN_TARGET_WIDTH = 8, WORKSPACE_TUI_MIN_WRAP_WIDTH = 12, WORKSPACE_TUI_PROMPT_CURSOR_OFFSET = 3, WORKSPACE_TUI_RECENT_LOG_LIMIT = 40, WORKSPACE_TUI_RENDER_DEBOUNCE_MS = 16, WORKSPACE_TUI_STATUS_WIDTH = 10, WORKSPACE_TUI_TARGET_PADDING_WIDTH = 6, WORKSPACE_TUI_VISIBILITY_WIDTH = 8;
65
+ var init_constants = __esm(() => {
66
+ IMAGE_DEFAULT_DEVICE_SIZES = [
67
+ 640,
68
+ 750,
69
+ 828,
70
+ 1080,
71
+ 1200,
72
+ 1920,
73
+ 2048,
74
+ 3840
75
+ ];
76
+ IMAGE_DEFAULT_IMAGE_SIZES = [16, 32, 48, 64, 96, 128, 256, 384];
77
+ MILLISECONDS_IN_A_MINUTE = MILLISECONDS_IN_A_SECOND * SECONDS_IN_A_MINUTE;
78
+ MILLISECONDS_IN_A_DAY = MILLISECONDS_IN_A_SECOND * SECONDS_IN_A_MINUTE * MINUTES_IN_AN_HOUR * HOURS_IN_DAY;
79
+ TWO_THIRDS = 2 / 3;
80
+ });
81
+
82
+ // src/core/devRouteRegistrationCallsite.ts
83
+ var exports_devRouteRegistrationCallsite = {};
84
+ __export(exports_devRouteRegistrationCallsite, {
85
+ patchElysiaRouteRegistrationCallsites: () => patchElysiaRouteRegistrationCallsites,
86
+ getCurrentRouteRegistrationCallsite: () => getCurrentRouteRegistrationCallsite
87
+ });
88
+ import { AsyncLocalStorage } from "async_hooks";
89
+ import { Elysia } from "elysia";
90
+ var ROUTE_CALLSITE_STORAGE_KEY, ROUTE_CALLSITE_PATCHED_KEY, ROUTE_METHOD_NAMES, isObjectRecord4 = (value) => Boolean(value) && typeof value === "object", isAsyncLocalStorage2 = (value) => isObjectRecord4(value) && ("getStore" in value) && typeof value.getStore === "function" && ("run" in value) && typeof value.run === "function", isRouteMethod = (value) => typeof value === "function", getRouteCallsiteStorage = () => {
91
+ const value = Reflect.get(globalThis, ROUTE_CALLSITE_STORAGE_KEY);
92
+ if (value === null || typeof value === "undefined") {
93
+ return;
94
+ }
95
+ return isAsyncLocalStorage2(value) ? value : undefined;
96
+ }, ensureRouteCallsiteStorage = () => {
97
+ const existing = getRouteCallsiteStorage();
98
+ if (existing) {
99
+ return existing;
100
+ }
101
+ const storage = new AsyncLocalStorage;
102
+ Reflect.set(globalThis, ROUTE_CALLSITE_STORAGE_KEY, storage);
103
+ return storage;
104
+ }, normalizeCallsitePath = (value) => value.replace(`${process.cwd()}/`, "").replace(process.cwd(), "").replace(/^\.\/+/, ""), shouldIgnoreRouteCallsiteFrame = (frame) => frame.includes("/node_modules/") || frame.includes("/dist/") || frame.includes("/src/core/devRouteRegistrationCallsite."), getRouteCallsiteLocation = (frame) => frame.match(/\((\/[^)]+:\d+:\d+)\)$/)?.[1] ?? frame.match(/at (\/[^ ]+:\d+:\d+)$/)?.[1], extractRouteRegistrationCallsite = (stack) => {
105
+ const location = stack.split(`
106
+ `).slice(1).map((line) => line.trim()).filter((frame) => !shouldIgnoreRouteCallsiteFrame(frame)).map((frame) => getRouteCallsiteLocation(frame)).find((frameLocation) => frameLocation !== undefined);
107
+ return location ? normalizeCallsitePath(location) : undefined;
108
+ }, captureRouteRegistrationCallsite = () => {
109
+ const { stack } = new Error;
110
+ if (!stack) {
111
+ return;
112
+ }
113
+ return extractRouteRegistrationCallsite(stack);
114
+ }, wrapRouteHandlerWithCallsite = (handler, callsite) => {
115
+ if (typeof handler !== "function" || !callsite) {
116
+ return handler;
117
+ }
118
+ const storage = ensureRouteCallsiteStorage();
119
+ const routeHandler = handler;
120
+ return function wrappedRouteHandler(...args) {
121
+ return storage.run({ callsite }, () => Reflect.apply(routeHandler, this, args));
122
+ };
123
+ }, createPatchedRouteMethod = (originalMethod) => function patchedRouteMethod(path, handler, ...rest) {
124
+ const callsite = captureRouteRegistrationCallsite();
125
+ return Reflect.apply(originalMethod, this, [
126
+ path,
127
+ wrapRouteHandlerWithCallsite(handler, callsite),
128
+ ...rest
129
+ ]);
130
+ }, getCurrentRouteRegistrationCallsite = () => getRouteCallsiteStorage()?.getStore()?.callsite, patchElysiaRouteRegistrationCallsites = () => {
131
+ if (false) {}
132
+ if (Reflect.get(globalThis, ROUTE_CALLSITE_PATCHED_KEY) === true) {
133
+ return;
134
+ }
135
+ const { prototype } = Elysia;
136
+ ROUTE_METHOD_NAMES.forEach((methodName) => {
137
+ const originalMethod = Reflect.get(prototype, methodName);
138
+ if (!isRouteMethod(originalMethod))
139
+ return;
140
+ Reflect.set(prototype, methodName, createPatchedRouteMethod(originalMethod));
141
+ });
142
+ Reflect.set(globalThis, ROUTE_CALLSITE_PATCHED_KEY, true);
143
+ };
144
+ var init_devRouteRegistrationCallsite = __esm(() => {
145
+ ROUTE_CALLSITE_STORAGE_KEY = Symbol.for("absolutejs.devRouteRegistrationCallsiteStorage");
146
+ ROUTE_CALLSITE_PATCHED_KEY = Symbol.for("absolutejs.devRouteRegistrationCallsitePatched");
147
+ ROUTE_METHOD_NAMES = [
148
+ "all",
149
+ "delete",
150
+ "get",
151
+ "head",
152
+ "options",
153
+ "patch",
154
+ "post",
155
+ "put"
156
+ ];
157
+ });
158
+
159
+ // src/client/streamSwap.ts
160
+ var streamSwapRuntime = () => {
161
+ const absoluteWindow = window;
162
+ const SLOT_PATCH_EVENT = "absolutejs:slot-patch";
163
+ if (absoluteWindow.__ABS_SLOT_RUNTIME__ === true)
164
+ return;
165
+ absoluteWindow.__ABS_SLOT_RUNTIME__ = true;
166
+ absoluteWindow.__ABS_SLOT_CONSUMERS__ = absoluteWindow.__ABS_SLOT_CONSUMERS__ ?? {};
167
+ absoluteWindow.__ABS_SLOT_PENDING__ = absoluteWindow.__ABS_SLOT_PENDING__ ?? {};
168
+ const consumers = absoluteWindow.__ABS_SLOT_CONSUMERS__;
169
+ const pending = absoluteWindow.__ABS_SLOT_PENDING__;
170
+ const isObjectRecord5 = (value) => Boolean(value) && typeof value === "object";
171
+ const isPatchedPendingEntry = (value) => {
172
+ if (!isObjectRecord5(value))
173
+ return false;
174
+ return value.domPatched === true && "payload" in value;
175
+ };
176
+ const unwrapPendingPayload = (value) => isPatchedPendingEntry(value) ? value.payload : value;
177
+ const canApplyImmediately = () => absoluteWindow.__ABS_SLOT_HYDRATION_PENDING__ !== true;
178
+ const isAngularDeferPayload = (payload) => {
179
+ if (!isObjectRecord5(payload))
180
+ return false;
181
+ return payload.kind === "angular-defer";
182
+ };
183
+ const isVueSuspensePayload2 = (payload) => {
184
+ if (!isObjectRecord5(payload))
185
+ return false;
186
+ return payload.kind === "vue-suspense";
187
+ };
188
+ const resolveHtml = (payload) => {
189
+ if (!isObjectRecord5(payload)) {
190
+ return typeof payload === "string" ? payload : "";
191
+ }
192
+ if (typeof payload.html === "string") {
193
+ return payload.html;
194
+ }
195
+ return "";
196
+ };
197
+ const apply = (id, pendingEntry) => {
198
+ const payload = unwrapPendingPayload(pendingEntry);
199
+ if (!canApplyImmediately()) {
200
+ pending[id] = payload;
201
+ return;
202
+ }
203
+ const consumer = consumers[id];
204
+ if (typeof consumer !== "function") {
205
+ applyToDom(id, payload, pendingEntry);
206
+ return;
207
+ }
208
+ const handled = consumer(payload);
209
+ if (handled !== false) {
210
+ delete pending[id];
211
+ return;
212
+ }
213
+ applyToDom(id, payload, pendingEntry);
214
+ };
215
+ const applyToDom = (id, payload, pendingEntry) => {
216
+ if (isAngularDeferPayload(payload)) {
217
+ pending[id] = payload;
218
+ return;
219
+ }
220
+ const node = document.getElementById(id);
221
+ if (!node) {
222
+ pending[id] = payload;
223
+ return;
224
+ }
225
+ const html = resolveHtml(payload);
226
+ if (isVueSuspensePayload2(payload) && isPatchedPendingEntry(pendingEntry)) {
227
+ return;
228
+ }
229
+ node.innerHTML = html;
230
+ node.setAttribute("data-absolute-slot-state", "resolved");
231
+ window.dispatchEvent(new CustomEvent(SLOT_PATCH_EVENT, {
232
+ detail: { html, id, payload }
233
+ }));
234
+ if (isVueSuspensePayload2(payload)) {
235
+ pending[id] = { domPatched: true, payload };
236
+ return;
237
+ }
238
+ delete pending[id];
239
+ };
240
+ const flush = () => {
241
+ for (const id in pending) {
242
+ if (!Object.prototype.hasOwnProperty.call(pending, id))
243
+ continue;
244
+ apply(id, pending[id] ?? "");
245
+ }
246
+ };
247
+ absoluteWindow.__ABS_SLOT_FLUSH__ = flush;
248
+ absoluteWindow.__ABS_SLOT_ENQUEUE__ = (id, payload) => {
249
+ apply(id, payload);
250
+ };
251
+ if (typeof MutationObserver === "function") {
252
+ const observer = new MutationObserver(flush);
253
+ const root = document.documentElement ?? document.body ?? document;
254
+ observer.observe(root, { childList: true, subtree: true });
255
+ }
256
+ if (document.readyState === "loading") {
257
+ document.addEventListener("DOMContentLoaded", flush, { once: true });
258
+ }
259
+ flush();
260
+ }, stripFunctionWrapper = (value) => {
261
+ const start = value.indexOf("{");
262
+ const end = value.lastIndexOf("}");
263
+ if (start < 0 || end <= start)
264
+ return "";
265
+ return value.slice(start + 1, end);
266
+ }, getStreamSwapRuntimeScript = () => `(function(){${stripFunctionWrapper(streamSwapRuntime.toString())}})();`;
267
+
268
+ // src/utils/escapeScriptContent.ts
269
+ var ESCAPE_LOOKUP, ESCAPE_REGEX, escapeScriptContent = (content) => content.replace(ESCAPE_REGEX, (char) => {
270
+ const escaped = ESCAPE_LOOKUP[char];
271
+ return escaped !== undefined ? escaped : char;
272
+ });
273
+ var init_escapeScriptContent = __esm(() => {
274
+ ESCAPE_LOOKUP = {
275
+ "\u2028": "\\u2028",
276
+ "\u2029": "\\u2029",
277
+ "<": "\\u003C"
278
+ };
279
+ ESCAPE_REGEX = /[<\u2028\u2029]/g;
280
+ });
281
+
282
+ // src/utils/streamingSlots.ts
283
+ var SLOT_ID_PREFIX = "abs-slot-", CLOSING_BODY_TAG = "</body>", CLOSING_HEAD_TAG2 = "</head>", CLOSING_BODY_TAG_LENGTH, CLOSING_HEAD_TAG_LENGTH, CLOSING_PAGE_TAG_REGEX, STREAMING_RUNTIME_GLOBAL = "__ABS_SLOT_ENQUEUE__", STREAMING_PENDING_GLOBAL = "__ABS_SLOT_PENDING__", STREAM_TAIL_LOOKBEHIND = 128, STREAMING_SLOT_TIMEOUT_MS = 5000, STREAMING_SLOT_MAX_PER_RESPONSE = 128, STREAMING_SLOT_MAX_HTML_BYTES = 64000, createSlotPatchStatement = (id, payload) => `(window.${STREAMING_RUNTIME_GLOBAL}||function(i,p){window.${STREAMING_PENDING_GLOBAL}=window.${STREAMING_PENDING_GLOBAL}||{};window.${STREAMING_PENDING_GLOBAL}[i]=p;})(${JSON.stringify(id)},${JSON.stringify(payload)});`, createNonceAttr = (nonce) => nonce ? ` nonce="${nonce}"` : "", createStreamingSlotId = () => `${SLOT_ID_PREFIX}${Math.random().toString(BASE_36_RADIX).slice(2, RANDOM_ID_END_INDEX)}`, getStreamingSlotsRuntimeScript = () => getStreamSwapRuntimeScript(), injectHtmlIntoBody = (html, injection) => {
284
+ const closingBodyIndex = html.indexOf(CLOSING_BODY_TAG);
285
+ if (closingBodyIndex >= 0) {
286
+ return `${html.slice(0, closingBodyIndex)}${injection}${html.slice(closingBodyIndex)}`;
287
+ }
288
+ return `${html}${injection}`;
289
+ }, injectHtmlIntoHead = (html, injection) => {
290
+ const closingHeadIndex = html.indexOf(CLOSING_HEAD_TAG2);
291
+ if (closingHeadIndex >= 0) {
292
+ return `${html.slice(0, closingHeadIndex)}${injection}${html.slice(closingHeadIndex)}`;
293
+ }
294
+ return `${html}${injection}`;
295
+ }, renderStreamingSlotPatchTag = (id, payload, nonce) => `<script${createNonceAttr(nonce)}>${escapeScriptContent(createSlotPatchStatement(id, payload))}</script>`, renderStreamingSlotPlaceholder = (id, fallbackHtml = "") => `<div id="${id}" data-absolute-slot="true" data-absolute-slot-state="fallback">${fallbackHtml}</div>`, renderStreamingSlotsRuntimeTag = (nonce, runtimePreludeScript) => {
296
+ const runtimeBody = [
297
+ runtimePreludeScript?.trim() ? runtimePreludeScript.trim() : "",
298
+ getStreamingSlotsRuntimeScript()
299
+ ].filter(Boolean).join(";");
300
+ return `<script${createNonceAttr(nonce)}>${escapeScriptContent(runtimeBody)}</script>`;
301
+ }, toUint8 = (value, encoder) => encoder.encode(value), isRecord = (value) => Boolean(value) && typeof value === "object", isSafeHtmlLike = (value) => isRecord(value) && typeof value.changingThisBreaksApplicationSecurity === "string", normalizeSafeHtml = (value) => {
302
+ if (isSafeHtmlLike(value)) {
303
+ return value.changingThisBreaksApplicationSecurity;
304
+ }
305
+ return value;
306
+ }, currentStreamingSlotPolicy, clonePolicy = (policy) => ({
307
+ ...policy
308
+ }), normalizeSlotBytes = (value, fallback) => {
309
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
310
+ return Math.floor(value);
311
+ }
312
+ return fallback;
313
+ }, normalizeSlotText = (value, fallback) => {
314
+ const normalizedValue = normalizeSafeHtml(value);
315
+ return typeof normalizedValue === "string" ? normalizedValue : fallback;
316
+ }, normalizeSlotError = (value, fallback = undefined) => {
317
+ const safeValue = normalizeSafeHtml(value);
318
+ if (typeof safeValue === "string")
319
+ return safeValue;
320
+ return fallback;
321
+ }, hasPolicyValue = (policy, key) => Object.prototype.hasOwnProperty.call(policy, key), applyStreamingSlotPolicyOverrides = (base, overridePolicy = {}) => ({
322
+ errorHtml: hasPolicyValue(overridePolicy, "errorHtml") ? normalizeSlotError(overridePolicy.errorHtml) : base.errorHtml,
323
+ fallbackHtml: hasPolicyValue(overridePolicy, "fallbackHtml") ? normalizeSlotText(overridePolicy.fallbackHtml, "") : base.fallbackHtml,
324
+ maxSlotHtmlSizeBytes: hasPolicyValue(overridePolicy, "maxSlotHtmlSizeBytes") ? normalizeSlotBytes(overridePolicy.maxSlotHtmlSizeBytes, base.maxSlotHtmlSizeBytes) : base.maxSlotHtmlSizeBytes,
325
+ maxSlotsPerResponse: hasPolicyValue(overridePolicy, "maxSlotsPerResponse") ? normalizeSlotBytes(overridePolicy.maxSlotsPerResponse, base.maxSlotsPerResponse) : base.maxSlotsPerResponse,
326
+ onError: hasPolicyValue(overridePolicy, "onError") ? overridePolicy.onError : base.onError,
327
+ onSlotMetric: hasPolicyValue(overridePolicy, "onSlotMetric") ? overridePolicy.onSlotMetric : base.onSlotMetric,
328
+ timeoutMs: hasPolicyValue(overridePolicy, "timeoutMs") ? normalizeSlotBytes(overridePolicy.timeoutMs, base.timeoutMs) : base.timeoutMs
329
+ }), createCombinedSlotErrorHandler = (policyOnError, enhancerOnError) => {
330
+ if (!policyOnError && !enhancerOnError)
331
+ return;
332
+ return (error, slot) => {
333
+ policyOnError?.(error, slot);
334
+ enhancerOnError?.(error, slot);
335
+ };
336
+ }, createCombinedSlotMetricHandler = (policyOnSlotMetric, callOnSlotMetric) => {
337
+ if (!policyOnSlotMetric && !callOnSlotMetric)
338
+ return;
339
+ return (metric) => {
340
+ policyOnSlotMetric?.(metric);
341
+ callOnSlotMetric?.(metric);
342
+ };
343
+ }, resolveStreamingSlotPolicy = (overridePolicy = {}) => {
344
+ const base = getStreamingSlotPolicy();
345
+ return applyStreamingSlotPolicyOverrides(base, overridePolicy);
346
+ }, getStreamingSlotPolicy = () => clonePolicy(currentStreamingSlotPolicy), setStreamingSlotPolicy = (policy = {}) => {
347
+ const base = getStreamingSlotPolicy();
348
+ currentStreamingSlotPolicy = applyStreamingSlotPolicyOverrides(base, policy);
349
+ }, withStreamingSlotPolicy = async (policy, callback) => {
350
+ const previous = getStreamingSlotPolicy();
351
+ setStreamingSlotPolicy(policy);
352
+ try {
353
+ return await callback();
354
+ } finally {
355
+ currentStreamingSlotPolicy = previous;
356
+ }
357
+ }, emitSlotMetric = (metric, onSlotMetric) => {
358
+ onSlotMetric?.(metric);
359
+ }, createTimeoutError = (slot, timeoutMs) => {
360
+ const error = Object.assign(new Error(`Streaming slot "${slot.id}" timed out after ${timeoutMs}ms`), { __absTimeout: true });
361
+ return error;
362
+ }, isSlotPatchPayloadObject = (value) => isRecord(value) && ("html" in value), isTimeoutError = (error) => isRecord(error) && error.__absTimeout === true, toStreamingSlot = (slot, policy) => ({
363
+ errorHtml: slot.errorHtml === undefined ? policy.errorHtml : slot.errorHtml,
364
+ fallbackHtml: normalizeSlotText(slot.fallbackHtml, policy.fallbackHtml),
365
+ id: slot.id ?? createStreamingSlotId(),
366
+ resolve: slot.resolve,
367
+ timeoutMs: normalizeSlotBytes(slot.timeoutMs, policy.timeoutMs)
368
+ }), prepareSlots = ({
369
+ policy,
370
+ slots,
371
+ onError,
372
+ onSlotMetric
373
+ }) => {
374
+ const preparedSlots = slots.map((slot) => toStreamingSlot(slot, policy));
375
+ const emitPreparedSlotMetric = (slot) => {
376
+ emitSlotMetric({
377
+ slotId: slot.id,
378
+ type: "prepared"
379
+ }, onSlotMetric);
380
+ };
381
+ const dropPreparedSlot = (slot, reason) => {
382
+ onError?.(new Error(reason), slot);
383
+ emitSlotMetric({
384
+ reason,
385
+ slotId: slot.id,
386
+ type: "dropped"
387
+ }, onSlotMetric);
388
+ };
389
+ const { maxSlotsPerResponse } = policy;
390
+ if (maxSlotsPerResponse === 0) {
391
+ preparedSlots.forEach((slot) => dropPreparedSlot(slot, "maxSlotsPerResponse is 0"));
392
+ return [];
393
+ }
394
+ if (preparedSlots.length <= maxSlotsPerResponse) {
395
+ preparedSlots.forEach(emitPreparedSlotMetric);
396
+ return preparedSlots;
397
+ }
398
+ const keptSlots = preparedSlots.slice(0, maxSlotsPerResponse);
399
+ const droppedSlots = preparedSlots.slice(maxSlotsPerResponse);
400
+ droppedSlots.forEach((slot) => {
401
+ dropPreparedSlot(slot, `Streaming slot "${slot.id}" dropped because ${maxSlotsPerResponse} slots is the configured maximum`);
402
+ });
403
+ keptSlots.forEach(emitPreparedSlotMetric);
404
+ return keptSlots;
405
+ }, htmlByteLength = (value, encoder) => encoder.encode(value).length, normalizeSlotPatchPayload = (value) => {
406
+ const safeValue = normalizeSafeHtml(value);
407
+ if (isSlotPatchPayloadObject(safeValue) && typeof safeValue.html === "string") {
408
+ return {
409
+ ...safeValue,
410
+ html: normalizeSlotText(safeValue.html, "")
411
+ };
412
+ }
413
+ return typeof safeValue === "string" ? safeValue : `${safeValue}`;
414
+ }, getPayloadHtml = (payload) => typeof payload === "string" ? payload : payload.html, enqueueEncodedText = (controller, encoder, value) => {
415
+ if (value.length === 0) {
416
+ return;
417
+ }
418
+ controller.enqueue(encoder.encode(value));
419
+ }, readStreamingRuntimeChunk = async (reader) => {
420
+ const { done, value } = await reader.read();
421
+ if (done || !value) {
422
+ return { done, value: undefined };
423
+ }
424
+ return { done, value };
425
+ }, applyBaseWinnerState = (state, winner, handleResolved) => {
426
+ if (!state.handled && winner.kind === "slot") {
427
+ handleResolved(winner);
428
+ }
429
+ return state;
430
+ }, resolveOversizedSlotPayload = (input) => {
431
+ const {
432
+ encoder,
433
+ html,
434
+ maxSlotHtmlSizeBytes,
435
+ onError,
436
+ onSlotMetric,
437
+ slot,
438
+ start
439
+ } = input;
440
+ const bytes = htmlByteLength(html, encoder);
441
+ if (bytes <= maxSlotHtmlSizeBytes) {
442
+ return null;
443
+ }
444
+ const error = new Error(`Streaming slot "${slot.id}" exceeded max payload size of ${maxSlotHtmlSizeBytes} bytes`);
445
+ const durationMs = Date.now() - start;
446
+ onError?.(error, slot);
447
+ emitSlotMetric({
448
+ bytes,
449
+ durationMs,
450
+ error,
451
+ slotId: slot.id,
452
+ type: "size_exceeded"
453
+ }, onSlotMetric);
454
+ const fallbackHtml = normalizeSlotError(slot.errorHtml, undefined);
455
+ return {
456
+ bytes: fallbackHtml === undefined ? 0 : htmlByteLength(fallbackHtml, encoder),
457
+ durationMs,
458
+ id: slot.id,
459
+ payload: fallbackHtml === undefined ? null : fallbackHtml
460
+ };
461
+ }, raceWithTimeout = (promise, slot) => {
462
+ const { timeoutMs } = slot;
463
+ if (typeof timeoutMs !== "number" || timeoutMs <= 0) {
464
+ return promise;
465
+ }
466
+ const { promise: timeoutPromise, reject } = Promise.withResolvers();
467
+ setTimeout(() => {
468
+ reject(createTimeoutError(slot, timeoutMs));
469
+ }, timeoutMs);
470
+ return Promise.race([promise, timeoutPromise]);
471
+ }, resolveSlot = async (slot, onError, policy, onSlotMetric) => {
472
+ const safePolicy = policy ?? getStreamingSlotPolicy();
473
+ const encoder = new TextEncoder;
474
+ const start = Date.now();
475
+ try {
476
+ const maybeAsyncValue = Promise.resolve(slot.resolve());
477
+ const resolved = await raceWithTimeout(maybeAsyncValue, slot);
478
+ const payload = normalizeSlotPatchPayload(resolved);
479
+ const html = getPayloadHtml(payload);
480
+ const oversizedResult = safePolicy.maxSlotHtmlSizeBytes > 0 ? resolveOversizedSlotPayload({
481
+ encoder,
482
+ html,
483
+ maxSlotHtmlSizeBytes: safePolicy.maxSlotHtmlSizeBytes,
484
+ onError,
485
+ onSlotMetric,
486
+ slot,
487
+ start
488
+ }) : null;
489
+ if (oversizedResult) {
490
+ return oversizedResult;
491
+ }
492
+ const durationMs = Date.now() - start;
493
+ const bytes = htmlByteLength(html, encoder);
494
+ emitSlotMetric({
495
+ bytes,
496
+ durationMs,
497
+ slotId: slot.id,
498
+ type: "resolved"
499
+ }, onSlotMetric);
500
+ return {
501
+ bytes,
502
+ durationMs,
503
+ id: slot.id,
504
+ payload
505
+ };
506
+ } catch (error) {
507
+ const durationMs = Date.now() - start;
508
+ onError?.(error, slot);
509
+ emitSlotMetric({
510
+ durationMs,
511
+ error,
512
+ slotId: slot.id,
513
+ type: isTimeoutError(error) ? "timeout" : "error"
514
+ }, onSlotMetric);
515
+ const html = normalizeSlotError(slot.errorHtml, undefined);
516
+ if (html) {
517
+ return {
518
+ bytes: htmlByteLength(html, encoder),
519
+ durationMs,
520
+ id: slot.id,
521
+ payload: html
522
+ };
523
+ }
524
+ return {
525
+ bytes: 0,
526
+ durationMs,
527
+ id: slot.id,
528
+ payload: null
529
+ };
530
+ }
531
+ }, nextResolvedSlot = async (pending) => {
532
+ const wrapped = pending.map((promise) => promise.then((result) => ({
533
+ original: promise,
534
+ result
535
+ })));
536
+ return Promise.race(wrapped);
537
+ }, streamChunkToString2 = (value, decoder) => typeof value === "string" ? value : decoder.decode(value, { stream: true }), appendStreamingSlotPatchesToStream = (stream, slots = [], {
538
+ injectRuntime = true,
539
+ nonce,
540
+ onError,
541
+ onSlotMetric,
542
+ policy,
543
+ runtimePreludeScript,
544
+ runtimePlacement = "head"
545
+ } = {}) => {
546
+ const resolvedPolicy = resolveStreamingSlotPolicy(policy);
547
+ const combinedOnError = createCombinedSlotErrorHandler(resolvedPolicy.onError, onError);
548
+ const combinedOnSlotMetric = createCombinedSlotMetricHandler(resolvedPolicy.onSlotMetric, onSlotMetric);
549
+ const effectivePolicy = {
550
+ ...resolvedPolicy,
551
+ onSlotMetric: combinedOnSlotMetric
552
+ };
553
+ const preparedSlots = prepareSlots({
554
+ onError: combinedOnError,
555
+ onSlotMetric: combinedOnSlotMetric,
556
+ policy: effectivePolicy,
557
+ slots
558
+ });
559
+ if (preparedSlots.length === 0)
560
+ return stream;
561
+ const source = injectRuntime ? injectStreamingRuntimeIntoStream(stream, nonce, runtimePlacement, runtimePreludeScript) : stream;
562
+ const encoder = new TextEncoder;
563
+ const decoder = new TextDecoder;
564
+ const reader = source.getReader();
565
+ const pending = preparedSlots.map((slot) => resolveSlot(slot, combinedOnError, effectivePolicy, combinedOnSlotMetric));
566
+ const createRaceCandidates = (baseDone, baseRead) => {
567
+ const racers = [];
568
+ if (!baseDone) {
569
+ racers.push(baseRead.then(({ done, value }) => ({
570
+ done,
571
+ kind: "base",
572
+ value
573
+ })));
574
+ }
575
+ if (pending.length > 0) {
576
+ racers.push(nextResolvedSlot(pending).then((resolved) => ({
577
+ kind: "slot",
578
+ ...resolved
579
+ })));
580
+ }
581
+ return racers;
582
+ };
583
+ const flushTailLookbehind = (controller, tail) => {
584
+ if (tail.length <= STREAM_TAIL_LOOKBEHIND) {
585
+ return tail;
586
+ }
587
+ const content = tail.slice(0, tail.length - STREAM_TAIL_LOOKBEHIND);
588
+ controller.enqueue(encoder.encode(content));
589
+ return tail.slice(-STREAM_TAIL_LOOKBEHIND);
590
+ };
591
+ const finalizeCompletedBaseWinner = (controller, decodedTail, baseRead) => {
592
+ const footerStart = decodedTail.search(CLOSING_PAGE_TAG_REGEX);
593
+ if (footerStart < 0) {
594
+ enqueueEncodedText(controller, encoder, decodedTail);
595
+ return {
596
+ baseDone: true,
597
+ baseRead,
598
+ footer: "",
599
+ handled: true,
600
+ tail: ""
601
+ };
602
+ }
603
+ const content = decodedTail.slice(0, footerStart);
604
+ const nextFooter = decodedTail.slice(footerStart);
605
+ enqueueEncodedText(controller, encoder, content);
606
+ return {
607
+ baseDone: true,
608
+ baseRead,
609
+ footer: nextFooter,
610
+ handled: true,
611
+ tail: ""
612
+ };
613
+ };
614
+ const handleBaseWinner = (controller, winner, baseRead, tail, footer) => {
615
+ if (winner.kind !== "base") {
616
+ return { baseDone: false, baseRead, footer, handled: false, tail };
617
+ }
618
+ if (winner.done) {
619
+ return finalizeCompletedBaseWinner(controller, tail + decoder.decode(), baseRead);
620
+ }
621
+ if (!winner.value) {
622
+ return { baseDone: false, baseRead, footer, handled: true, tail };
623
+ }
624
+ const nextTail = flushTailLookbehind(controller, tail + streamChunkToString2(winner.value, decoder));
625
+ return {
626
+ baseDone: false,
627
+ baseRead: reader.read(),
628
+ footer,
629
+ handled: true,
630
+ tail: nextTail
631
+ };
632
+ };
633
+ const handleResolvedSlot = (controller, winner) => {
634
+ const index = pending.indexOf(winner.original);
635
+ if (index >= 0)
636
+ pending.splice(index, 1);
637
+ if (winner.result.payload === null) {
638
+ return;
639
+ }
640
+ emitSlotMetric({
641
+ bytes: winner.result.bytes,
642
+ durationMs: winner.result.durationMs,
643
+ slotId: winner.result.id,
644
+ type: "patched"
645
+ }, combinedOnSlotMetric);
646
+ controller.enqueue(encoder.encode(renderStreamingSlotPatchTag(winner.result.id, winner.result.payload, nonce)));
647
+ };
648
+ const runPatchedStreamLoop = async (controller) => {
649
+ let baseDone = false;
650
+ let baseRead = reader.read();
651
+ let tail = "";
652
+ let footer = "";
653
+ const readNextRaceWinner = async () => {
654
+ const racers = createRaceCandidates(baseDone, baseRead);
655
+ if (racers.length === 0) {
656
+ return footer;
657
+ }
658
+ const winner = await Promise.race(racers);
659
+ const baseWinnerState = applyBaseWinnerState(handleBaseWinner(controller, winner, baseRead, tail, footer), winner, (slotWinner) => {
660
+ handleResolvedSlot(controller, slotWinner);
661
+ });
662
+ ({ baseDone, baseRead, footer, tail } = baseWinnerState);
663
+ if (baseDone && pending.length === 0) {
664
+ return footer;
665
+ }
666
+ return readNextRaceWinner();
667
+ };
668
+ return readNextRaceWinner();
669
+ };
670
+ return new ReadableStream({
671
+ async start(controller) {
672
+ try {
673
+ const footer = await runPatchedStreamLoop(controller);
674
+ enqueueEncodedText(controller, encoder, footer);
675
+ controller.close();
676
+ } catch (error) {
677
+ controller.error(error);
678
+ }
679
+ }
680
+ });
681
+ }, injectStreamingRuntimeIntoStream = (stream, nonce, runtimePlacement = "head", runtimePreludeScript) => {
682
+ const runtimeTag = renderStreamingSlotsRuntimeTag(nonce, runtimePreludeScript);
683
+ const encoder = new TextEncoder;
684
+ const decoder = new TextDecoder;
685
+ const closingTag = runtimePlacement === "body" ? CLOSING_BODY_TAG : CLOSING_HEAD_TAG2;
686
+ const lookbehind = (runtimePlacement === "body" ? CLOSING_BODY_TAG_LENGTH : CLOSING_HEAD_TAG_LENGTH) - 1;
687
+ const flushRuntimeLookbehind = (controller, pending) => {
688
+ if (pending.length <= lookbehind) {
689
+ return pending;
690
+ }
691
+ const safeText = pending.slice(0, pending.length - lookbehind);
692
+ controller.enqueue(encoder.encode(safeText));
693
+ return pending.slice(-lookbehind);
694
+ };
695
+ const injectRuntimeIntoPending = (pending) => runtimePlacement === "body" ? injectHtmlIntoBody(pending, runtimeTag) : injectHtmlIntoHead(pending, runtimeTag);
696
+ const processRuntimePending = (controller, pending, injected) => {
697
+ if (injected) {
698
+ controller.enqueue(encoder.encode(pending));
699
+ return { injected, pending: "" };
700
+ }
701
+ const closingTagIndex = pending.indexOf(closingTag);
702
+ if (closingTagIndex >= 0) {
703
+ const withRuntime = `${pending.slice(0, closingTagIndex)}${runtimeTag}${pending.slice(closingTagIndex)}`;
704
+ controller.enqueue(encoder.encode(withRuntime));
705
+ return { injected: true, pending: "" };
706
+ }
707
+ return {
708
+ injected,
709
+ pending: flushRuntimeLookbehind(controller, pending)
710
+ };
711
+ };
712
+ return new ReadableStream({
713
+ async start(controller) {
714
+ const reader = stream.getReader();
715
+ let injected = false;
716
+ let pending = "";
717
+ const enqueuePending = () => enqueueEncodedText(controller, encoder, pending);
718
+ const consumeRuntimeChunk = async () => {
719
+ const { done, value } = await readStreamingRuntimeChunk(reader);
720
+ if (done || !value) {
721
+ return done;
722
+ }
723
+ pending += streamChunkToString2(value, decoder);
724
+ ({ injected, pending } = processRuntimePending(controller, pending, injected));
725
+ return false;
726
+ };
727
+ const runRuntimeInjectionLoop = async () => {
728
+ const done = await consumeRuntimeChunk();
729
+ if (done) {
730
+ return;
731
+ }
732
+ await runRuntimeInjectionLoop();
733
+ };
734
+ try {
735
+ await runRuntimeInjectionLoop();
736
+ pending += decoder.decode();
737
+ pending = injected ? pending : injectRuntimeIntoPending(pending);
738
+ enqueuePending();
739
+ controller.close();
740
+ } catch (error) {
741
+ controller.error(error);
742
+ }
743
+ }
744
+ });
745
+ }, streamOutOfOrderSlots = ({
746
+ footerHtml = "",
747
+ headerHtml = "",
748
+ nonce,
749
+ policy,
750
+ onSlotMetric,
751
+ onError,
752
+ slots
753
+ }) => {
754
+ const resolvedPolicy = resolveStreamingSlotPolicy(policy);
755
+ const combinedOnError = createCombinedSlotErrorHandler(resolvedPolicy.onError, onError);
756
+ const combinedOnSlotMetric = createCombinedSlotMetricHandler(resolvedPolicy.onSlotMetric, onSlotMetric);
757
+ const effectivePolicy = {
758
+ ...resolvedPolicy,
759
+ onSlotMetric: combinedOnSlotMetric
760
+ };
761
+ const preparedSlots = prepareSlots({
762
+ onError: combinedOnError,
763
+ onSlotMetric: combinedOnSlotMetric,
764
+ policy: effectivePolicy,
765
+ slots
766
+ });
767
+ const encoder = new TextEncoder;
768
+ const createPendingSlots = (controller) => preparedSlots.map((slot) => {
769
+ const fallback = renderStreamingSlotPlaceholder(slot.id, normalizeSlotText(slot.fallbackHtml, ""));
770
+ controller.enqueue(toUint8(fallback, encoder));
771
+ return resolveSlot(slot, combinedOnError, effectivePolicy, combinedOnSlotMetric);
772
+ });
773
+ const handleResolvedPreparedSlot = async (controller, pending) => {
774
+ const { original, result } = await nextResolvedSlot(pending);
775
+ const index = pending.indexOf(original);
776
+ if (index >= 0)
777
+ pending.splice(index, 1);
778
+ if (result.payload === null) {
779
+ return;
780
+ }
781
+ emitSlotMetric({
782
+ bytes: result.bytes,
783
+ durationMs: result.durationMs,
784
+ slotId: result.id,
785
+ type: "patched"
786
+ }, combinedOnSlotMetric);
787
+ controller.enqueue(toUint8(renderStreamingSlotPatchTag(result.id, result.payload, nonce), encoder));
788
+ };
789
+ const streamPreparedSlots = async (controller) => {
790
+ const pending = createPendingSlots(controller);
791
+ const streamNextPreparedSlot = async () => {
792
+ if (pending.length === 0) {
793
+ return;
794
+ }
795
+ await handleResolvedPreparedSlot(controller, pending);
796
+ await streamNextPreparedSlot();
797
+ };
798
+ await streamNextPreparedSlot();
799
+ };
800
+ const resolveHeaderHtml = () => {
801
+ const needsRuntimeTag = preparedSlots.length > 0 && !headerHtml.includes(STREAMING_RUNTIME_GLOBAL);
802
+ if (!needsRuntimeTag) {
803
+ return headerHtml;
804
+ }
805
+ return injectHtmlIntoHead(headerHtml, renderStreamingSlotsRuntimeTag(nonce));
806
+ };
807
+ return new ReadableStream({
808
+ async start(controller) {
809
+ try {
810
+ const header = resolveHeaderHtml();
811
+ controller.enqueue(toUint8(header, encoder));
812
+ await streamPreparedSlots(controller);
813
+ enqueueEncodedText(controller, encoder, footerHtml);
814
+ controller.close();
815
+ } catch (error) {
816
+ controller.error(error);
817
+ }
818
+ }
819
+ });
820
+ };
821
+ var init_streamingSlots = __esm(() => {
822
+ init_constants();
823
+ init_escapeScriptContent();
824
+ CLOSING_BODY_TAG_LENGTH = CLOSING_BODY_TAG.length;
825
+ CLOSING_HEAD_TAG_LENGTH = CLOSING_HEAD_TAG2.length;
826
+ CLOSING_PAGE_TAG_REGEX = /<\/body>\s*<\/html>\s*$/i;
827
+ currentStreamingSlotPolicy = {
828
+ errorHtml: undefined,
829
+ fallbackHtml: "",
830
+ maxSlotHtmlSizeBytes: STREAMING_SLOT_MAX_HTML_BYTES,
831
+ maxSlotsPerResponse: STREAMING_SLOT_MAX_PER_RESPONSE,
832
+ timeoutMs: STREAMING_SLOT_TIMEOUT_MS
833
+ };
834
+ });
835
+
836
+ // src/utils/getDurationString.ts
837
+ var getDurationString = (duration) => {
838
+ let durationString;
839
+ if (duration < MILLISECONDS_IN_A_SECOND) {
840
+ durationString = `${duration.toFixed(TIME_PRECISION)}ms`;
841
+ } else if (duration < MILLISECONDS_IN_A_MINUTE) {
842
+ durationString = `${(duration / MILLISECONDS_IN_A_SECOND).toFixed(TIME_PRECISION)}s`;
843
+ } else {
844
+ const totalSeconds = Math.round(duration / MILLISECONDS_IN_A_SECOND);
845
+ const minutes = Math.floor(totalSeconds / 60);
846
+ const seconds = totalSeconds % 60;
847
+ durationString = seconds === 0 ? `${minutes}m` : `${minutes}m ${seconds}s`;
848
+ }
849
+ return durationString;
850
+ };
851
+ var init_getDurationString = __esm(() => {
852
+ init_constants();
853
+ });
854
+
855
+ // src/utils/startupBanner.ts
856
+ var colors, MONTHS, formatTimestamp = () => {
857
+ const now = new Date;
858
+ const month = MONTHS[now.getMonth()];
859
+ const day = now.getDate().toString().padStart(2, "0");
860
+ let hours = now.getHours();
861
+ const minutes = now.getMinutes().toString().padStart(2, "0");
862
+ const seconds = now.getSeconds().toString().padStart(2, "0");
863
+ const ampm = hours >= HOURS_IN_HALF_DAY ? "PM" : "AM";
864
+ hours = hours % HOURS_IN_HALF_DAY || HOURS_IN_HALF_DAY;
865
+ return `${month} ${day} ${hours}:${minutes}:${seconds} ${ampm}`;
866
+ }, startupBanner = (options) => {
867
+ const {
868
+ version,
869
+ readyDuration,
870
+ buildDuration,
871
+ port,
872
+ host,
873
+ networkUrl,
874
+ protocol = "http"
875
+ } = options;
876
+ const name = `${colors.cyan}${colors.bold}ABSOLUTEJS${colors.reset}`;
877
+ const ver = `${colors.dim}v${version}${colors.reset}`;
878
+ const time = `${colors.dim}ready in${colors.reset} ${colors.bold}${getDurationString(readyDuration)}${colors.reset}`;
879
+ const build = typeof buildDuration === "number" && Number.isFinite(buildDuration) ? ` ${colors.dim}(build ${getDurationString(buildDuration)})${colors.reset}` : "";
880
+ console.log("");
881
+ console.log(` ${name} ${ver} ${time}${build}`);
882
+ console.log("");
883
+ console.log(` ${colors.green}\u279C${colors.reset} ${colors.bold}Local:${colors.reset} ${protocol}://${host === "0.0.0.0" ? "localhost" : host}:${port}/`);
884
+ if (networkUrl) {
885
+ console.log(` ${colors.green}\u279C${colors.reset} ${colors.bold}Network:${colors.reset} ${networkUrl}`);
886
+ }
887
+ console.log("");
888
+ };
889
+ var init_startupBanner = __esm(() => {
890
+ init_constants();
891
+ init_getDurationString();
892
+ colors = {
893
+ bold: "\x1B[1m",
894
+ cyan: "\x1B[36m",
895
+ dim: "\x1B[2m",
896
+ green: "\x1B[32m",
897
+ reset: "\x1B[0m"
898
+ };
899
+ MONTHS = [
900
+ "Jan",
901
+ "Feb",
902
+ "Mar",
903
+ "Apr",
904
+ "May",
905
+ "Jun",
906
+ "Jul",
907
+ "Aug",
908
+ "Sep",
909
+ "Oct",
910
+ "Nov",
911
+ "Dec"
912
+ ];
913
+ });
914
+
915
+ // src/utils/logger.ts
916
+ var colors2, frameworkColors, formatPath = (filePath) => {
917
+ const cwd = process.cwd();
918
+ let relative = filePath.startsWith(cwd) ? filePath.slice(cwd.length + 1) : filePath;
919
+ relative = relative.replace(/\\/g, "/");
920
+ if (!relative.startsWith("/")) {
921
+ relative = `/${relative}`;
922
+ }
923
+ return relative;
924
+ }, getFrameworkColor = (framework) => frameworkColors[framework] || colors2.white, log = (action, options) => {
925
+ const timestamp = `${colors2.dim}${formatTimestamp()}${colors2.reset}`;
926
+ const tag = `${colors2.cyan}[hmr]${colors2.reset}`;
927
+ let message = action;
928
+ if (options?.path) {
929
+ const pathColor = options.framework ? getFrameworkColor(options.framework) : colors2.white;
930
+ message += ` ${pathColor}${formatPath(options.path)}${colors2.reset}`;
931
+ }
932
+ if (options?.duration !== undefined) {
933
+ message += ` ${colors2.dim}(${options.duration}ms)${colors2.reset}`;
934
+ }
935
+ console.log(`${timestamp} ${tag} ${message}`);
936
+ }, logCssUpdate = (path, framework, duration) => {
937
+ log("css update", { duration, framework: framework ?? "css", path });
938
+ }, logError = (message, error) => {
939
+ const timestamp = `${colors2.dim}${formatTimestamp()}${colors2.reset}`;
940
+ const tag = `${colors2.red}[hmr]${colors2.reset}`;
941
+ const errorMsg = error instanceof Error ? error.message : error;
942
+ const fullMessage = `${colors2.red}error${colors2.reset} ${message}${errorMsg ? `: ${errorMsg}` : ""}`;
943
+ console.error(`${timestamp} ${tag} ${fullMessage}`);
944
+ }, logHmrUpdate = (path, framework, duration) => {
945
+ log("hmr update", { duration, framework, path });
946
+ }, logScriptUpdate = (path, framework, duration) => {
947
+ log("script update", { duration, framework, path });
948
+ }, logServerReload = () => {
949
+ log(`${colors2.cyan}server module reloaded${colors2.reset}`);
950
+ }, logWarn = (message) => {
951
+ const timestamp = `${colors2.dim}${formatTimestamp()}${colors2.reset}`;
952
+ const tag = `${colors2.yellow}[hmr]${colors2.reset}`;
953
+ console.log(`${timestamp} ${tag} ${colors2.yellow}warning ${message}${colors2.reset}`);
954
+ };
955
+ var init_logger = __esm(() => {
956
+ init_startupBanner();
957
+ colors2 = {
958
+ blue: "\x1B[34m",
959
+ bold: "\x1B[1m",
960
+ cyan: "\x1B[36m",
961
+ dim: "\x1B[2m",
962
+ green: "\x1B[32m",
963
+ magenta: "\x1B[35m",
964
+ red: "\x1B[31m",
965
+ reset: "\x1B[0m",
966
+ white: "\x1B[37m",
967
+ yellow: "\x1B[33m"
968
+ };
969
+ frameworkColors = {
970
+ angular: colors2.magenta,
971
+ assets: colors2.dim,
972
+ css: colors2.cyan,
973
+ html: colors2.white,
974
+ htmx: colors2.white,
975
+ react: colors2.blue,
976
+ svelte: colors2.yellow,
977
+ vue: colors2.green
978
+ };
979
+ });
980
+
981
+ // src/core/ssrCache.ts
982
+ var dirtyFrameworks, isSsrCacheDirty = (framework) => dirtyFrameworks.has(framework), markSsrCacheDirty = (framework) => {
983
+ dirtyFrameworks.add(framework);
984
+ };
985
+ var init_ssrCache = __esm(() => {
986
+ dirtyFrameworks = new Set;
987
+ });
988
+
989
+ // src/utils/stringModifiers.ts
990
+ var normalizeSlug = (str) => str.trim().replace(/\s+/g, "-").replace(/[^A-Za-z0-9\-_]+/g, "").replace(/[-_]{2,}/g, "-"), toKebab = (str) => normalizeSlug(str).replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase(), toPascal = (str) => {
991
+ if (!str.includes("-") && !str.includes("_")) {
992
+ return str.charAt(0).toUpperCase() + str.slice(1);
993
+ }
994
+ return normalizeSlug(str).split(/[-_]/).filter(Boolean).map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1).toLowerCase()).join("");
995
+ }, toScreamingSnake = (str) => str.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toUpperCase();
996
+
997
+ // src/core/islandManifest.ts
998
+ var toIslandFrameworkSegment = (framework) => framework[0]?.toUpperCase() + framework.slice(1), collectFrameworkIslands = (manifest, prefix) => {
999
+ const entries = {};
1000
+ let found = false;
1001
+ for (const [key, value] of Object.entries(manifest)) {
1002
+ if (!key.startsWith(prefix))
1003
+ continue;
1004
+ const component = key.slice(prefix.length);
1005
+ if (!component)
1006
+ continue;
1007
+ entries[component] = value;
1008
+ found = true;
1009
+ }
1010
+ return found ? entries : undefined;
1011
+ }, getIslandManifestEntries = (manifest) => {
1012
+ const islands = {};
1013
+ const frameworks = ["react", "svelte", "vue", "angular"];
1014
+ for (const framework of frameworks) {
1015
+ const prefix = `Island${toIslandFrameworkSegment(framework)}`;
1016
+ const entries = collectFrameworkIslands(manifest, prefix);
1017
+ if (entries)
1018
+ islands[framework] = entries;
1019
+ }
1020
+ return islands;
1021
+ }, getIslandManifestKey = (framework, component) => `Island${toIslandFrameworkSegment(framework)}${component}`;
1022
+
1023
+ // src/core/islands.ts
1024
+ function getIslandComponent(component) {
1025
+ if (isIslandComponentDefinition(component)) {
1026
+ return component.component;
1027
+ }
1028
+ return component;
1029
+ }
1030
+ var defineIslandComponent = (component, options) => ({
1031
+ component,
1032
+ export: options.export,
1033
+ source: options.source
1034
+ }), defineIslandRegistry = (registry) => registry, isRecord3 = (value) => typeof value === "object" && value !== null, getIslandBuildReference = (component) => {
1035
+ if (!isIslandComponentDefinition(component))
1036
+ return null;
1037
+ return {
1038
+ export: component.export,
1039
+ source: component.source
1040
+ };
1041
+ }, isIslandComponentDefinition = (value) => isRecord3(value) && ("component" in value) && ("source" in value) && typeof value.source === "string", parseIslandProps = (rawProps) => {
1042
+ if (!rawProps)
1043
+ return {};
1044
+ return JSON.parse(rawProps);
1045
+ }, serializeIslandProps = (props) => JSON.stringify(props ?? {});
1046
+ var init_islands = () => {};
1047
+
1048
+ // src/core/islandMarkupAttributes.ts
1049
+ var getIslandMarkerAttributes = (props, islandId) => ({
1050
+ "data-component": props.component,
1051
+ "data-framework": props.framework,
1052
+ "data-hydrate": props.hydrate ?? "load",
1053
+ "data-island": "true",
1054
+ ...islandId ? { "data-island-id": islandId } : {},
1055
+ "data-props": serializeIslandProps(props.props)
1056
+ }), escapeHtmlAttribute = (value) => value.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"), serializeIslandAttributes = (attributes) => Object.entries(attributes).map(([key, value]) => `${key}="${escapeHtmlAttribute(value)}"`).join(" ");
1057
+ var init_islandMarkupAttributes = __esm(() => {
1058
+ init_islands();
1059
+ });
1060
+
1061
+ // src/core/currentIslandRegistry.ts
1062
+ var requireCurrentIslandRegistry = () => {
1063
+ const registry = globalThis.__absoluteIslandRegistry;
1064
+ if (!registry) {
1065
+ throw new Error("No island registry is active. Configure `islands.registry` in absolute.config.ts before rendering <Island />.");
1066
+ }
1067
+ return registry;
1068
+ }, setCurrentIslandRegistry = (registry) => {
1069
+ globalThis.__absoluteIslandRegistry = registry;
1070
+ };
1071
+
1072
+ // src/angular/resolveAngularPackage.ts
1073
+ import { existsSync, readFileSync } from "fs";
1074
+ import { join, resolve } from "path";
1075
+ var resolveAngularPackageDir = (specifier) => {
1076
+ const fromCompiledRuntime = process.env.ABSOLUTE_BUILD_DIR ? resolve(process.env.ABSOLUTE_BUILD_DIR, "node_modules", specifier) : null;
1077
+ if (fromCompiledRuntime && existsSync(fromCompiledRuntime)) {
1078
+ return fromCompiledRuntime;
1079
+ }
1080
+ const fromProject = resolve(process.cwd(), "node_modules", specifier);
1081
+ if (existsSync(fromProject)) {
1082
+ return fromProject;
1083
+ }
1084
+ return null;
1085
+ }, resolvePackageEntry = (packageDir) => {
1086
+ try {
1087
+ const pkg = JSON.parse(readFileSync(join(packageDir, "package.json"), "utf-8"));
1088
+ const rootExport = pkg.exports?.["."];
1089
+ const entry = (typeof rootExport === "string" ? rootExport : rootExport?.default) ?? pkg.module ?? pkg.main ?? "index.js";
1090
+ return join(packageDir, entry);
1091
+ } catch {
1092
+ return packageDir;
1093
+ }
1094
+ }, resolveAngularPackage = (specifier) => {
1095
+ const packageDir = resolveAngularPackageDir(specifier);
1096
+ if (packageDir)
1097
+ return resolvePackageEntry(packageDir);
1098
+ return specifier;
1099
+ }, toSafeVendorName = (specifier) => specifier.replace(/^@/, "").replace(/\//g, "_"), resolveAngularRuntimePath = (specifier) => {
1100
+ const buildDir = process.env.ABSOLUTE_BUILD_DIR;
1101
+ if (buildDir) {
1102
+ const vendorPath = join(buildDir, "angular", "vendor", "server", `${toSafeVendorName(specifier)}.js`);
1103
+ if (existsSync(vendorPath))
1104
+ return vendorPath;
1105
+ }
1106
+ return resolveAngularPackage(specifier);
1107
+ };
1108
+ var init_resolveAngularPackage = () => {};
1109
+
1110
+ // src/angular/angularPatch.ts
1111
+ var exports_angularPatch = {};
1112
+ __export(exports_angularPatch, {
1113
+ applyPatches: () => applyPatches
1114
+ });
1115
+ var ensureHead = (doc) => {
1116
+ if (!doc || doc.head || !doc.documentElement) {
1117
+ return;
1118
+ }
1119
+ const head = doc.createElement("head");
1120
+ doc.documentElement.insertBefore(head, doc.documentElement.firstChild);
1121
+ }, SSR_LAYOUT_RECT, layoutPatchApplied = false, collectPrototypeChain = (instance) => {
1122
+ const protos = [];
1123
+ let current = instance ? Object.getPrototypeOf(instance) : null;
1124
+ while (current && current !== Object.prototype) {
1125
+ protos.push(current);
1126
+ current = Object.getPrototypeOf(current);
1127
+ }
1128
+ return protos;
1129
+ }, patchElementLayout = (doc) => {
1130
+ if (layoutPatchApplied || !doc) {
1131
+ return;
1132
+ }
1133
+ let element;
1134
+ try {
1135
+ element = doc.createElement("div");
1136
+ } catch {
1137
+ return;
1138
+ }
1139
+ const protos = collectPrototypeChain(element);
1140
+ if (protos.length === 0)
1141
+ return;
1142
+ const copyLayoutRect = (rect) => ({ ...rect });
1143
+ const createLayoutRect = () => copyLayoutRect(SSR_LAYOUT_RECT);
1144
+ const getClientRects = () => [];
1145
+ const noop = () => {
1146
+ return;
1147
+ };
1148
+ const numericProps = [
1149
+ "clientWidth",
1150
+ "clientHeight",
1151
+ "clientLeft",
1152
+ "clientTop",
1153
+ "offsetWidth",
1154
+ "offsetHeight",
1155
+ "offsetLeft",
1156
+ "offsetTop",
1157
+ "scrollWidth",
1158
+ "scrollHeight",
1159
+ "scrollLeft",
1160
+ "scrollTop"
1161
+ ];
1162
+ for (const proto of protos) {
1163
+ const define = (name, value) => {
1164
+ const descriptor = Object.getOwnPropertyDescriptor(proto, name);
1165
+ if (typeof descriptor?.value === "function")
1166
+ return;
1167
+ Object.defineProperty(proto, name, {
1168
+ configurable: true,
1169
+ value,
1170
+ writable: true
1171
+ });
1172
+ };
1173
+ define("getBoundingClientRect", createLayoutRect);
1174
+ define("getClientRects", getClientRects);
1175
+ define("scrollTo", noop);
1176
+ define("scrollBy", noop);
1177
+ define("scrollIntoView", noop);
1178
+ define("focus", noop);
1179
+ define("blur", noop);
1180
+ for (const prop of numericProps) {
1181
+ const desc = Object.getOwnPropertyDescriptor(proto, prop);
1182
+ if (desc)
1183
+ continue;
1184
+ Object.defineProperty(proto, prop, {
1185
+ configurable: true,
1186
+ get: () => 0
1187
+ });
1188
+ }
1189
+ }
1190
+ layoutPatchApplied = true;
1191
+ }, applyPatches = async () => {
1192
+ const { \u{275}DominoAdapter } = await import(resolveAngularRuntimePath("@angular/platform-server"));
1193
+ if (!\u{275}DominoAdapter?.prototype) {
1194
+ console.warn("[Angular Patch] \u0275DominoAdapter not found, skipping patches");
1195
+ return false;
1196
+ }
1197
+ try {
1198
+ const adapter = new \u{275}DominoAdapter;
1199
+ const seedDoc = typeof adapter.createHtmlDocument === "function" ? adapter.createHtmlDocument() : typeof adapter.getDefaultDocument === "function" ? adapter.getDefaultDocument() : null;
1200
+ if (seedDoc) {
1201
+ patchElementLayout(seedDoc);
1202
+ const probe = seedDoc.createElement("div");
1203
+ if (typeof probe.getBoundingClientRect !== "function") {
1204
+ console.warn("[Angular Patch] Layout shim did not stick on probe element prototype chain");
1205
+ }
1206
+ }
1207
+ } catch (error) {
1208
+ console.warn("[Angular Patch] Could not eagerly patch Element prototypes:", error);
1209
+ }
1210
+ const proto = \u{275}DominoAdapter.prototype;
1211
+ const origGetBaseHref = proto.getBaseHref;
1212
+ proto.getBaseHref = function(doc) {
1213
+ if (!doc || !doc.head || typeof doc.head.children === "undefined") {
1214
+ return "";
1215
+ }
1216
+ return origGetBaseHref.call(this, doc);
1217
+ };
1218
+ const origCreateHtmlDocument = proto.createHtmlDocument;
1219
+ proto.createHtmlDocument = function() {
1220
+ const doc = origCreateHtmlDocument.call(this);
1221
+ ensureHead(doc);
1222
+ patchElementLayout(doc);
1223
+ return doc;
1224
+ };
1225
+ const origGetDefaultDocument = proto.getDefaultDocument;
1226
+ proto.getDefaultDocument = function() {
1227
+ const doc = origGetDefaultDocument.call(this);
1228
+ ensureHead(doc);
1229
+ patchElementLayout(doc);
1230
+ return doc;
1231
+ };
1232
+ return true;
1233
+ };
1234
+ var init_angularPatch = __esm(() => {
1235
+ init_resolveAngularPackage();
1236
+ SSR_LAYOUT_RECT = Object.freeze({
1237
+ bottom: 0,
1238
+ height: 0,
1239
+ left: 0,
1240
+ right: 0,
1241
+ top: 0,
1242
+ width: 0,
1243
+ x: 0,
1244
+ y: 0,
1245
+ toJSON() {
1246
+ return this;
1247
+ }
1248
+ });
1249
+ });
1250
+
1251
+ // src/angular/angularDeps.ts
1252
+ var initDominoAdapter = (platformServer) => {
1253
+ try {
1254
+ platformServer.\u{275}DominoAdapter?.makeCurrent?.();
1255
+ } catch (err) {
1256
+ console.error("Failed to initialize DominoAdapter:", err);
1257
+ }
1258
+ }, loadAngularDeps = async () => {
1259
+ if (true) {
1260
+ await import(resolveAngularRuntimePath("@angular/compiler"));
1261
+ }
1262
+ const { applyPatches: applyPatches2 } = await Promise.resolve().then(() => (init_angularPatch(), exports_angularPatch));
1263
+ await applyPatches2();
1264
+ const [platformBrowser, platformServer, common, core] = await Promise.all([
1265
+ import(resolveAngularRuntimePath("@angular/platform-browser")),
1266
+ import(resolveAngularRuntimePath("@angular/platform-server")),
1267
+ import(resolveAngularRuntimePath("@angular/common")),
1268
+ import(resolveAngularRuntimePath("@angular/core"))
1269
+ ]);
1270
+ if (false) {}
1271
+ initDominoAdapter(platformServer);
1272
+ return {
1273
+ APP_BASE_HREF: common.APP_BASE_HREF,
1274
+ bootstrapApplication: platformBrowser.bootstrapApplication,
1275
+ DomSanitizer: platformBrowser.DomSanitizer,
1276
+ ENVIRONMENT_INITIALIZER: core.ENVIRONMENT_INITIALIZER,
1277
+ inject: core.inject,
1278
+ provideClientHydration: platformBrowser.provideClientHydration,
1279
+ provideServerRendering: platformServer.provideServerRendering,
1280
+ provideZonelessChangeDetection: core.provideZonelessChangeDetection,
1281
+ reflectComponentType: core.reflectComponentType,
1282
+ renderApplication: platformServer.renderApplication,
1283
+ REQUEST: core.REQUEST,
1284
+ REQUEST_CONTEXT: core.REQUEST_CONTEXT,
1285
+ RESPONSE_INIT: core.RESPONSE_INIT,
1286
+ Sanitizer: core.Sanitizer,
1287
+ SecurityContext: core.SecurityContext,
1288
+ withHttpTransferCacheOptions: platformBrowser.withHttpTransferCacheOptions
1289
+ };
1290
+ }, angularDeps = null, getAngularDeps = () => {
1291
+ if (!angularDeps) {
1292
+ angularDeps = loadAngularDeps();
1293
+ }
1294
+ return angularDeps;
1295
+ };
1296
+ var init_angularDeps = __esm(() => {
1297
+ init_resolveAngularPackage();
1298
+ });
1299
+
1300
+ // src/utils/registerClientScript.ts
1301
+ var scriptRegistry, requestCounter = 0, getRequestId = () => `req_${Date.now()}_${++requestCounter}`, ssrContextGetter = null, getSsrContextId = () => ssrContextGetter?.() || Object.getOwnPropertyDescriptor(globalThis, "__absolutejs_requestId")?.value, registerClientScript = (script, requestId) => {
1302
+ const id = requestId || getSsrContextId() || getRequestId();
1303
+ if (!scriptRegistry.has(id)) {
1304
+ scriptRegistry.set(id, new Set);
1305
+ }
1306
+ scriptRegistry.get(id)?.add(script);
1307
+ return id;
1308
+ }, setSsrContextGetter = (getter) => {
1309
+ ssrContextGetter = getter;
1310
+ }, clearAllClientScripts = () => {
1311
+ scriptRegistry.clear();
1312
+ }, generateClientScriptCode = (scripts) => {
1313
+ if (scripts.length === 0) {
1314
+ return "";
1315
+ }
1316
+ const scriptCode = scripts.map((script, index) => {
1317
+ const funcString = script.toString();
1318
+ const bodyMatch = funcString.match(/\{([\s\S]*)\}/);
1319
+ if (!bodyMatch || !bodyMatch[1]) {
1320
+ return "";
1321
+ }
1322
+ const body = bodyMatch[1].trim();
1323
+ return `
1324
+ (function() {
1325
+ var executed = false;
1326
+ function executeScript_${index}() {
1327
+ if (executed) return;
1328
+ executed = true;
1329
+ ${body}
1330
+ }
1331
+
1332
+ if (document.readyState === 'complete' || document.readyState === 'interactive') {
1333
+ executeScript_${index}();
1334
+ } else {
1335
+ document.addEventListener('DOMContentLoaded', executeScript_${index});
1336
+ }
1337
+
1338
+ // Watch for hydration-added elements
1339
+ var observer = new MutationObserver(function() {
1340
+ executeScript_${index}();
1341
+ if (executed) observer.disconnect();
1342
+ });
1343
+ if (!executed) {
1344
+ observer.observe(document.body || document.documentElement, { childList: true, subtree: true });
1345
+ }
1346
+
1347
+ // Single fallback timeout
1348
+ setTimeout(function() {
1349
+ executeScript_${index}();
1350
+ observer.disconnect();
1351
+ }, 1000);
1352
+ })();`;
1353
+ }).join(`
1354
+ `);
1355
+ return `<script>
1356
+ (function() {
1357
+ ${scriptCode}
1358
+ })();
1359
+ </script>`;
1360
+ }, getAndClearClientScripts = (requestId) => {
1361
+ const id = requestId || ssrContextGetter?.();
1362
+ if (!id)
1363
+ return [];
1364
+ const scripts = scriptRegistry.get(id);
1365
+ if (!scripts) {
1366
+ return [];
1367
+ }
1368
+ const scriptArray = Array.from(scripts);
1369
+ scriptRegistry.delete(id);
1370
+ return scriptArray;
1371
+ };
1372
+ var init_registerClientScript = __esm(() => {
1373
+ scriptRegistry = new Map;
1374
+ if (typeof globalThis !== "undefined") {
1375
+ Object.assign(globalThis, { registerClientScript });
1376
+ }
1377
+ });
1378
+
1379
+ // src/angular/httpTransferCache.ts
1380
+ var ABSOLUTE_HTTP_TRANSFER_CACHE_SKIP_HEADER = "x-skip-transfer-cache", buildAbsoluteHttpTransferCacheOptions = (options = {}) => {
1381
+ const {
1382
+ filter: userFilter,
1383
+ skipHeader = ABSOLUTE_HTTP_TRANSFER_CACHE_SKIP_HEADER,
1384
+ ...angularOptions
1385
+ } = options;
1386
+ return {
1387
+ includePostRequests: false,
1388
+ includeRequestsWithAuthHeaders: false,
1389
+ ...angularOptions,
1390
+ filter: (request) => !request.headers.has(skipHeader) && (userFilter?.(request) ?? true)
1391
+ };
1392
+ };
1393
+
1394
+ // src/angular/requestProviders.ts
1395
+ import { REQUEST, REQUEST_CONTEXT, RESPONSE_INIT } from "@angular/core";
1396
+ var buildRequestProviders = (deps, request, requestContext, responseInit) => [
1397
+ { provide: deps.REQUEST, useValue: request ?? null },
1398
+ { provide: deps.REQUEST_CONTEXT, useValue: requestContext ?? null },
1399
+ { provide: deps.RESPONSE_INIT, useValue: responseInit ?? null }
1400
+ ];
1401
+ var init_requestProviders = () => {};
1402
+
1403
+ // src/angular/ssrRender.ts
1404
+ var routePropsCache, cacheRouteData = (pagePath, data) => {
1405
+ const cacheKey = pagePath.split("?")[0] ?? pagePath;
1406
+ routePropsCache.set(cacheKey, data);
1407
+ }, getCachedRouteData = (pagePath) => routePropsCache.get(pagePath), selectorCache, buildProviders = (deps, sanitizer, maybeProps, tokenMap, request, requestContext, responseInit, userProviders = []) => {
1408
+ const providers = [
1409
+ deps.provideServerRendering(),
1410
+ deps.provideClientHydration(deps.withHttpTransferCacheOptions(buildAbsoluteHttpTransferCacheOptions())),
1411
+ deps.provideZonelessChangeDetection(),
1412
+ { provide: deps.APP_BASE_HREF, useValue: "/" },
1413
+ {
1414
+ provide: deps.DomSanitizer,
1415
+ useValue: sanitizer
1416
+ },
1417
+ { provide: deps.Sanitizer, useValue: sanitizer },
1418
+ ...buildRequestProviders(deps, request, requestContext, responseInit),
1419
+ ...userProviders
1420
+ ];
1421
+ if (!maybeProps) {
1422
+ return providers;
1423
+ }
1424
+ const propProviders = Object.entries(maybeProps).map(([propName, propValue]) => ({
1425
+ token: tokenMap.get(toScreamingSnake(propName)),
1426
+ value: propValue
1427
+ })).filter((entry) => entry.token).map((entry) => ({ provide: entry.token, useValue: entry.value }));
1428
+ return [...providers, ...propProviders];
1429
+ }, clearSelectorCache = () => selectorCache.clear(), isInjectionToken = (value) => {
1430
+ if (!value || typeof value !== "object") {
1431
+ return false;
1432
+ }
1433
+ return "ngMetadataName" in value && value.ngMetadataName === "InjectionToken";
1434
+ }, discoverTokens = (pageModule) => new Map(Object.entries(pageModule).filter(([, value]) => isInjectionToken(value))), resolveSelector = (deps, pagePath, PageComponent) => {
1435
+ const cached = selectorCache.get(pagePath);
1436
+ if (cached) {
1437
+ return cached;
1438
+ }
1439
+ const selector = deps.reflectComponentType(PageComponent)?.selector ?? "ng-app";
1440
+ selectorCache.set(pagePath, selector);
1441
+ return selector;
1442
+ }, injectBeforeClose = (html, snippet) => {
1443
+ if (html.includes("</body>")) {
1444
+ return html.replace("</body>", `${snippet}</body>`);
1445
+ }
1446
+ if (html.includes("</html>")) {
1447
+ return html.replace("</html>", `${snippet}</html>`);
1448
+ }
1449
+ return html + snippet;
1450
+ }, injectSsrScripts = (html, requestId, indexPath, props) => {
1451
+ let result = html;
1452
+ const registeredScripts = getAndClearClientScripts(requestId);
1453
+ if (registeredScripts.length > 0) {
1454
+ result = injectBeforeClose(result, generateClientScriptCode(registeredScripts));
1455
+ }
1456
+ if (props) {
1457
+ result = injectBeforeClose(result, `<script>window.__ABS_ANGULAR_PAGE_PROPS__ = ${JSON.stringify(props)};</script>`);
1458
+ }
1459
+ if (indexPath) {
1460
+ const escapedIndexPath = JSON.stringify(indexPath);
1461
+ result = injectBeforeClose(result, `<script>import(${escapedIndexPath});</script>`);
1462
+ }
1463
+ return result;
1464
+ }, renderAngularApp = async (deps, PageComponent, providers, document2, url = "/") => {
1465
+ const bootstrap = (context) => deps.bootstrapApplication(PageComponent, { providers }, context);
1466
+ return withSuppressedAngularDevLogs(() => deps.renderApplication(bootstrap, {
1467
+ document: document2,
1468
+ platformProviders: [],
1469
+ url
1470
+ }));
1471
+ }, withSuppressedAngularDevLogs = async (render) => {
1472
+ const origLog = console.log;
1473
+ console.log = (...args) => {
1474
+ if (typeof args[0] === "string" && args[0].includes("development mode")) {
1475
+ return;
1476
+ }
1477
+ origLog.apply(console, args);
1478
+ };
1479
+ try {
1480
+ return await render();
1481
+ } finally {
1482
+ console.log = origLog;
1483
+ }
1484
+ };
1485
+ var init_ssrRender = __esm(() => {
1486
+ init_registerClientScript();
1487
+ init_requestProviders();
1488
+ routePropsCache = new Map;
1489
+ selectorCache = new Map;
1490
+ });
1491
+
1492
+ // src/angular/islands.ts
1493
+ var exports_islands = {};
1494
+ __export(exports_islands, {
1495
+ renderAngularIslandToHtml: () => renderAngularIslandToHtml,
1496
+ mountAngularIsland: () => mountAngularIsland,
1497
+ isAngularComponent: () => isAngularComponent,
1498
+ getAngularIslandSelector: () => getAngularIslandSelector
1499
+ });
1500
+ var angularIslandSelector = "abs-angular-island", isAngularComponent = (value) => typeof value === "function", getAngularIslandSelector = (_islandId) => angularIslandSelector, getSelectorFromRenderedIsland = (rootElement) => {
1501
+ const firstChild = rootElement.firstElementChild;
1502
+ if (!(firstChild instanceof HTMLElement)) {
1503
+ return null;
1504
+ }
1505
+ const selector = firstChild.tagName.toLowerCase();
1506
+ return selector.length > 0 ? selector : null;
1507
+ }, getClientAngularComponentSelector = (component) => {
1508
+ const maybeDef = Reflect.get(component, "\u0275cmp");
1509
+ if (typeof maybeDef !== "object" || maybeDef === null) {
1510
+ return null;
1511
+ }
1512
+ const maybeSelectors = Reflect.get(maybeDef, "selectors");
1513
+ if (!Array.isArray(maybeSelectors)) {
1514
+ return null;
1515
+ }
1516
+ const [firstSelectorGroup] = maybeSelectors;
1517
+ if (!Array.isArray(firstSelectorGroup)) {
1518
+ return null;
1519
+ }
1520
+ const [selector] = firstSelectorGroup;
1521
+ return typeof selector === "string" && selector.length > 0 ? selector : null;
1522
+ }, createAngularIslandApp = async () => {
1523
+ const { EnvironmentInjector, provideZonelessChangeDetection } = await import("@angular/core");
1524
+ const { createApplication } = await import("@angular/platform-browser");
1525
+ const app = await createApplication({
1526
+ providers: [provideZonelessChangeDetection()]
1527
+ });
1528
+ const environmentInjector = app.injector.get(EnvironmentInjector);
1529
+ return { app, environmentInjector };
1530
+ }, angularIslandAppPromise = null, getAngularIslandApp = async () => {
1531
+ if (!angularIslandAppPromise) {
1532
+ angularIslandAppPromise = createAngularIslandApp();
1533
+ }
1534
+ return angularIslandAppPromise;
1535
+ }, wrapperMetadataCache, requestRenderCache, getRequestRenderCache = () => {
1536
+ const requestId = getSsrContextId();
1537
+ if (!requestId) {
1538
+ return null;
1539
+ }
1540
+ const cached = requestRenderCache.get(requestId);
1541
+ if (cached) {
1542
+ return cached;
1543
+ }
1544
+ const renderCache = new Map;
1545
+ requestRenderCache.set(requestId, renderCache);
1546
+ return renderCache;
1547
+ }, getAngularIslandWrapperKey = (component, _islandId) => {
1548
+ const componentName = typeof component.name === "string" && component.name.length > 0 ? component.name : "AngularIsland";
1549
+ return `${componentName}:${angularIslandSelector}`;
1550
+ }, getIslandRenderCacheKey = (component, props) => {
1551
+ const componentName = typeof component.name === "string" && component.name.length > 0 ? component.name : "AngularIsland";
1552
+ return `${componentName}:${JSON.stringify(props)}`;
1553
+ }, buildAngularIslandWrapperMetadata = async (component, islandId, wrapperKey) => {
1554
+ const { Component, InjectionToken, inject } = await import("@angular/core");
1555
+ const { NgComponentOutlet } = await import("@angular/common");
1556
+ const deps = await getAngularDeps();
1557
+ const selector = getAngularIslandSelector(islandId);
1558
+ const propsToken = new InjectionToken(`${wrapperKey}:props`);
1559
+
1560
+ class AngularIslandWrapperComponent {
1561
+ component = component;
1562
+ props = inject(propsToken);
1563
+ }
1564
+ return {
1565
+ deps,
1566
+ propsToken,
1567
+ selector,
1568
+ WrapperComponent: Component({
1569
+ imports: [NgComponentOutlet, component],
1570
+ selector,
1571
+ standalone: true,
1572
+ template: '<ng-container *ngComponentOutlet="component; inputs: props"></ng-container>'
1573
+ })(AngularIslandWrapperComponent)
1574
+ };
1575
+ }, createAngularIslandWrapper = async (component, islandId) => {
1576
+ const wrapperKey = getAngularIslandWrapperKey(component, islandId);
1577
+ const cached = wrapperMetadataCache.get(wrapperKey);
1578
+ if (cached) {
1579
+ return cached;
1580
+ }
1581
+ const metadataPromise = buildAngularIslandWrapperMetadata(component, islandId, wrapperKey);
1582
+ wrapperMetadataCache.set(wrapperKey, metadataPromise);
1583
+ return metadataPromise;
1584
+ }, extractAngularIslandRoot = (html, selector) => {
1585
+ const openTag = `<${selector}`;
1586
+ const start = html.indexOf(openTag);
1587
+ if (start < 0) {
1588
+ throw new Error(`Could not find Angular island root "${selector}".`);
1589
+ }
1590
+ const endTag = `</${selector}>`;
1591
+ const end = html.indexOf(endTag, start);
1592
+ if (end < 0) {
1593
+ throw new Error(`Could not close Angular island root "${selector}".`);
1594
+ }
1595
+ return html.slice(start, end + endTag.length);
1596
+ }, mountAngularIsland = async (component, element, props, islandId) => {
1597
+ await import("@angular/compiler");
1598
+ const { createComponent, inputBinding } = await import("@angular/core");
1599
+ const selector = getAngularIslandSelector(islandId);
1600
+ const { app, environmentInjector } = await getAngularIslandApp();
1601
+ let rootElement = element.querySelector(selector);
1602
+ if (!(rootElement instanceof HTMLElement)) {
1603
+ element.innerHTML = `<${selector}></${selector}>`;
1604
+ rootElement = element.querySelector(selector);
1605
+ }
1606
+ if (!(rootElement instanceof HTMLElement))
1607
+ return app;
1608
+ const componentSelector = getClientAngularComponentSelector(component) ?? getSelectorFromRenderedIsland(rootElement);
1609
+ if (!componentSelector)
1610
+ return app;
1611
+ rootElement.innerHTML = `<${componentSelector}></${componentSelector}>`;
1612
+ const hostElement = rootElement.querySelector(componentSelector);
1613
+ if (!(hostElement instanceof HTMLElement))
1614
+ return app;
1615
+ const bindings = Object.entries(props).map(([key, value]) => inputBinding(key, () => value));
1616
+ const componentRef = createComponent(component, {
1617
+ bindings,
1618
+ environmentInjector,
1619
+ hostElement
1620
+ });
1621
+ app.attachView(componentRef.hostView);
1622
+ componentRef.changeDetectorRef.detectChanges();
1623
+ window.__ABS_ANGULAR_ISLAND_APPS__ ??= [];
1624
+ window.__ABS_ANGULAR_ISLAND_APPS__.push(app);
1625
+ return app;
1626
+ }, renderAngularIslandToHtml = async (component, props, islandId) => {
1627
+ const requestCache = getRequestRenderCache();
1628
+ const renderCacheKey = getIslandRenderCacheKey(component, props);
1629
+ const cachedHtml = requestCache?.get(renderCacheKey);
1630
+ if (cachedHtml) {
1631
+ return cachedHtml;
1632
+ }
1633
+ const { deps, propsToken, selector, WrapperComponent } = await createAngularIslandWrapper(component, islandId);
1634
+ const providers = [
1635
+ deps.provideServerRendering(),
1636
+ deps.provideZonelessChangeDetection(),
1637
+ { provide: deps.APP_BASE_HREF, useValue: "/" },
1638
+ { provide: propsToken, useValue: props }
1639
+ ];
1640
+ const document2 = `<!DOCTYPE html><html><body><${selector}></${selector}></body></html>`;
1641
+ const html = await withSuppressedAngularDevLogs(() => deps.renderApplication((context) => deps.bootstrapApplication(WrapperComponent, { providers }, context), {
1642
+ document: document2,
1643
+ platformProviders: [],
1644
+ url: "/"
1645
+ }));
1646
+ const islandHtml = extractAngularIslandRoot(html, selector);
1647
+ requestCache?.set(renderCacheKey, islandHtml);
1648
+ return islandHtml;
1649
+ };
1650
+ var init_islands2 = __esm(() => {
1651
+ init_angularDeps();
1652
+ init_ssrRender();
1653
+ init_registerClientScript();
1654
+ wrapperMetadataCache = new Map;
1655
+ requestRenderCache = new Map;
1656
+ });
1657
+
1658
+ // src/core/islandSsr.ts
1659
+ var renderAngularIslandToHtmlInternal = async (component, props, islandId) => {
1660
+ const { renderAngularIslandToHtml: renderAngularIslandToHtml2 } = await Promise.resolve().then(() => (init_islands2(), exports_islands));
1661
+ return renderAngularIslandToHtml2(component, props, islandId);
1662
+ }, renderAngularIslandToHtml2, renderReactIslandToHtml = (component, props) => import("react").then(({ createElement }) => import("react-dom/server").then(({ renderToStaticMarkup }) => renderToStaticMarkup(createElement(component, props)))), renderSvelteIslandToHtml = (component, props) => import("svelte/server").then(({ render }) => {
1663
+ const { body } = render(component, { props });
1664
+ return body;
1665
+ }), renderVueIslandToHtml = (component, props) => import("vue").then(({ createSSRApp, h: createVueVNode }) => {
1666
+ const app = createSSRApp({
1667
+ render: () => createVueVNode(component, props)
1668
+ });
1669
+ return import("vue/server-renderer").then(({ renderToString }) => renderToString(app));
1670
+ });
1671
+ var init_islandSsr = __esm(() => {
1672
+ renderAngularIslandToHtml2 = renderAngularIslandToHtmlInternal;
1673
+ });
1674
+
1675
+ // src/build/resolvePackageImport.ts
1676
+ import { resolve as resolve2, join as join2 } from "path";
1677
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
1678
+ var resolveExportPath = (entry, conditions) => {
1679
+ if (typeof entry === "string")
1680
+ return entry;
1681
+ if (!entry || typeof entry !== "object")
1682
+ return null;
1683
+ for (const condition of conditions) {
1684
+ const target = Reflect.get(entry, condition);
1685
+ if (typeof target === "string") {
1686
+ return target;
1687
+ }
1688
+ }
1689
+ return null;
1690
+ }, resolvePackageImport = (specifier, conditions = ["import"]) => {
1691
+ if (specifier.startsWith(".") || specifier.startsWith("/"))
1692
+ return null;
1693
+ const parts = specifier.split("/");
1694
+ const isScoped = specifier.startsWith("@");
1695
+ const packageName = isScoped ? `${parts[0]}/${parts[1]}` : parts[0];
1696
+ const subpath = isScoped ? parts.slice(2).join("/") : parts.slice(1).join("/");
1697
+ const exportKey = subpath ? `./${subpath}` : ".";
1698
+ const currentPackageJsonPath = resolve2(process.cwd(), "package.json");
1699
+ const currentPackageJson = existsSync2(currentPackageJsonPath) ? JSON.parse(readFileSync2(currentPackageJsonPath, "utf-8")) : null;
1700
+ const currentPackageDir = currentPackageJson?.name === packageName ? process.cwd() : null;
1701
+ const packageDir = currentPackageDir ?? resolve2(process.cwd(), "node_modules", packageName ?? "");
1702
+ const packageJsonPath = join2(packageDir, "package.json");
1703
+ if (!existsSync2(packageJsonPath))
1704
+ return null;
1705
+ try {
1706
+ const packageJson = currentPackageDir && currentPackageJson ? currentPackageJson : JSON.parse(readFileSync2(packageJsonPath, "utf-8"));
1707
+ const { exports } = packageJson;
1708
+ if (!exports)
1709
+ return null;
1710
+ const entry = exports[exportKey];
1711
+ if (!entry)
1712
+ return null;
1713
+ const importPath = resolveExportPath(entry, conditions);
1714
+ if (!importPath)
1715
+ return null;
1716
+ if (currentPackageDir && importPath.startsWith("./dist/")) {
1717
+ const sourceCandidate = resolve2(packageDir, importPath.replace(/^\.\/dist\//, "./src/"));
1718
+ if (existsSync2(sourceCandidate)) {
1719
+ return sourceCandidate;
1720
+ }
1721
+ }
1722
+ const resolved = resolve2(packageDir, importPath);
1723
+ return existsSync2(resolved) ? resolved : null;
1724
+ } catch {
1725
+ return null;
1726
+ }
1727
+ };
1728
+ var init_resolvePackageImport = () => {};
1729
+
1730
+ // src/svelte/lowerIslandSyntax.ts
1731
+ var ISLAND_TAG_RE, extractBracedExpression = (text, braceStart) => {
1732
+ let depth = 0;
1733
+ for (let index = braceStart;index < text.length; index += 1) {
1734
+ const char = text[index];
1735
+ if (char === "{")
1736
+ depth += 1;
1737
+ if (char === "}")
1738
+ depth -= 1;
1739
+ if (depth === 0) {
1740
+ return text.slice(braceStart + 1, index).trim();
1741
+ }
1742
+ }
1743
+ return null;
1744
+ }, extractIslandAttribute = (attributeString, name) => {
1745
+ const quotedMatch = attributeString.match(new RegExp(`\\b${name}\\s*=\\s*["']([^"']+)["']`));
1746
+ if (quotedMatch?.[1]) {
1747
+ return { expression: JSON.stringify(quotedMatch[1]), found: true };
1748
+ }
1749
+ const attributeIndex = attributeString.search(new RegExp(`\\b${name}\\s*=\\s*\\{`));
1750
+ if (attributeIndex < 0) {
1751
+ return { expression: "", found: false };
1752
+ }
1753
+ const braceStart = attributeString.indexOf("{", attributeIndex);
1754
+ if (braceStart < 0) {
1755
+ return { expression: "", found: false };
1756
+ }
1757
+ const expression = extractBracedExpression(attributeString, braceStart);
1758
+ if (expression === null) {
1759
+ return { expression: "", found: false };
1760
+ }
1761
+ return { expression, found: true };
1762
+ }, lowerSvelteIslandSyntax = (source, _mode = "server") => {
1763
+ if (!source.includes("<Island")) {
1764
+ return { code: source, transformed: false };
1765
+ }
1766
+ let islandIndex = 0;
1767
+ const transformedMarkup = source.replace(ISLAND_TAG_RE, (fullMatch, attributeString) => {
1768
+ const framework = extractIslandAttribute(attributeString, "framework");
1769
+ const component = extractIslandAttribute(attributeString, "component");
1770
+ if (!framework.found || !component.found) {
1771
+ return fullMatch;
1772
+ }
1773
+ const hydrate = extractIslandAttribute(attributeString, "hydrate");
1774
+ const props = extractIslandAttribute(attributeString, "props");
1775
+ const slotId = `absolute-svelte-island-${islandIndex.toString(BASE_36_RADIX)}`;
1776
+ islandIndex += 1;
1777
+ const resolveExpression = `await __absoluteResolveIslandHtml(${JSON.stringify(slotId)}, { component: ${component.expression}, framework: ${framework.expression}, hydrate: ${hydrate.found ? hydrate.expression : JSON.stringify("load")}, props: ${props.found ? props.expression : "{}"} })`;
1778
+ return `<div data-absolute-island-slot="${slotId}" style="display: contents">{@html ${resolveExpression}}</div>`;
1779
+ });
1780
+ const importLine = 'import { resolveIslandHtml as __absoluteResolveIslandHtml } from "@absolutejs/absolute/svelte";';
1781
+ if (transformedMarkup.includes("<script")) {
1782
+ return {
1783
+ code: transformedMarkup.replace(/<script(\s[^>]*)?>/, (match) => `${match}
1784
+ ${importLine}
1785
+ `),
1786
+ transformed: true
1787
+ };
1788
+ }
1789
+ return {
1790
+ code: `<script lang="ts">
1791
+ ${importLine}
1792
+ </script>
1793
+ ${transformedMarkup}`,
1794
+ transformed: true
1795
+ };
1796
+ };
1797
+ var init_lowerIslandSyntax = __esm(() => {
1798
+ init_constants();
1799
+ ISLAND_TAG_RE = /<Island\b([\s\S]*?)\/>/g;
1800
+ });
1801
+
1802
+ // src/svelte/lowerAwaitSlotSyntax.ts
1803
+ var AWAIT_BLOCK_RE, escapeTemplateLiteral = (value) => value.replaceAll("\\", "\\\\").replaceAll("`", "\\`").replaceAll("${", "\\${"), markupToTemplateLiteral = (markup) => {
1804
+ const escaped = escapeTemplateLiteral(markup.trim());
1805
+ const withExpressions = escaped.replace(/\{([^{}]+)\}/g, (_, expression) => `\${${String(expression).trim()}}`);
1806
+ return `\`${withExpressions}\``;
1807
+ }, lowerSvelteAwaitSlotSyntax = (source) => {
1808
+ if (!source.includes("{#await")) {
1809
+ return { code: source, transformed: false };
1810
+ }
1811
+ let awaitIndex = 0;
1812
+ let transformed = false;
1813
+ const lowered = source.replace(AWAIT_BLOCK_RE, (fullMatch, awaitExpression, pendingMarkup, thenIdentifier, thenMarkup, catchIdentifier, catchMarkup) => {
1814
+ const trimmedAwaitExpression = awaitExpression.trim();
1815
+ if (!trimmedAwaitExpression) {
1816
+ return fullMatch;
1817
+ }
1818
+ const slotId = `absolute-svelte-await-${awaitIndex.toString(BASE_36_RADIX)}`;
1819
+ awaitIndex += 1;
1820
+ transformed = true;
1821
+ const thenValueIdentifier = thenIdentifier?.trim() || "__awaitValue";
1822
+ const catchValueIdentifier = catchIdentifier?.trim() || "__awaitError";
1823
+ const fallbackHtml = markupToTemplateLiteral(pendingMarkup);
1824
+ const resolvedHtml = markupToTemplateLiteral(thenMarkup);
1825
+ const rejectedHtml = typeof catchMarkup === "string" ? markupToTemplateLiteral(catchMarkup) : null;
1826
+ const catchBranch = rejectedHtml ? `catch (${catchValueIdentifier}) { return ${rejectedHtml}; }` : "catch (_absoluteAwaitError) { throw _absoluteAwaitError; }";
1827
+ return `<AbsoluteAwaitSlot id="${slotId}" fallbackHtml={${fallbackHtml}} resolve={async () => { try { const ${thenValueIdentifier} = await (${trimmedAwaitExpression}); return ${resolvedHtml}; } ${catchBranch} }} />`;
1828
+ });
1829
+ if (!transformed) {
1830
+ return { code: source, transformed: false };
1831
+ }
1832
+ const importLine = 'import AbsoluteAwaitSlot from "@absolutejs/absolute/svelte/components/AwaitSlot.svelte";';
1833
+ if (lowered.includes("<script")) {
1834
+ return {
1835
+ code: lowered.replace(/<script(\s[^>]*)?>/, (match) => `${match}
1836
+ ${importLine}
1837
+ `),
1838
+ transformed: true
1839
+ };
1840
+ }
1841
+ return {
1842
+ code: `<script lang="ts">
1843
+ ${importLine}
1844
+ </script>
1845
+ ${lowered}`,
1846
+ transformed: true
1847
+ };
1848
+ };
1849
+ var init_lowerAwaitSlotSyntax = __esm(() => {
1850
+ init_constants();
1851
+ AWAIT_BLOCK_RE = /\{#await\s+([^}]+)\}([\s\S]*?)\{:then(?:\s+([A-Za-z_$][\w$]*))?\}([\s\S]*?)(?:\{:catch(?:\s+([A-Za-z_$][\w$]*))?\}([\s\S]*?))?\{\/await\}/g;
1852
+ });
1853
+
1854
+ // src/build/stylePreprocessor.ts
1855
+ var exports_stylePreprocessor = {};
1856
+ __export(exports_stylePreprocessor, {
1857
+ stylePreprocessorPlugin: () => stylePreprocessorPlugin,
1858
+ recordStyleOutput: () => recordStyleOutput,
1859
+ isStylePath: () => isStylePath,
1860
+ isStyleModulePath: () => isStyleModulePath,
1861
+ isPreprocessableStylePath: () => isPreprocessableStylePath,
1862
+ getStyleBaseName: () => getStyleBaseName,
1863
+ getCssOutputExtension: () => getCssOutputExtension,
1864
+ forgetStyleEntry: () => forgetStyleEntry,
1865
+ findStyleEntriesImporting: () => findStyleEntriesImporting,
1866
+ createSvelteStylePreprocessor: () => createSvelteStylePreprocessor,
1867
+ createStyleTransformConfig: () => createStyleTransformConfig,
1868
+ createStylePreprocessorPlugin: () => createStylePreprocessorPlugin,
1869
+ compileStyleSource: () => compileStyleSource,
1870
+ compileStyleFileIfNeededSync: () => compileStyleFileIfNeededSync,
1871
+ compileStyleFileIfNeeded: () => compileStyleFileIfNeeded,
1872
+ addStyleImporter: () => addStyleImporter
1873
+ });
1874
+ import { createHash } from "crypto";
1875
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
1876
+ import { readFile } from "fs/promises";
1877
+ import { createRequire } from "module";
2
1878
  import {
3
- useIslandStore
4
- } from "../chunk-tx9edm1x.js";
5
- import {
6
- handleVuePageRequest
7
- } from "../chunk-e3r9fxaa.js";
8
- import {
9
- StreamSlot,
10
- SuspenseSlot
11
- } from "../chunk-g15qj669.js";
12
- import {
13
- Image
14
- } from "../chunk-9c5tj4k3.js";
15
- import"../chunk-798spvzv.js";
16
- import"../chunk-gd6wmknh.js";
17
- import"../chunk-mtgf69xn.js";
18
- import"../chunk-v5vmsxmy.js";
19
- import"../chunk-c1jfjnka.js";
20
- import"../chunk-d9c0am65.js";
21
- import"../chunk-cbkrwmvh.js";
22
- import {
23
- requireCurrentIslandRegistry
24
- } from "../chunk-5003emhv.js";
25
- import"../chunk-sd39p726.js";
26
- import"../chunk-gf0ygptk.js";
27
- import"../chunk-851whwc7.js";
28
- import"../chunk-qxq2zcty.js";
29
- import {
30
- preserveIslandMarkup
31
- } from "../chunk-fak944et.js";
32
- import"../chunk-s6defjk2.js";
33
- import"../chunk-p5504p14.js";
34
- import {
35
- renderIslandResult
36
- } from "../chunk-9j59emg3.js";
37
- import"../chunk-9ve9jq72.js";
38
- import"../chunk-7fw6x3js.js";
39
- import"../chunk-mbazhahf.js";
40
- import"../chunk-xnt8c6h2.js";
41
- import"../chunk-qh75agse.js";
1879
+ dirname as dirname2,
1880
+ extname,
1881
+ isAbsolute,
1882
+ join as join3,
1883
+ relative,
1884
+ resolve as resolve3
1885
+ } from "path";
1886
+ import { fileURLToPath } from "url";
1887
+ var CSS_EXTENSION_PATTERN, STYLE_EXTENSION_PATTERN, STYLE_MODULE_EXTENSION_PATTERN, STYLE_LANGUAGE_PATTERN, importOptionalPeer, requireOptionalPeer, requireFromCwd, isPreprocessableStylePath = (filePath) => STYLE_EXTENSION_PATTERN.test(filePath), isStyleModulePath = (filePath) => STYLE_MODULE_EXTENSION_PATTERN.test(filePath), isStylePath = (filePath) => /\.(css|s[ac]ss|less|styl(?:us)?)$/i.test(filePath), getStyleBaseName = (filePath) => filePath.replace(/\.(css|s[ac]ss|less|styl(?:us)?)$/i, ""), getStyleLanguage = (filePathOrLanguage) => {
1888
+ const normalized = filePathOrLanguage.toLowerCase();
1889
+ if (normalized === "scss" || normalized.endsWith(".scss"))
1890
+ return "scss";
1891
+ if (normalized === "sass" || normalized.endsWith(".sass"))
1892
+ return "sass";
1893
+ if (normalized === "less" || normalized.endsWith(".less"))
1894
+ return "less";
1895
+ if (normalized === "styl" || normalized === "stylus" || normalized.endsWith(".styl") || normalized.endsWith(".stylus"))
1896
+ return "stylus";
1897
+ return null;
1898
+ }, missingDependencyError = (name, filePath) => new Error(`Unable to compile ${filePath}: install optional dependency "${name}" to use this stylesheet preprocessor.`), throwPreprocessorError = (error, filePath, language) => {
1899
+ if (!(error instanceof Error)) {
1900
+ throw new Error(`${language} compile failed in ${filePath}: ${String(error)}`);
1901
+ }
1902
+ const detail = error;
1903
+ const sassLine = detail.span?.start?.line;
1904
+ const sassCol = detail.span?.start?.column;
1905
+ const line = detail.line ?? sassLine;
1906
+ const column = detail.column ?? sassCol;
1907
+ const location = typeof line === "number" ? `:${line}${typeof column === "number" ? `:${column}` : ""}` : "";
1908
+ const message = detail.formatted ?? detail.message;
1909
+ const wrapped = new Error(`${language} compile failed in ${filePath}${location}
1910
+ ${message}`);
1911
+ wrapped.cause = error;
1912
+ throw wrapped;
1913
+ }, requireOptionalPeerSync = (specifier) => {
1914
+ try {
1915
+ return requireFromCwd(specifier);
1916
+ } catch {
1917
+ return requireOptionalPeer(specifier);
1918
+ }
1919
+ }, normalizeLoadPaths = (filePath, paths = []) => [
1920
+ dirname2(filePath),
1921
+ process.cwd(),
1922
+ ...paths.map((path) => resolve3(process.cwd(), path))
1923
+ ], tsconfigAliasCache, stripJsonComments = (source) => source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1"), normalizeAliasEntries = (aliases) => Object.entries(aliases ?? {}).map(([pattern, value]) => ({
1924
+ pattern,
1925
+ replacements: Array.isArray(value) ? value : [value]
1926
+ })), readTsconfigAliases = () => {
1927
+ const cwd = process.cwd();
1928
+ if (tsconfigAliasCache?.cwd === cwd)
1929
+ return tsconfigAliasCache;
1930
+ const tsconfigPath = resolve3(cwd, "tsconfig.json");
1931
+ const empty = { aliases: [], baseUrl: cwd, cwd };
1932
+ if (!existsSync3(tsconfigPath)) {
1933
+ tsconfigAliasCache = empty;
1934
+ return empty;
1935
+ }
1936
+ try {
1937
+ const parsed = JSON.parse(stripJsonComments(readFileSync3(tsconfigPath, "utf-8")));
1938
+ const compilerOptions = parsed.compilerOptions ?? {};
1939
+ const baseUrl = resolve3(cwd, compilerOptions.baseUrl ?? ".");
1940
+ tsconfigAliasCache = {
1941
+ aliases: normalizeAliasEntries(compilerOptions.paths),
1942
+ baseUrl,
1943
+ cwd
1944
+ };
1945
+ } catch {
1946
+ tsconfigAliasCache = empty;
1947
+ }
1948
+ return tsconfigAliasCache;
1949
+ }, getAliasEntries = (config) => {
1950
+ const tsconfig = readTsconfigAliases();
1951
+ return {
1952
+ aliases: [
1953
+ ...normalizeAliasEntries(config?.aliases),
1954
+ ...tsconfig.aliases
1955
+ ],
1956
+ baseUrl: tsconfig.baseUrl
1957
+ };
1958
+ }, aliasPatternToRegExp = (pattern) => new RegExp(`^${pattern.split("*").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("(.+)")}$`), resolveAliasTargets = (specifier, config) => {
1959
+ const { aliases, baseUrl } = getAliasEntries(config);
1960
+ const targets = [];
1961
+ for (const alias of aliases) {
1962
+ const match = specifier.match(aliasPatternToRegExp(alias.pattern));
1963
+ if (!match)
1964
+ continue;
1965
+ const wildcard = match[1] ?? "";
1966
+ for (const replacement of alias.replacements) {
1967
+ targets.push(resolve3(baseUrl, replacement.replace("*", wildcard)));
1968
+ }
1969
+ }
1970
+ return targets;
1971
+ }, getLanguageExtensions = (language) => {
1972
+ if (language === "less")
1973
+ return [".less", ".css"];
1974
+ if (language === "stylus")
1975
+ return [".styl", ".stylus", ".css"];
1976
+ return [".scss", ".sass", ".css"];
1977
+ }, getCandidatePaths = (basePath, language) => {
1978
+ const ext = extname(basePath);
1979
+ const paths = ext ? [basePath] : getLanguageExtensions(language).flatMap((extension) => [
1980
+ `${basePath}${extension}`,
1981
+ join3(basePath, `index${extension}`)
1982
+ ]);
1983
+ if (language === "scss" || language === "sass") {
1984
+ return paths.flatMap((path) => {
1985
+ const dir = dirname2(path);
1986
+ const base = path.slice(dir.length + 1);
1987
+ return [path, join3(dir, `_${base}`)];
1988
+ });
1989
+ }
1990
+ return paths;
1991
+ }, resolveImportPath = (specifier, fromDirectory, loadPaths, language, config) => {
1992
+ const rawCandidates = [
1993
+ ...resolveAliasTargets(specifier, config),
1994
+ isAbsolute(specifier) ? specifier : resolve3(fromDirectory, specifier),
1995
+ ...loadPaths.map((path) => resolve3(path, specifier))
1996
+ ];
1997
+ for (const candidate of rawCandidates.flatMap((path) => getCandidatePaths(path, language))) {
1998
+ if (existsSync3(candidate))
1999
+ return candidate;
2000
+ }
2001
+ return null;
2002
+ }, isExternalCssUrl = (url) => /^(?:[a-z][a-z0-9+.-]*:|\/\/|#|\/)/i.test(url), splitCssUrl = (url) => {
2003
+ const markerIndex = url.search(/[?#]/);
2004
+ if (markerIndex === -1)
2005
+ return { marker: "", path: url };
2006
+ return {
2007
+ marker: url.slice(markerIndex),
2008
+ path: url.slice(0, markerIndex)
2009
+ };
2010
+ }, rebaseCssUrls = (contents, sourceFile, entryFile) => {
2011
+ const sourceDir = dirname2(sourceFile);
2012
+ const entryDir = dirname2(entryFile);
2013
+ if (sourceDir === entryDir)
2014
+ return contents;
2015
+ return contents.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/gi, (match, quote, rawUrl) => {
2016
+ const trimmedUrl = rawUrl.trim();
2017
+ if (!trimmedUrl || isExternalCssUrl(trimmedUrl))
2018
+ return match;
2019
+ const { marker, path } = splitCssUrl(trimmedUrl);
2020
+ const rebased = relative(entryDir, resolve3(sourceDir, path)).replace(/\\/g, "/");
2021
+ const normalized = rebased.startsWith(".") ? rebased : `./${rebased}`;
2022
+ const nextQuote = quote || '"';
2023
+ return `url(${nextQuote}${normalized}${marker}${nextQuote})`;
2024
+ });
2025
+ }, rewriteAliasedStyleImports = (contents, sourceFile, loadPaths, language, config) => contents.replace(/(@(?:use|forward|import|require)\s+)(["'])([^"']+)\2/g, (match, prefix, quote, specifier) => {
2026
+ if (specifier.startsWith(".") || isAbsolute(specifier) || isExternalCssUrl(specifier))
2027
+ return match;
2028
+ const resolved = resolveImportPath(specifier, dirname2(sourceFile), loadPaths, language, config);
2029
+ return resolved ? `${prefix}${quote}${resolved}${quote}` : match;
2030
+ }), preprocessLoadedStyle = (contents, sourceFile, entryFile, loadPaths = [], language, config) => {
2031
+ const rebased = rebaseCssUrls(contents, sourceFile, entryFile);
2032
+ return language ? rewriteAliasedStyleImports(rebased, sourceFile, loadPaths, language, config) : rebased;
2033
+ }, extractCssModuleExports = (css) => {
2034
+ const exports = {};
2035
+ const nextCss = css.replace(/:export\s*\{([^}]*)\}/g, (_, body) => {
2036
+ for (const declaration of body.split(";")) {
2037
+ const separator = declaration.indexOf(":");
2038
+ if (separator === -1)
2039
+ continue;
2040
+ const key = declaration.slice(0, separator).trim();
2041
+ const value = declaration.slice(separator + 1).trim();
2042
+ if (key && value)
2043
+ exports[key] = value;
2044
+ }
2045
+ return "";
2046
+ });
2047
+ return { css: nextCss, exports };
2048
+ }, getSassOptions = (config, language) => ({
2049
+ ...config?.sass ?? {},
2050
+ ...language === "scss" ? config?.scss ?? {} : {}
2051
+ }), getLessOptions = (config) => config?.less ?? {}, getStylusOptions = (config) => config?.stylus ?? {}, createStyleTransformConfig = (stylePreprocessors, postcss) => postcss === undefined ? stylePreprocessors : { ...stylePreprocessors ?? {}, postcss }, withAdditionalData = (contents, additionalData) => additionalData ? `${additionalData}
2052
+ ${contents}` : contents, normalizePostcssModule = (mod) => {
2053
+ if (mod && typeof mod === "object" && "default" in mod) {
2054
+ return mod.default ?? mod;
2055
+ }
2056
+ return mod;
2057
+ }, loadPostcssConfigFile = async (configPath) => {
2058
+ const resolved = resolve3(process.cwd(), configPath);
2059
+ const loaded = resolved.endsWith(".cjs") || resolved.endsWith(".cts") ? requireOptionalPeerSync(resolved) : await importOptionalPeer(`${new URL(`file://${resolved}`).href}?t=${Date.now()}`);
2060
+ const config = normalizePostcssModule(loaded);
2061
+ const value = typeof config === "function" ? await config({
2062
+ cwd: process.cwd(),
2063
+ env: "development"
2064
+ }) : config;
2065
+ return normalizePostcssModule(value) ?? {};
2066
+ }, normalizePostcssPlugins = (plugins) => {
2067
+ if (!plugins)
2068
+ return [];
2069
+ if (Array.isArray(plugins))
2070
+ return plugins.filter(Boolean);
2071
+ const resolved = [];
2072
+ for (const [specifier, options] of Object.entries(plugins)) {
2073
+ if (options === false)
2074
+ continue;
2075
+ const mod = normalizePostcssModule(requireOptionalPeerSync(specifier));
2076
+ const plugin = typeof mod === "function" ? mod(options === true ? undefined : options) : mod;
2077
+ if (plugin)
2078
+ resolved.push(plugin);
2079
+ }
2080
+ return resolved;
2081
+ }, resolvePostcssConfig = async (config) => {
2082
+ const inlineConfig = config?.postcss;
2083
+ if (!inlineConfig)
2084
+ return null;
2085
+ const fileConfig = inlineConfig.config ? await loadPostcssConfigFile(inlineConfig.config) : {};
2086
+ const plugins = [
2087
+ ...normalizePostcssPlugins(fileConfig.plugins),
2088
+ ...normalizePostcssPlugins(inlineConfig.plugins)
2089
+ ];
2090
+ if (plugins.length === 0)
2091
+ return null;
2092
+ return {
2093
+ options: {
2094
+ ...fileConfig.options ?? {},
2095
+ ...inlineConfig.options ?? {}
2096
+ },
2097
+ plugins
2098
+ };
2099
+ }, runPostcss = async (css, filePath, config) => {
2100
+ const postcssConfig = await resolvePostcssConfig(config);
2101
+ if (!postcssConfig)
2102
+ return css;
2103
+ let postcssModule;
2104
+ try {
2105
+ postcssModule = await importOptionalPeer("postcss");
2106
+ } catch {
2107
+ throw missingDependencyError("postcss", filePath);
2108
+ }
2109
+ const postcss = postcssModule.default ?? postcssModule;
2110
+ const result = await postcss(postcssConfig.plugins).process(css, {
2111
+ from: filePath,
2112
+ map: false,
2113
+ ...postcssConfig.options
2114
+ });
2115
+ return result.css;
2116
+ }, createSassImporter = (entryFile, loadPaths, language, config, deps) => ({
2117
+ canonicalize(specifier, options) {
2118
+ const fromDirectory = options.containingUrl ? dirname2(fileURLToPath(options.containingUrl)) : dirname2(entryFile);
2119
+ const resolved = resolveImportPath(specifier, fromDirectory, loadPaths, language, config);
2120
+ return resolved ? new URL(`file://${resolved}`) : null;
2121
+ },
2122
+ load(canonicalUrl) {
2123
+ const filePath = fileURLToPath(canonicalUrl);
2124
+ deps?.add(filePath);
2125
+ const fileLanguage = getStyleLanguage(filePath);
2126
+ if (fileLanguage !== "scss" && fileLanguage !== "sass" && fileLanguage !== null)
2127
+ return null;
2128
+ return {
2129
+ contents: preprocessLoadedStyle(readFileSync3(filePath, "utf-8"), filePath, entryFile, loadPaths, language, config),
2130
+ syntax: filePath.endsWith(".sass") ? "indented" : "scss"
2131
+ };
2132
+ }
2133
+ }), createLessFileManager = (entryFile, loadPaths, config, deps) => ({
2134
+ install(less, pluginManager) {
2135
+ const baseManager = new less.FileManager;
2136
+ const manager = Object.create(baseManager);
2137
+ manager.supports = (filename, currentDirectory) => Boolean(resolveImportPath(filename, resolve3(currentDirectory), loadPaths, "less", config));
2138
+ manager.loadFile = async (filename, currentDirectory) => {
2139
+ const resolved = resolveImportPath(filename, resolve3(currentDirectory), loadPaths, "less", config);
2140
+ if (!resolved) {
2141
+ throw new Error(`Unable to resolve Less import "${filename}"`);
2142
+ }
2143
+ deps?.add(resolved);
2144
+ return {
2145
+ contents: preprocessLoadedStyle(await readFile(resolved, "utf-8"), resolved, entryFile, loadPaths, "less", config),
2146
+ filename: resolved
2147
+ };
2148
+ };
2149
+ pluginManager.addFileManager(manager);
2150
+ }
2151
+ }), renderStylus = async (contents, filePath, loadPaths, options, deps) => {
2152
+ let stylus;
2153
+ try {
2154
+ const stylusModule = await importOptionalPeer("stylus");
2155
+ stylus = stylusModule.default ?? stylusModule;
2156
+ } catch {
2157
+ throw missingDependencyError("stylus", filePath);
2158
+ }
2159
+ return new Promise((resolveCss, reject) => {
2160
+ const renderer = stylus(contents);
2161
+ renderer.set("filename", filePath);
2162
+ for (const [key, value] of Object.entries(options.options ?? {})) {
2163
+ renderer.set(key, value);
2164
+ }
2165
+ for (const path of loadPaths)
2166
+ renderer.include(path);
2167
+ renderer.render((error, css) => {
2168
+ if (error) {
2169
+ reject(error);
2170
+ return;
2171
+ }
2172
+ if (deps) {
2173
+ const stylusDeps = renderer.deps?.();
2174
+ if (Array.isArray(stylusDeps)) {
2175
+ for (const dep of stylusDeps)
2176
+ deps.add(resolve3(dep));
2177
+ }
2178
+ }
2179
+ resolveCss(css ?? "");
2180
+ });
2181
+ });
2182
+ }, styleDependencyGraph, styleOutputHashes, recordStyleDeps = (entry, deps) => {
2183
+ const key = resolve3(entry);
2184
+ const stripped = new Set;
2185
+ for (const dep of deps) {
2186
+ const resolved = resolve3(dep);
2187
+ if (resolved !== key)
2188
+ stripped.add(resolved);
2189
+ }
2190
+ styleDependencyGraph.set(key, stripped);
2191
+ }, addStyleImporter = (importerPath, stylePath) => {
2192
+ const key = resolve3(importerPath);
2193
+ const target = resolve3(stylePath);
2194
+ const deps = styleDependencyGraph.get(key) ?? new Set;
2195
+ deps.add(target);
2196
+ styleDependencyGraph.set(key, deps);
2197
+ }, findStyleEntriesImporting = (changedPath) => {
2198
+ const target = resolve3(changedPath);
2199
+ const importers = [];
2200
+ for (const [entry, deps] of styleDependencyGraph) {
2201
+ if (deps.has(target))
2202
+ importers.push(entry);
2203
+ }
2204
+ return importers;
2205
+ }, recordStyleOutput = (entry, css) => {
2206
+ const key = resolve3(entry);
2207
+ const hash = createHash("sha1").update(css).digest("hex");
2208
+ const previous = styleOutputHashes.get(key);
2209
+ styleOutputHashes.set(key, hash);
2210
+ return previous !== hash;
2211
+ }, forgetStyleEntry = (entry) => {
2212
+ const key = resolve3(entry);
2213
+ styleDependencyGraph.delete(key);
2214
+ styleOutputHashes.delete(key);
2215
+ }, compileStyleSource = async (filePath, source, languageHint, config) => {
2216
+ const language = getStyleLanguage(languageHint ?? filePath);
2217
+ const rawContents = source ?? await readFile(filePath, "utf-8");
2218
+ const deps = new Set;
2219
+ if (language === "scss" || language === "sass") {
2220
+ const options = getSassOptions(config, language);
2221
+ const packageName = options.implementation ?? "sass";
2222
+ let sass;
2223
+ try {
2224
+ sass = await importOptionalPeer(packageName);
2225
+ } catch {
2226
+ throw missingDependencyError(packageName, filePath);
2227
+ }
2228
+ const contents = withAdditionalData(rawContents, options.additionalData);
2229
+ const loadPaths = normalizeLoadPaths(filePath, options.loadPaths);
2230
+ try {
2231
+ const result = sass.compileString(contents, {
2232
+ importers: [
2233
+ createSassImporter(filePath, loadPaths, language, config, deps)
2234
+ ],
2235
+ loadPaths,
2236
+ style: "expanded",
2237
+ syntax: language === "sass" ? "indented" : "scss",
2238
+ url: new URL(`file://${filePath}`)
2239
+ });
2240
+ const css = await runPostcss(result.css, filePath, config);
2241
+ recordStyleDeps(filePath, deps);
2242
+ return css;
2243
+ } catch (error) {
2244
+ throwPreprocessorError(error, filePath, language);
2245
+ }
2246
+ }
2247
+ if (language === "less") {
2248
+ const options = getLessOptions(config);
2249
+ let lessModule;
2250
+ try {
2251
+ lessModule = await importOptionalPeer("less");
2252
+ } catch {
2253
+ throw missingDependencyError("less", filePath);
2254
+ }
2255
+ const less = lessModule.render ? lessModule : lessModule.default;
2256
+ const render = less?.render;
2257
+ if (!render)
2258
+ throw missingDependencyError("less", filePath);
2259
+ const contents = withAdditionalData(rawContents, options.additionalData);
2260
+ const loadPaths = normalizeLoadPaths(filePath, options.paths);
2261
+ try {
2262
+ const result = await render(contents, {
2263
+ ...options.options ?? {},
2264
+ filename: filePath,
2265
+ paths: loadPaths,
2266
+ plugins: [
2267
+ ...options.options?.plugins ?? [],
2268
+ createLessFileManager(filePath, loadPaths, config, deps)
2269
+ ]
2270
+ });
2271
+ const css = await runPostcss(result.css, filePath, config);
2272
+ recordStyleDeps(filePath, deps);
2273
+ return css;
2274
+ } catch (error) {
2275
+ throwPreprocessorError(error, filePath, "less");
2276
+ }
2277
+ }
2278
+ if (language === "stylus") {
2279
+ const options = getStylusOptions(config);
2280
+ const loadPaths = normalizeLoadPaths(filePath, options.paths);
2281
+ const contents = withAdditionalData(preprocessLoadedStyle(rawContents, filePath, filePath, loadPaths, "stylus", config), options.additionalData);
2282
+ try {
2283
+ const css = await runPostcss(await renderStylus(contents, filePath, loadPaths, options, deps), filePath, config);
2284
+ recordStyleDeps(filePath, deps);
2285
+ return css;
2286
+ } catch (error) {
2287
+ throwPreprocessorError(error, filePath, "stylus");
2288
+ }
2289
+ }
2290
+ return runPostcss(rawContents, filePath, config);
2291
+ }, createStylePreprocessorPlugin = (config) => ({
2292
+ name: "absolute-style-preprocessor",
2293
+ setup(build) {
2294
+ const cssModuleSources = new Map;
2295
+ build.onResolve({ filter: /^absolute-style-module:/ }, ({ path }) => ({
2296
+ namespace: "absolute-style-module",
2297
+ path: path.slice("absolute-style-module:".length)
2298
+ }));
2299
+ build.onLoad({ filter: /\.module\.css$/i, namespace: "absolute-style-module" }, async ({ path }) => {
2300
+ const source = cssModuleSources.get(path);
2301
+ if (!source) {
2302
+ throw new Error(`Unable to resolve CSS module source for ${path}`);
2303
+ }
2304
+ return {
2305
+ contents: source.css,
2306
+ loader: "css"
2307
+ };
2308
+ });
2309
+ build.onLoad({ filter: STYLE_EXTENSION_PATTERN }, async ({ path }) => {
2310
+ if (isStyleModulePath(path)) {
2311
+ const cssModulePath = path.replace(STYLE_EXTENSION_PATTERN, ".css");
2312
+ const compiled = await compileStyleSource(path, undefined, undefined, config);
2313
+ const { css, exports } = extractCssModuleExports(compiled);
2314
+ cssModuleSources.set(cssModulePath, { css, exports });
2315
+ const exportSource = Object.keys(exports).length > 0 ? `import styles from ${JSON.stringify(`absolute-style-module:${cssModulePath}`)}; export default Object.assign({}, styles, ${JSON.stringify(exports)});` : `export { default } from ${JSON.stringify(`absolute-style-module:${cssModulePath}`)};`;
2316
+ return {
2317
+ contents: exportSource,
2318
+ loader: "js"
2319
+ };
2320
+ }
2321
+ return {
2322
+ contents: await compileStyleSource(path, undefined, undefined, config),
2323
+ loader: "css"
2324
+ };
2325
+ });
2326
+ build.onLoad({ filter: CSS_EXTENSION_PATTERN }, async ({ path }) => ({
2327
+ contents: await compileStyleSource(path, undefined, undefined, config),
2328
+ loader: "css"
2329
+ }));
2330
+ }
2331
+ }), stylePreprocessorPlugin, createSvelteStylePreprocessor = (config) => ({
2332
+ style: async ({
2333
+ attributes,
2334
+ content,
2335
+ filename
2336
+ }) => {
2337
+ const language = typeof attributes.lang === "string" ? attributes.lang : typeof attributes.type === "string" ? attributes.type.replace(/^text\//, "") : null;
2338
+ if (!language || !STYLE_LANGUAGE_PATTERN.test(language))
2339
+ return;
2340
+ const path = filename ?? `style.${language}`;
2341
+ return {
2342
+ code: await compileStyleSource(path, content, language, config)
2343
+ };
2344
+ }
2345
+ }), compileStyleFileIfNeeded = async (filePath, config) => {
2346
+ if (!isPreprocessableStylePath(filePath)) {
2347
+ return runPostcss(await readFile(filePath, "utf-8"), filePath, config);
2348
+ }
2349
+ return compileStyleSource(filePath, undefined, undefined, config);
2350
+ }, compileStyleFileIfNeededSync = (filePath, config) => {
2351
+ const rawContents = readFileSync3(filePath, "utf-8");
2352
+ const language = getStyleLanguage(filePath);
2353
+ if (config?.postcss) {
2354
+ throw new Error(`Unable to compile ${filePath}: PostCSS preprocessing is async-only.`);
2355
+ }
2356
+ if (language === "scss" || language === "sass") {
2357
+ const options = getSassOptions(config, language);
2358
+ const packageName = options.implementation ?? "sass";
2359
+ let sass;
2360
+ try {
2361
+ sass = requireOptionalPeerSync(packageName);
2362
+ } catch {
2363
+ throw missingDependencyError(packageName, filePath);
2364
+ }
2365
+ const contents = withAdditionalData(rawContents, options.additionalData);
2366
+ const loadPaths = normalizeLoadPaths(filePath, options.loadPaths);
2367
+ return sass.compileString(contents, {
2368
+ importers: [
2369
+ createSassImporter(filePath, loadPaths, language, config)
2370
+ ],
2371
+ loadPaths,
2372
+ style: "expanded",
2373
+ syntax: language === "sass" ? "indented" : "scss",
2374
+ url: new URL(`file://${filePath}`)
2375
+ }).css;
2376
+ }
2377
+ if (language === "less") {
2378
+ throw new Error(`Unable to compile ${filePath}: Less styleUrl preprocessing is async-only. Import the Less file from a bundled entrypoint or use SCSS/CSS for Angular styleUrl.`);
2379
+ }
2380
+ if (language === "stylus") {
2381
+ throw new Error(`Unable to compile ${filePath}: Stylus styleUrl preprocessing is async-only. Import the Stylus file from a bundled entrypoint or use SCSS/CSS for Angular styleUrl.`);
2382
+ }
2383
+ return rawContents;
2384
+ }, getCssOutputExtension = (filePath) => isPreprocessableStylePath(filePath) ? ".css" : extname(filePath);
2385
+ var init_stylePreprocessor = __esm(() => {
2386
+ CSS_EXTENSION_PATTERN = /\.css$/i;
2387
+ STYLE_EXTENSION_PATTERN = /\.(s[ac]ss|less|styl(?:us)?)$/i;
2388
+ STYLE_MODULE_EXTENSION_PATTERN = /\.module\.(s[ac]ss|less|styl(?:us)?)$/i;
2389
+ STYLE_LANGUAGE_PATTERN = /^(s[ac]ss|less|styl(?:us)?)$/i;
2390
+ importOptionalPeer = new Function("specifier", "return import(specifier)");
2391
+ requireOptionalPeer = new Function("specifier", "return require(specifier)");
2392
+ requireFromCwd = createRequire(join3(process.cwd(), "package.json"));
2393
+ styleDependencyGraph = new Map;
2394
+ styleOutputHashes = new Map;
2395
+ stylePreprocessorPlugin = createStylePreprocessorPlugin();
2396
+ });
2397
+
2398
+ // src/core/svelteServerModule.ts
2399
+ import { mkdir, readdir as readdir2 } from "fs/promises";
2400
+ import { basename as basename3, dirname as dirname3, extname as extname2, join as join4, relative as relative2, resolve as resolve4 } from "path";
2401
+ var serverCacheRoot, compiledModuleCache, originalSourcePathCache, transpiler, ensureRelativeImportPath = (from, target) => {
2402
+ const importPath = relative2(dirname3(from), target).replace(/\\/g, "/");
2403
+ return importPath.startsWith(".") ? importPath : `./${importPath}`;
2404
+ }, processDirectoryEntries = (entries, dir, targetFileName, stack) => {
2405
+ for (const entry of entries) {
2406
+ const entryPath = join4(dir, entry.name);
2407
+ if (entry.isDirectory())
2408
+ stack.push(entryPath);
2409
+ if (entry.isFile() && entry.name === targetFileName) {
2410
+ return entryPath;
2411
+ }
2412
+ }
2413
+ return null;
2414
+ }, searchDirectoryLevel = async (dirs, targetFileName) => {
2415
+ if (dirs.length === 0)
2416
+ return null;
2417
+ const nextStack = [];
2418
+ const dirEntries = await Promise.all(dirs.map(async (dir) => ({
2419
+ dir,
2420
+ entries: await readdir2(dir, {
2421
+ encoding: "utf-8",
2422
+ withFileTypes: true
2423
+ })
2424
+ })));
2425
+ for (const { dir, entries } of dirEntries) {
2426
+ const found = processDirectoryEntries(entries, dir, targetFileName, nextStack);
2427
+ if (found)
2428
+ return found;
2429
+ }
2430
+ return searchDirectoryLevel(nextStack, targetFileName);
2431
+ }, findSourceFileByBasename = async (searchRoot, targetFileName) => searchDirectoryLevel([searchRoot], targetFileName), normalizeBuiltSvelteFileName = (sourcePath) => basename3(sourcePath).replace(/-[a-z0-9]{6,}(?=\.svelte$)/i, ""), resolveOriginalSourcePath = async (sourcePath) => {
2432
+ const cachedPath = originalSourcePathCache.get(sourcePath);
2433
+ if (cachedPath !== undefined) {
2434
+ return cachedPath;
2435
+ }
2436
+ if (!sourcePath.includes(`${join4(process.cwd(), "build")}${process.platform === "win32" ? "" : "/"}`) && !sourcePath.includes("/build/")) {
2437
+ originalSourcePathCache.set(sourcePath, sourcePath);
2438
+ return sourcePath;
2439
+ }
2440
+ const resolvedSourcePath = await findSourceFileByBasename(join4(process.cwd(), "src"), normalizeBuiltSvelteFileName(sourcePath));
2441
+ const nextPath = resolvedSourcePath ?? sourcePath;
2442
+ originalSourcePathCache.set(sourcePath, nextPath);
2443
+ return nextPath;
2444
+ }, resolveRelativeModule = async (spec, from) => {
2445
+ if (!spec.startsWith(".")) {
2446
+ return null;
2447
+ }
2448
+ const basePath = resolve4(dirname3(from), spec);
2449
+ const candidates = [
2450
+ basePath,
2451
+ `${basePath}.ts`,
2452
+ `${basePath}.js`,
2453
+ `${basePath}.mjs`,
2454
+ `${basePath}.cjs`,
2455
+ `${basePath}.json`,
2456
+ join4(basePath, "index.ts"),
2457
+ join4(basePath, "index.js"),
2458
+ join4(basePath, "index.mjs"),
2459
+ join4(basePath, "index.cjs"),
2460
+ join4(basePath, "index.json")
2461
+ ];
2462
+ const existResults = await Promise.all(candidates.map((candidate) => Bun.file(candidate).exists()));
2463
+ const foundIndex = existResults.indexOf(true);
2464
+ return foundIndex >= 0 ? candidates[foundIndex] ?? null : null;
2465
+ }, getCachedModulePath = (sourcePath) => {
2466
+ const relativeSourcePath = relative2(process.cwd(), sourcePath).replace(/\\/g, "/");
2467
+ const normalizedSourcePath = relativeSourcePath.startsWith("..") ? sourcePath.replace(/[:\\/]/g, "_") : relativeSourcePath;
2468
+ return join4(serverCacheRoot, `${normalizedSourcePath}.server.js`);
2469
+ }, resolveSvelteImport = async (spec, from) => {
2470
+ if (!spec.startsWith(".") && !spec.startsWith("/")) {
2471
+ const resolved = resolvePackageImport(spec);
2472
+ return resolved && resolved.endsWith(".svelte") ? resolved : null;
2473
+ }
2474
+ if (spec.startsWith("/")) {
2475
+ return spec;
2476
+ }
2477
+ if (!spec.startsWith(".")) {
2478
+ return null;
2479
+ }
2480
+ const explicitPath = resolve4(dirname3(from), spec);
2481
+ if (extname2(explicitPath) === ".svelte") {
2482
+ return explicitPath;
2483
+ }
2484
+ const candidate = `${explicitPath}.svelte`;
2485
+ if (await Bun.file(candidate).exists() === true) {
2486
+ return candidate;
2487
+ }
2488
+ return null;
2489
+ }, writeIfChanged = async (path, content) => {
2490
+ const targetFile = Bun.file(path);
2491
+ const exists = await targetFile.exists();
2492
+ if (exists) {
2493
+ const currentContent = await targetFile.text();
2494
+ if (currentContent === content) {
2495
+ return;
2496
+ }
2497
+ }
2498
+ await Bun.write(path, content);
2499
+ }, compileSvelteServerModule = async (sourcePath) => {
2500
+ const cachedModulePath = compiledModuleCache.get(sourcePath);
2501
+ if (cachedModulePath) {
2502
+ return cachedModulePath;
2503
+ }
2504
+ const resolutionSourcePath = await resolveOriginalSourcePath(sourcePath);
2505
+ const source = await Bun.file(sourcePath).text();
2506
+ const { compile, preprocess } = await import("svelte/compiler");
2507
+ const loweredAwaitSource = lowerSvelteAwaitSlotSyntax(source);
2508
+ const loweredSource = lowerSvelteIslandSyntax(loweredAwaitSource.code, "server");
2509
+ const preprocessed = await preprocess(loweredSource.code, createSvelteStylePreprocessor());
2510
+ let transpiled = sourcePath.endsWith(".ts") || sourcePath.endsWith(".svelte.ts") ? transpiler.transformSync(preprocessed.code) : preprocessed.code;
2511
+ const childImportSpecs = Array.from(transpiled.matchAll(/from\s+['"]([^'"]+)['"]/g)).map((match) => match[1]).filter((value) => value !== undefined);
2512
+ const resolvedChildModules = await Promise.all(childImportSpecs.map((spec) => resolveSvelteImport(spec, resolutionSourcePath)));
2513
+ const resolvedModuleImports = await Promise.all(childImportSpecs.map((spec) => resolveRelativeModule(spec, resolutionSourcePath)));
2514
+ const childModulePaths = new Map;
2515
+ const rewrittenModulePaths = new Map;
2516
+ const compiledChildren = await Promise.all(childImportSpecs.map(async (spec, index) => {
2517
+ const resolvedChild = resolvedChildModules[index];
2518
+ if (!spec || !resolvedChild)
2519
+ return null;
2520
+ return {
2521
+ compiledPath: await compileSvelteServerModule(resolvedChild),
2522
+ resolvedChild,
2523
+ spec
2524
+ };
2525
+ }));
2526
+ for (const result of compiledChildren) {
2527
+ if (!result)
2528
+ continue;
2529
+ childModulePaths.set(result.spec, result.compiledPath);
2530
+ childModulePaths.set(result.resolvedChild, result.compiledPath);
2531
+ }
2532
+ for (let index = 0;index < childImportSpecs.length; index += 1) {
2533
+ const spec = childImportSpecs[index];
2534
+ const resolvedModuleImport = resolvedModuleImports[index];
2535
+ if (!spec || !resolvedModuleImport)
2536
+ continue;
2537
+ if (resolvedChildModules[index])
2538
+ continue;
2539
+ rewrittenModulePaths.set(spec, ensureRelativeImportPath(getCachedModulePath(sourcePath), resolvedModuleImport));
2540
+ }
2541
+ for (const [spec, resolvedModuleImport] of rewrittenModulePaths) {
2542
+ transpiled = transpiled.replaceAll(spec, resolvedModuleImport);
2543
+ }
2544
+ let compiledCode = compile(transpiled, {
2545
+ css: "injected",
2546
+ experimental: {
2547
+ async: loweredAwaitSource.transformed || loweredSource.transformed
2548
+ },
2549
+ filename: resolutionSourcePath,
2550
+ generate: "server"
2551
+ }).js.code;
2552
+ for (const [spec, compiledChildPath] of childModulePaths) {
2553
+ compiledCode = compiledCode.replaceAll(spec, ensureRelativeImportPath(getCachedModulePath(sourcePath), compiledChildPath));
2554
+ }
2555
+ for (const [spec, resolvedModuleImport] of rewrittenModulePaths) {
2556
+ compiledCode = compiledCode.replaceAll(spec, resolvedModuleImport);
2557
+ }
2558
+ const compiledModulePath = getCachedModulePath(sourcePath);
2559
+ await mkdir(dirname3(compiledModulePath), { recursive: true });
2560
+ await writeIfChanged(compiledModulePath, compiledCode);
2561
+ compiledModuleCache.set(sourcePath, compiledModulePath);
2562
+ return compiledModulePath;
2563
+ };
2564
+ var init_svelteServerModule = __esm(() => {
2565
+ init_resolvePackageImport();
2566
+ init_lowerIslandSyntax();
2567
+ init_lowerAwaitSlotSyntax();
2568
+ init_stylePreprocessor();
2569
+ serverCacheRoot = join4(process.cwd(), ".absolutejs", "islands", "svelte");
2570
+ compiledModuleCache = new Map;
2571
+ originalSourcePathCache = new Map;
2572
+ transpiler = new Bun.Transpiler({
2573
+ loader: "ts",
2574
+ target: "browser"
2575
+ });
2576
+ });
2577
+
2578
+ // src/core/renderIslandMarkup.ts
2579
+ var islandSequence = 0, resolvedServerComponentCache, resolvedServerBuildComponentCache, nextIslandId = () => {
2580
+ islandSequence += 1;
2581
+ return `island-${islandSequence}`;
2582
+ }, isRecord4 = (value) => typeof value === "object" && value !== null, isReactServerIslandComponent = (value) => typeof value === "function", isSvelteServerIslandComponent = (value) => typeof value === "function", isVueServerIslandComponent = (value) => typeof value === "function" || isRecord4(value), isAngularServerIslandComponent = (value) => typeof value === "function", resolveBuildReferencePath = (source, registryPath) => {
2583
+ if (source.startsWith("file://"))
2584
+ return new URL(source).pathname;
2585
+ if (source.startsWith("."))
2586
+ return new URL(source, registryPath).pathname;
2587
+ return source;
2588
+ }, loadAndCompileServerBuildComponent = async (buildReferencePath) => {
2589
+ const compiledModulePath = await compileSvelteServerModule(buildReferencePath);
2590
+ const loadedModule = await import(compiledModulePath);
2591
+ return "default" in loadedModule ? loadedModule.default : loadedModule;
2592
+ }, loadServerBuildComponent = async (buildReferencePath) => {
2593
+ const cachedBuildComponent = resolvedServerBuildComponentCache.get(buildReferencePath);
2594
+ if (cachedBuildComponent) {
2595
+ return cachedBuildComponent;
2596
+ }
2597
+ const loadPromise = loadAndCompileServerBuildComponent(buildReferencePath);
2598
+ resolvedServerBuildComponentCache.set(buildReferencePath, loadPromise);
2599
+ return loadPromise;
2600
+ }, loadServerImportComponent = async (resolvedComponent, exportName) => {
2601
+ const resolvedModulePath = resolvedComponent.startsWith(".") ? new URL(resolvedComponent, import.meta.url).pathname : resolvedComponent;
2602
+ const importTarget = resolvedModulePath.endsWith(".svelte") ? await compileSvelteServerModule(resolvedModulePath) : resolvedModulePath;
2603
+ const loadedModule = await import(importTarget);
2604
+ if (exportName && exportName !== "default" && exportName in loadedModule) {
2605
+ return loadedModule[exportName];
2606
+ }
2607
+ return "default" in loadedModule ? loadedModule.default : loadedModule;
2608
+ }, resolveIslandComponent = async (component) => {
2609
+ const buildReference = getIslandBuildReference(component);
2610
+ const buildReferencePath = buildReference?.source ? resolveBuildReferencePath(buildReference.source, import.meta.url) : null;
2611
+ if (buildReferencePath?.endsWith(".svelte")) {
2612
+ return loadServerBuildComponent(buildReferencePath);
2613
+ }
2614
+ if (buildReferencePath) {
2615
+ return loadServerImportComponent(buildReferencePath, buildReference?.export);
2616
+ }
2617
+ const resolvedComponent = getIslandComponent(component);
2618
+ if (typeof resolvedComponent !== "string") {
2619
+ return resolvedComponent;
2620
+ }
2621
+ return loadServerImportComponent(resolvedComponent);
2622
+ }, resolveServerIslandComponent = async (component) => {
2623
+ const cachedResolvedComponent = resolvedServerComponentCache.get(component);
2624
+ if (cachedResolvedComponent) {
2625
+ return cachedResolvedComponent;
2626
+ }
2627
+ const resolutionPromise = resolveIslandComponent(component);
2628
+ resolvedServerComponentCache.set(component, resolutionPromise);
2629
+ return resolutionPromise;
2630
+ }, resolveReactServerIslandComponent = async (component) => {
2631
+ const resolvedComponent = await resolveServerIslandComponent(component);
2632
+ if (!isReactServerIslandComponent(resolvedComponent)) {
2633
+ throw new Error("Resolved React island is not a valid React component.");
2634
+ }
2635
+ return resolvedComponent;
2636
+ }, resolveSvelteServerIslandComponent = async (component) => {
2637
+ const resolvedComponent = await resolveServerIslandComponent(component);
2638
+ if (!isSvelteServerIslandComponent(resolvedComponent)) {
2639
+ throw new Error("Resolved Svelte island is not a valid Svelte component.");
2640
+ }
2641
+ return resolvedComponent;
2642
+ }, resolveVueServerIslandComponent = async (component) => {
2643
+ const resolvedComponent = await resolveServerIslandComponent(component);
2644
+ if (!isVueServerIslandComponent(resolvedComponent)) {
2645
+ throw new Error("Resolved Vue island is not a valid Vue component.");
2646
+ }
2647
+ return resolvedComponent;
2648
+ }, resolveAngularServerIslandComponent = async (component) => {
2649
+ const resolvedComponent = await resolveServerIslandComponent(component);
2650
+ if (!isAngularServerIslandComponent(resolvedComponent)) {
2651
+ throw new Error("Resolved Angular island is not a valid Angular component.");
2652
+ }
2653
+ return resolvedComponent;
2654
+ }, renderIslandMarkup = async (registry, props) => {
2655
+ const result = await renderIslandResult(registry, props);
2656
+ return `<div ${serializeIslandAttributes(result.attributes)}>${result.html}</div>`;
2657
+ }, renderIslandResult = async (registry, props) => {
2658
+ const islandId = nextIslandId();
2659
+ const attributes = getIslandMarkerAttributes(props);
2660
+ if (props.framework === "react") {
2661
+ const entry = registry.react?.[props.component];
2662
+ if (!entry) {
2663
+ throw new Error(`Island component "${props.component}" is not registered for framework "react".`);
2664
+ }
2665
+ const component = await resolveReactServerIslandComponent(entry);
2666
+ const html = await renderReactIslandToHtml(component, props.props);
2667
+ return { attributes, html };
2668
+ }
2669
+ if (props.framework === "svelte") {
2670
+ const entry = registry.svelte?.[props.component];
2671
+ if (!entry) {
2672
+ throw new Error(`Island component "${props.component}" is not registered for framework "svelte".`);
2673
+ }
2674
+ const component = await resolveSvelteServerIslandComponent(entry);
2675
+ const html = await renderSvelteIslandToHtml(component, props.props);
2676
+ return { attributes, html };
2677
+ }
2678
+ if (props.framework === "vue") {
2679
+ const entry = registry.vue?.[props.component];
2680
+ if (!entry) {
2681
+ throw new Error(`Island component "${props.component}" is not registered for framework "vue".`);
2682
+ }
2683
+ const component = await resolveVueServerIslandComponent(entry);
2684
+ const html = await renderVueIslandToHtml(component, props.props);
2685
+ return { attributes, html };
2686
+ }
2687
+ if (props.framework === "angular") {
2688
+ const entry = registry.angular?.[props.component];
2689
+ if (!entry) {
2690
+ throw new Error(`Island component "${props.component}" is not registered for framework "angular".`);
2691
+ }
2692
+ const component = await resolveAngularServerIslandComponent(entry);
2693
+ const html = await renderAngularIslandToHtml2(component, props.props, islandId);
2694
+ return {
2695
+ attributes: {
2696
+ ...getIslandMarkerAttributes(props, islandId)
2697
+ },
2698
+ html
2699
+ };
2700
+ }
2701
+ throw new Error(`Framework "${props.framework}" is not implemented in this prototype.`);
2702
+ };
2703
+ var init_renderIslandMarkup = __esm(() => {
2704
+ init_islandSsr();
2705
+ init_svelteServerModule();
2706
+ init_islandMarkupAttributes();
2707
+ init_islands();
2708
+ resolvedServerComponentCache = new Map;
2709
+ resolvedServerBuildComponentCache = new Map;
2710
+ });
2711
+
2712
+ // src/core/streamingSlotRegistrar.ts
2713
+ var STREAMING_SLOT_REGISTRAR_KEY = Symbol.for("absolutejs.streamingSlotRegistrar");
2714
+ var STREAMING_SLOT_WARNING_STORAGE_KEY = Symbol.for("absolutejs.streamingSlotWarningController");
2715
+ var STREAMING_SLOT_COLLECTION_STORAGE_KEY = Symbol.for("absolutejs.streamingSlotCollectionController");
2716
+ var getRegisteredStreamingSlotRegistrar = () => {
2717
+ const value = Reflect.get(globalThis, STREAMING_SLOT_REGISTRAR_KEY);
2718
+ if (typeof value === "function" || value === null) {
2719
+ return value;
2720
+ }
2721
+ return;
2722
+ };
2723
+ var isObjectRecord = (value) => Boolean(value) && typeof value === "object";
2724
+ var isStreamingSlotWarningController = (value) => isObjectRecord(value) && ("maybeWarn" in value) && typeof value.maybeWarn === "function";
2725
+ var isStreamingSlotCollectionController = (value) => isObjectRecord(value) && ("isCollecting" in value) && typeof value.isCollecting === "function";
2726
+ var getWarningController = () => {
2727
+ const value = Reflect.get(globalThis, STREAMING_SLOT_WARNING_STORAGE_KEY);
2728
+ if (value === null || typeof value === "undefined")
2729
+ return;
2730
+ return isStreamingSlotWarningController(value) ? value : undefined;
2731
+ };
2732
+ var getCollectionController = () => {
2733
+ const value = Reflect.get(globalThis, STREAMING_SLOT_COLLECTION_STORAGE_KEY);
2734
+ if (value === null || typeof value === "undefined")
2735
+ return;
2736
+ return isStreamingSlotCollectionController(value) ? value : undefined;
2737
+ };
2738
+ var hasRegisteredStreamingSlotRegistrar = () => typeof getRegisteredStreamingSlotRegistrar() === "function";
2739
+ var isStreamingSlotCollectionActive = () => getCollectionController()?.isCollecting() === true;
2740
+ var registerStreamingSlot = (slot) => {
2741
+ getRegisteredStreamingSlotRegistrar()?.(slot);
2742
+ };
2743
+ var setStreamingSlotCollectionController = (controller) => {
2744
+ Reflect.set(globalThis, STREAMING_SLOT_COLLECTION_STORAGE_KEY, controller);
2745
+ };
2746
+ var setStreamingSlotRegistrar = (nextRegistrar) => {
2747
+ Reflect.set(globalThis, STREAMING_SLOT_REGISTRAR_KEY, nextRegistrar);
2748
+ };
2749
+ var setStreamingSlotWarningController = (controller) => {
2750
+ Reflect.set(globalThis, STREAMING_SLOT_WARNING_STORAGE_KEY, controller);
2751
+ };
2752
+ var warnMissingStreamingSlotCollector = (primitiveName) => {
2753
+ if (isStreamingSlotCollectionActive()) {
2754
+ return;
2755
+ }
2756
+ getWarningController()?.maybeWarn(primitiveName);
2757
+ };
2758
+
2759
+ // src/core/streamingSlotRegistry.ts
2760
+ var STREAMING_SLOT_STORAGE_KEY = Symbol.for("absolutejs.streamingSlotAsyncLocalStorage");
2761
+ var isObjectRecord2 = (value) => Boolean(value) && typeof value === "object";
2762
+ var isAsyncLocalStorage = (value) => isObjectRecord2(value) && ("getStore" in value) && typeof value.getStore === "function" && ("run" in value) && typeof value.run === "function";
2763
+ var getStorageGlobal = () => {
2764
+ const value = Reflect.get(globalThis, STREAMING_SLOT_STORAGE_KEY);
2765
+ if (value === null || typeof value === "undefined") {
2766
+ return value;
2767
+ }
2768
+ return isAsyncLocalStorage(value) ? value : undefined;
2769
+ };
2770
+ var isServerRuntime = () => typeof process !== "undefined" && typeof process.versions?.node === "string";
2771
+ var ensureAsyncLocalStorage = async () => {
2772
+ const storage = getStorageGlobal();
2773
+ if (typeof storage !== "undefined") {
2774
+ return storage;
2775
+ }
2776
+ if (!isServerRuntime()) {
2777
+ Reflect.set(globalThis, STREAMING_SLOT_STORAGE_KEY, null);
2778
+ return getStorageGlobal();
2779
+ }
2780
+ const mod = await import("async_hooks");
2781
+ Reflect.set(globalThis, STREAMING_SLOT_STORAGE_KEY, new mod.AsyncLocalStorage);
2782
+ return getStorageGlobal();
2783
+ };
2784
+ var getActiveSlotStore = () => {
2785
+ const storage = getStorageGlobal();
2786
+ if (!storage)
2787
+ return;
2788
+ return storage.getStore();
2789
+ };
2790
+ var registerStreamingSlot2 = (slot) => {
2791
+ const store = getActiveSlotStore();
2792
+ if (!store)
2793
+ return;
2794
+ store.set(slot.id, slot);
2795
+ };
2796
+ setStreamingSlotRegistrar(registerStreamingSlot2);
2797
+ setStreamingSlotCollectionController({
2798
+ isCollecting: () => getActiveSlotStore() !== undefined
2799
+ });
2800
+ var hasActiveStreamingSlotRegistry = () => getActiveSlotStore() !== undefined;
2801
+ var runWithStreamingSlotRegistry = async (task) => {
2802
+ const storage = await ensureAsyncLocalStorage();
2803
+ if (!storage) {
2804
+ const slots = [];
2805
+ return {
2806
+ result: await task(),
2807
+ slots
2808
+ };
2809
+ }
2810
+ return storage.run(new Map, async () => {
2811
+ const result = await task();
2812
+ const store = storage.getStore();
2813
+ return {
2814
+ result,
2815
+ slots: store ? [...store.values()] : []
2816
+ };
2817
+ });
2818
+ };
2819
+
2820
+ // src/vue/components/Image.ts
2821
+ import { computed, defineComponent, h, ref } from "vue";
2822
+
2823
+ // src/utils/imageClient.ts
2824
+ init_constants();
2825
+ var DEFAULT_DEVICE_SIZES = IMAGE_DEFAULT_DEVICE_SIZES;
2826
+ var DEFAULT_IMAGE_SIZES = IMAGE_DEFAULT_IMAGE_SIZES;
2827
+ var DEFAULT_QUALITY = IMAGE_DEFAULT_QUALITY;
2828
+ var OPTIMIZATION_ENDPOINT = "/_absolute/image";
2829
+ var buildOptimizedUrl = (src, width, quality, basePath = OPTIMIZATION_ENDPOINT) => `${basePath}?url=${encodeURIComponent(src)}&w=${width}&q=${quality}`;
2830
+ var getAllSizes = (deviceSizes, imageSizes) => {
2831
+ const device = deviceSizes ?? DEFAULT_DEVICE_SIZES;
2832
+ const image = imageSizes ?? DEFAULT_IMAGE_SIZES;
2833
+ return [...device, ...image].sort((left, right) => left - right);
2834
+ };
2835
+ var snapToSize = (target, sizes) => {
2836
+ for (const size of sizes) {
2837
+ if (size >= target)
2838
+ return size;
2839
+ }
2840
+ return sizes[sizes.length - 1] ?? target;
2841
+ };
2842
+ var generateBlurSvg = (base64Thumbnail) => {
2843
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 320"><filter id="b" color-interpolation-filters="sRGB"><feGaussianBlur stdDeviation="20"/><feColorMatrix values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 100 -1"/></filter><image filter="url(#b)" x="0" y="0" width="100%" height="100%" href="${base64Thumbnail}"/></svg>`;
2844
+ const encoded = encodeURIComponent(svg);
2845
+ return `url("data:image/svg+xml,${encoded}")`;
2846
+ };
2847
+ var generateSrcSet = (src, width, sizes, deviceSizes, imageSizes) => {
2848
+ const quality = DEFAULT_QUALITY;
2849
+ if (sizes) {
2850
+ const allSizes = getAllSizes(deviceSizes, imageSizes);
2851
+ return allSizes.map((sizeWidth) => `${buildOptimizedUrl(src, sizeWidth, quality)} ${sizeWidth}w`).join(", ");
2852
+ }
2853
+ if (width) {
2854
+ const allSizes = getAllSizes(deviceSizes, imageSizes);
2855
+ const w1x = snapToSize(width, allSizes);
2856
+ const w2x = snapToSize(width * 2, allSizes);
2857
+ return `${buildOptimizedUrl(src, w1x, quality)} 1x, ${buildOptimizedUrl(src, w2x, quality)} 2x`;
2858
+ }
2859
+ const devSizes = deviceSizes ?? DEFAULT_DEVICE_SIZES;
2860
+ return devSizes.map((sizeWidth) => `${buildOptimizedUrl(src, sizeWidth, quality)} ${sizeWidth}w`).join(", ");
2861
+ };
2862
+
2863
+ // src/vue/components/Image.ts
2864
+ var fillWrapperStyle = {
2865
+ display: "block",
2866
+ height: "100%",
2867
+ overflow: "hidden",
2868
+ position: "relative",
2869
+ width: "100%"
2870
+ };
2871
+ var Image = defineComponent({
2872
+ name: "AbsoluteImage",
2873
+ props: {
2874
+ alt: { required: true, type: String },
2875
+ blurDataURL: { default: undefined, type: String },
2876
+ className: { default: undefined, type: String },
2877
+ crossOrigin: { default: undefined, type: String },
2878
+ fetchPriority: { default: undefined, type: String },
2879
+ fill: { default: false, type: Boolean },
2880
+ height: { default: undefined, type: Number },
2881
+ loader: { default: undefined, type: Function },
2882
+ loading: { default: "lazy", type: String },
2883
+ onError: { default: undefined, type: Function },
2884
+ onLoad: { default: undefined, type: Function },
2885
+ overrideSrc: { default: undefined, type: String },
2886
+ placeholder: { default: undefined, type: String },
2887
+ priority: { default: false, type: Boolean },
2888
+ quality: { default: DEFAULT_QUALITY, type: Number },
2889
+ referrerPolicy: { default: undefined, type: String },
2890
+ sizes: { default: undefined, type: String },
2891
+ src: { required: true, type: String },
2892
+ style: { default: undefined, type: Object },
2893
+ unoptimized: { default: false, type: Boolean },
2894
+ width: { default: undefined, type: Number }
2895
+ },
2896
+ setup(props) {
2897
+ const blurRemoved = ref(false);
2898
+ const resolvedSrc = computed(() => {
2899
+ if (props.overrideSrc)
2900
+ return props.overrideSrc;
2901
+ if (props.unoptimized)
2902
+ return props.src;
2903
+ if (props.loader) {
2904
+ return props.loader({
2905
+ quality: props.quality ?? DEFAULT_QUALITY,
2906
+ src: props.src,
2907
+ width: props.width ?? 0
2908
+ });
2909
+ }
2910
+ if (!props.width) {
2911
+ return buildOptimizedUrl(props.src, 0, props.quality ?? DEFAULT_QUALITY);
2912
+ }
2913
+ return buildOptimizedUrl(props.src, props.width, props.quality ?? DEFAULT_QUALITY);
2914
+ });
2915
+ const srcSet = computed(() => props.unoptimized ? undefined : generateSrcSet(props.src, props.width, props.sizes));
2916
+ const resolvedSizes = computed(() => props.sizes ?? (props.fill ? "100vw" : undefined));
2917
+ const resolvedLoading = computed(() => props.priority ? "eager" : props.loading ?? "lazy");
2918
+ const resolvedFetchPriority = computed(() => props.priority ? "high" : props.fetchPriority);
2919
+ const hasBlur = computed(() => props.placeholder === "blur" || typeof props.placeholder === "string" && props.placeholder !== "empty" && props.placeholder.startsWith("data:"));
2920
+ const blurBackground = computed(() => {
2921
+ if (!hasBlur.value || blurRemoved.value)
2922
+ return;
2923
+ if (typeof props.placeholder === "string" && props.placeholder !== "blur" && props.placeholder.startsWith("data:")) {
2924
+ return generateBlurSvg(props.placeholder);
2925
+ }
2926
+ if (props.blurDataURL)
2927
+ return generateBlurSvg(props.blurDataURL);
2928
+ return;
2929
+ });
2930
+ const imgStyle = computed(() => {
2931
+ const base = {
2932
+ ...props.style ?? {},
2933
+ color: "transparent"
2934
+ };
2935
+ if (blurBackground.value) {
2936
+ base.backgroundImage = blurBackground.value;
2937
+ base.backgroundPosition = "center";
2938
+ base.backgroundRepeat = "no-repeat";
2939
+ base.backgroundSize = "cover";
2940
+ }
2941
+ if (props.fill) {
2942
+ base.height = "100%";
2943
+ base.inset = "0";
2944
+ base.objectFit = "cover";
2945
+ base.position = "absolute";
2946
+ base.width = "100%";
2947
+ }
2948
+ return base;
2949
+ });
2950
+ const handleLoad = (event) => {
2951
+ blurRemoved.value = true;
2952
+ props.onLoad?.(event);
2953
+ };
2954
+ const handleError = (event) => {
2955
+ props.onError?.(event);
2956
+ };
2957
+ return () => {
2958
+ const imgNode = h("img", {
2959
+ alt: props.alt,
2960
+ class: props.className,
2961
+ crossorigin: props.crossOrigin,
2962
+ decoding: "async",
2963
+ fetchpriority: resolvedFetchPriority.value,
2964
+ height: props.fill ? undefined : props.height,
2965
+ loading: resolvedLoading.value,
2966
+ onError: handleError,
2967
+ onLoad: handleLoad,
2968
+ referrerpolicy: props.referrerPolicy,
2969
+ sizes: resolvedSizes.value,
2970
+ src: resolvedSrc.value,
2971
+ srcset: srcSet.value,
2972
+ style: imgStyle.value,
2973
+ width: props.fill ? undefined : props.width
2974
+ });
2975
+ return props.fill ? h("span", { style: fillWrapperStyle }, [imgNode]) : imgNode;
2976
+ };
2977
+ }
2978
+ });
2979
+ // src/vue/components/SuspenseSlot.ts
42
2980
  import {
43
- getIslandMarkerAttributes
44
- } from "../chunk-2f21eenc.js";
45
- import"../chunk-fygx2ymm.js";
46
- import"../chunk-8kcfffry.js";
47
- import"../chunk-3yjzpcne.js";
48
- import"../chunk-bmgqm774.js";
2981
+ cloneVNode,
2982
+ defineComponent as defineComponent2,
2983
+ h as h2,
2984
+ isVNode,
2985
+ onMounted,
2986
+ onBeforeUnmount,
2987
+ ref as ref2,
2988
+ useSSRContext
2989
+ } from "vue";
2990
+ var renderVueNodesToHtml = async (nodes) => {
2991
+ const { createSSRApp, h: createVNode } = await import("vue");
2992
+ const { renderToString } = await import("vue/server-renderer");
2993
+ const app = createSSRApp({
2994
+ render: () => createVNode("div", undefined, nodes ?? undefined)
2995
+ });
2996
+ const html = await renderToString(app);
2997
+ return html.replace(/^<div>|<\/div>$/g, "");
2998
+ };
2999
+ var hasFrameworkSlots = (defaultSlot, fallbackSlot, errorSlot, promise) => defaultSlot !== undefined || fallbackSlot !== undefined || errorSlot !== undefined || promise !== undefined;
3000
+ var allowMismatchOnSlotNodes = (nodes) => {
3001
+ if (Array.isArray(nodes)) {
3002
+ return nodes.map((node) => allowMismatchOnSlotNodes(node));
3003
+ }
3004
+ if (isVNode(nodes)) {
3005
+ return cloneVNode(nodes, {
3006
+ "data-allow-mismatch": ""
3007
+ });
3008
+ }
3009
+ return nodes;
3010
+ };
3011
+ var resolveSuspenseValue = async (resolve, promise) => {
3012
+ if (resolve !== undefined) {
3013
+ return resolve();
3014
+ }
3015
+ if (promise !== undefined) {
3016
+ return promise;
3017
+ }
3018
+ return;
3019
+ };
3020
+ var isObjectRecord3 = (value) => Boolean(value) && typeof value === "object";
3021
+ var isVueSuspensePayload = (payload) => {
3022
+ if (!isObjectRecord3(payload)) {
3023
+ return false;
3024
+ }
3025
+ return payload.kind === "vue-suspense";
3026
+ };
3027
+ var hasEventDetailId = (event, id) => {
3028
+ if (!(event instanceof CustomEvent)) {
3029
+ return false;
3030
+ }
3031
+ const { detail } = event;
3032
+ if (!detail || typeof detail !== "object") {
3033
+ return false;
3034
+ }
3035
+ return detail.id === id;
3036
+ };
3037
+ var toLegacySuspenseSlotRegistration = (props) => {
3038
+ if (!props.resolve) {
3039
+ return null;
3040
+ }
3041
+ return {
3042
+ errorHtml: props.errorHtml,
3043
+ fallbackHtml: props.fallbackHtml,
3044
+ id: props.id,
3045
+ timeoutMs: props.timeoutMs,
3046
+ resolve: async () => {
3047
+ const resolved = await props.resolve?.();
3048
+ return typeof resolved === "string" ? resolved : "";
3049
+ }
3050
+ };
3051
+ };
3052
+ var registerLegacySuspenseSlot = (props) => {
3053
+ registerStreamingSlot({
3054
+ errorHtml: props.errorHtml,
3055
+ fallbackHtml: props.fallbackHtml,
3056
+ id: props.id,
3057
+ resolve: props.resolve,
3058
+ timeoutMs: props.timeoutMs
3059
+ });
3060
+ };
3061
+ var resolveStreamingSuspenseSlot = async (props, slots) => {
3062
+ try {
3063
+ const value = await resolveSuspenseValue(props.resolve, props.promise);
3064
+ const nodes = allowMismatchOnSlotNodes(slots.default?.({ value }) ?? []);
3065
+ const html = await renderVueNodesToHtml(nodes);
3066
+ return {
3067
+ html,
3068
+ kind: "vue-suspense",
3069
+ value
3070
+ };
3071
+ } catch (error) {
3072
+ const errorNodes = slots.error?.({ error });
3073
+ if (errorNodes !== undefined)
3074
+ return renderVueNodesToHtml(allowMismatchOnSlotNodes(errorNodes));
3075
+ if (typeof props.errorHtml === "string")
3076
+ return props.errorHtml;
3077
+ throw error;
3078
+ }
3079
+ };
3080
+ var registerSuspenseSlotForSsr = (props, slots, usesFrameworkSlots) => {
3081
+ if (!isStreamingSlotCollectionActive()) {
3082
+ warnMissingStreamingSlotCollector("SuspenseSlot");
3083
+ }
3084
+ const legacyRegistration = toLegacySuspenseSlotRegistration(props);
3085
+ if (!usesFrameworkSlots && legacyRegistration) {
3086
+ registerLegacySuspenseSlot(legacyRegistration);
3087
+ return;
3088
+ }
3089
+ registerStreamingSlot({
3090
+ id: props.id,
3091
+ timeoutMs: props.timeoutMs,
3092
+ resolve: () => resolveStreamingSuspenseSlot(props, slots)
3093
+ });
3094
+ };
3095
+ var applySuspensePayload = (payload, state) => {
3096
+ state.hasError.value = payload.state === "error";
3097
+ state.resolvedValue.value = payload.value;
3098
+ state.isResolved.value = payload.state !== "error";
3099
+ };
3100
+ var SuspenseSlot = defineComponent2({
3101
+ name: "AbsoluteSuspenseSlot",
3102
+ props: {
3103
+ className: { default: undefined, type: String },
3104
+ errorHtml: { default: undefined, type: String },
3105
+ fallbackHtml: { default: "", type: String },
3106
+ id: { required: true, type: String },
3107
+ promise: {
3108
+ default: undefined,
3109
+ type: Object
3110
+ },
3111
+ resolve: {
3112
+ default: undefined,
3113
+ type: Function
3114
+ },
3115
+ timeoutMs: { default: undefined, type: Number }
3116
+ },
3117
+ setup(props, { slots }) {
3118
+ const readPatchedDomState = () => {
3119
+ if (typeof document === "undefined")
3120
+ return false;
3121
+ const slotNode = document.getElementById(props.id);
3122
+ if (!slotNode)
3123
+ return false;
3124
+ return slotNode.getAttribute("data-absolute-slot-state") === "resolved";
3125
+ };
3126
+ const isResolved = ref2(false);
3127
+ const resolvedValue = ref2(undefined);
3128
+ const hasError = ref2(false);
3129
+ const hasPatchedDom = ref2(readPatchedDomState());
3130
+ const usesFrameworkSlots = hasFrameworkSlots(slots.default, slots.fallback, slots.error, props.promise);
3131
+ const isSsrRender = useSSRContext() !== undefined;
3132
+ if (isSsrRender) {
3133
+ registerSuspenseSlotForSsr(props, slots, usesFrameworkSlots);
3134
+ }
3135
+ if (typeof window !== "undefined" && usesFrameworkSlots) {
3136
+ const consumers = window.__ABS_SLOT_CONSUMERS__ = window.__ABS_SLOT_CONSUMERS__ ?? {};
3137
+ let runtimeReady = false;
3138
+ consumers[props.id] = (payload) => {
3139
+ if (!runtimeReady)
3140
+ return false;
3141
+ if (!isVueSuspensePayload(payload)) {
3142
+ return false;
3143
+ }
3144
+ applySuspensePayload(payload, {
3145
+ hasError,
3146
+ isResolved,
3147
+ resolvedValue
3148
+ });
3149
+ return true;
3150
+ };
3151
+ const handlePatchedDom = (event) => {
3152
+ if (hasEventDetailId(event, props.id)) {
3153
+ hasPatchedDom.value = true;
3154
+ }
3155
+ };
3156
+ onMounted(() => {
3157
+ hasPatchedDom.value = readPatchedDomState();
3158
+ window.addEventListener("absolutejs:slot-patch", handlePatchedDom);
3159
+ runtimeReady = true;
3160
+ window.__ABS_SLOT_FLUSH__?.();
3161
+ });
3162
+ onBeforeUnmount(() => {
3163
+ window.removeEventListener("absolutejs:slot-patch", handlePatchedDom);
3164
+ delete window.__ABS_SLOT_CONSUMERS__?.[props.id];
3165
+ });
3166
+ }
3167
+ const resolveSlotChildren = () => {
3168
+ if (hasPatchedDom.value) {
3169
+ return;
3170
+ }
3171
+ if (hasError.value) {
3172
+ return allowMismatchOnSlotNodes(slots.error?.({ error: undefined }) ?? slots.fallback?.() ?? undefined) ?? undefined;
3173
+ }
3174
+ if (isResolved.value) {
3175
+ return allowMismatchOnSlotNodes(slots.default?.({ value: resolvedValue.value }) ?? undefined) ?? undefined;
3176
+ }
3177
+ return allowMismatchOnSlotNodes(slots.fallback?.() ?? undefined);
3178
+ };
3179
+ return () => {
3180
+ if (!usesFrameworkSlots) {
3181
+ return h2("div", {
3182
+ class: props.className,
3183
+ "data-absolute-slot": "true",
3184
+ id: props.id,
3185
+ innerHTML: props.fallbackHtml
3186
+ });
3187
+ }
3188
+ return h2("div", {
3189
+ class: props.className,
3190
+ "data-absolute-slot": "true",
3191
+ "data-allow-mismatch": "",
3192
+ id: props.id
3193
+ }, resolveSlotChildren() ?? undefined);
3194
+ };
3195
+ }
3196
+ });
3197
+ // src/vue/components/StreamSlot.ts
3198
+ import { defineComponent as defineComponent3, h as h3, useSSRContext as useSSRContext2 } from "vue";
3199
+ var StreamSlot = defineComponent3({
3200
+ name: "AbsoluteStreamSlot",
3201
+ props: {
3202
+ className: { default: undefined, type: String },
3203
+ errorHtml: { default: undefined, type: String },
3204
+ fallbackHtml: { default: "", type: String },
3205
+ id: { required: true, type: String },
3206
+ resolve: {
3207
+ required: true,
3208
+ type: Function
3209
+ },
3210
+ timeoutMs: { default: undefined, type: Number }
3211
+ },
3212
+ setup(props) {
3213
+ if (useSSRContext2() !== undefined) {
3214
+ registerStreamSlotForSsr(props);
3215
+ }
3216
+ return () => h3("div", {
3217
+ class: props.className,
3218
+ "data-absolute-slot": "true",
3219
+ id: props.id,
3220
+ innerHTML: props.fallbackHtml
3221
+ });
3222
+ }
3223
+ });
3224
+ var registerStreamSlotForSsr = (props) => {
3225
+ if (!isStreamingSlotCollectionActive()) {
3226
+ warnMissingStreamingSlotCollector("StreamSlot");
3227
+ return;
3228
+ }
3229
+ registerStreamingSlot({
3230
+ errorHtml: props.errorHtml,
3231
+ fallbackHtml: props.fallbackHtml,
3232
+ id: props.id,
3233
+ resolve: props.resolve,
3234
+ timeoutMs: props.timeoutMs
3235
+ });
3236
+ };
3237
+ // src/vue/pageHandler.ts
3238
+ init_constants();
3239
+ import { readdir } from "fs/promises";
3240
+ import { basename as basename2, dirname } from "path";
3241
+
3242
+ // src/core/islandPageContext.ts
3243
+ init_constants();
3244
+ var BOOTSTRAP_MANIFEST_KEY = "BootstrapClient";
3245
+ var ISLAND_MARKER = 'data-island="true"';
3246
+ var MANIFEST_MARKER = "__ABSOLUTE_MANIFEST__";
3247
+ var ISLAND_STATE_MARKER = "__ABS_ISLAND_STATE__";
3248
+ var CLOSING_HEAD_TAG = "</head>";
3249
+ var buildIslandsHeadMarkup = (manifest) => {
3250
+ const manifestScript = `<script>window.__ABSOLUTE_MANIFEST__ = ${JSON.stringify(manifest)}</script>`;
3251
+ const islandStateScript = `<script>window.__ABS_ISLAND_STATE__ = ${JSON.stringify(globalThis.__ABS_ISLAND_STATE__ ?? {})}</script>`;
3252
+ const bootstrapPath = manifest[BOOTSTRAP_MANIFEST_KEY];
3253
+ const bootstrapScript = bootstrapPath ? `<script type="module" src="${bootstrapPath}"></script>` : "";
3254
+ return `${manifestScript}${islandStateScript}${bootstrapScript}`;
3255
+ };
3256
+ var injectHeadMarkup = (html, markup) => {
3257
+ const closingHeadIndex = html.indexOf("</head>");
3258
+ if (closingHeadIndex >= 0) {
3259
+ return `${html.slice(0, closingHeadIndex)}${markup}${html.slice(closingHeadIndex)}`;
3260
+ }
3261
+ const openingBodyIndex = html.indexOf("<body");
3262
+ if (openingBodyIndex >= 0) {
3263
+ const bodyStart = html.indexOf(">", openingBodyIndex);
3264
+ if (bodyStart >= 0) {
3265
+ return `${html.slice(0, openingBodyIndex)}<head>${markup}</head>${html.slice(openingBodyIndex)}`;
3266
+ }
3267
+ }
3268
+ return `<!DOCTYPE html><html><head>${markup}</head><body>${html}</body></html>`;
3269
+ };
3270
+ var streamChunkToString = (value, decoder) => typeof value === "string" ? value : decoder.decode(value, { stream: true });
3271
+ var flushSafePendingText = (controller, encoder, pending, lookbehind) => {
3272
+ if (pending.length <= lookbehind) {
3273
+ return pending;
3274
+ }
3275
+ const safeText = pending.slice(0, pending.length - lookbehind);
3276
+ controller.enqueue(encoder.encode(safeText));
3277
+ return pending.slice(-lookbehind);
3278
+ };
3279
+ var updateInjectedState = (consumed, injected, pending) => {
3280
+ if (consumed.done) {
3281
+ return { done: true, injected, pending };
3282
+ }
3283
+ return {
3284
+ done: false,
3285
+ injected: consumed.injected,
3286
+ pending: consumed.pending
3287
+ };
3288
+ };
3289
+ var readStreamChunk = async (reader) => {
3290
+ const { done, value } = await reader.read();
3291
+ if (done || !value) {
3292
+ return { done, value: undefined };
3293
+ }
3294
+ return { done, value };
3295
+ };
3296
+ var pipeStreamWithHeadInjection = (stream, markup) => {
3297
+ const encoder = new TextEncoder;
3298
+ const decoder = new TextDecoder;
3299
+ const lookbehind = CLOSING_HEAD_TAG.length - 1;
3300
+ const processPending = (controller, pending, injected) => {
3301
+ if (injected) {
3302
+ controller.enqueue(encoder.encode(pending));
3303
+ return { injected, pending: "" };
3304
+ }
3305
+ const headIndex = pending.indexOf(CLOSING_HEAD_TAG);
3306
+ if (headIndex >= 0) {
3307
+ const next = `${pending.slice(0, headIndex)}${markup}${pending.slice(headIndex)}`;
3308
+ controller.enqueue(encoder.encode(next));
3309
+ return { injected: true, pending: "" };
3310
+ }
3311
+ return {
3312
+ injected,
3313
+ pending: flushSafePendingText(controller, encoder, pending, lookbehind)
3314
+ };
3315
+ };
3316
+ const finishHeadInjectionStream = (controller, pending, injected) => {
3317
+ let finalPending = pending + decoder.decode();
3318
+ if (!injected) {
3319
+ finalPending = injectHeadMarkup(finalPending, markup);
3320
+ }
3321
+ if (finalPending.length > 0) {
3322
+ controller.enqueue(encoder.encode(finalPending));
3323
+ }
3324
+ controller.close();
3325
+ };
3326
+ const consumeHeadChunk = async (controller, reader, pending, injected) => {
3327
+ const { done, value } = await readStreamChunk(reader);
3328
+ if (done || !value) {
3329
+ return { done, injected, pending };
3330
+ }
3331
+ const processed = processPending(controller, pending + streamChunkToString(value, decoder), injected);
3332
+ return {
3333
+ done,
3334
+ injected: processed.injected,
3335
+ pending: processed.pending
3336
+ };
3337
+ };
3338
+ const runHeadInjectionLoop = async (controller, reader) => {
3339
+ const consumeNextHeadChunk = async (injected, pending) => {
3340
+ const consumed = await consumeHeadChunk(controller, reader, pending, injected);
3341
+ const nextState = updateInjectedState(consumed, injected, pending);
3342
+ if (nextState.done) {
3343
+ return { injected, pending };
3344
+ }
3345
+ return consumeNextHeadChunk(nextState.injected, nextState.pending);
3346
+ };
3347
+ return consumeNextHeadChunk(false, "");
3348
+ };
3349
+ return new ReadableStream({
3350
+ async start(controller) {
3351
+ const reader = stream.getReader();
3352
+ try {
3353
+ const { injected, pending } = await runHeadInjectionLoop(controller, reader);
3354
+ finishHeadInjectionStream(controller, pending, injected);
3355
+ } catch (error) {
3356
+ controller.error(error);
3357
+ }
3358
+ }
3359
+ });
3360
+ };
3361
+ var pipeStreamWithIslandMarkerDetection = (stream, markup) => {
3362
+ const encoder = new TextEncoder;
3363
+ const decoder = new TextDecoder;
3364
+ const lookbehind = Math.max(ISLAND_MARKER.length, BYTES_PER_KILOBYTE);
3365
+ const processPending = (controller, pending, injected) => {
3366
+ if (injected) {
3367
+ controller.enqueue(encoder.encode(pending));
3368
+ return { injected, pending: "" };
3369
+ }
3370
+ const markerIndex = pending.indexOf(ISLAND_MARKER);
3371
+ if (markerIndex >= 0) {
3372
+ const tagStart = pending.lastIndexOf("<", markerIndex);
3373
+ const injectAt = tagStart >= 0 ? tagStart : markerIndex;
3374
+ const next = `${pending.slice(0, injectAt)}${markup}${pending.slice(injectAt)}`;
3375
+ controller.enqueue(encoder.encode(next));
3376
+ return { injected: true, pending: "" };
3377
+ }
3378
+ return {
3379
+ injected,
3380
+ pending: flushSafePendingText(controller, encoder, pending, lookbehind)
3381
+ };
3382
+ };
3383
+ const finishIslandMarkerStream = (controller, pending) => {
3384
+ const finalPending = pending + decoder.decode();
3385
+ if (finalPending.length > 0) {
3386
+ controller.enqueue(encoder.encode(finalPending));
3387
+ }
3388
+ controller.close();
3389
+ };
3390
+ const consumeIslandChunk = async (controller, reader, pending, injected) => {
3391
+ const { done, value } = await readStreamChunk(reader);
3392
+ if (done || !value) {
3393
+ return { done, injected, pending };
3394
+ }
3395
+ const processed = processPending(controller, pending + streamChunkToString(value, decoder), injected);
3396
+ return {
3397
+ done,
3398
+ injected: processed.injected,
3399
+ pending: processed.pending
3400
+ };
3401
+ };
3402
+ const runIslandMarkerLoop = async (controller, reader) => {
3403
+ const consumeNextIslandChunk = async (injected, pending) => {
3404
+ const consumed = await consumeIslandChunk(controller, reader, pending, injected);
3405
+ const nextState = updateInjectedState(consumed, injected, pending);
3406
+ if (nextState.done) {
3407
+ return { injected, pending };
3408
+ }
3409
+ return consumeNextIslandChunk(nextState.injected, nextState.pending);
3410
+ };
3411
+ return consumeNextIslandChunk(false, "");
3412
+ };
3413
+ return new ReadableStream({
3414
+ async start(controller) {
3415
+ const reader = stream.getReader();
3416
+ try {
3417
+ const { pending } = await runIslandMarkerLoop(controller, reader);
3418
+ finishIslandMarkerStream(controller, pending);
3419
+ } catch (error) {
3420
+ controller.error(error);
3421
+ }
3422
+ }
3423
+ });
3424
+ };
3425
+ var htmlContainsIslands = (html) => html.includes(ISLAND_MARKER);
3426
+ var injectIslandPageContext = (html, options) => {
3427
+ const manifest = globalThis.__absoluteManifest;
3428
+ const hasIslands = options?.hasIslands ?? htmlContainsIslands(html);
3429
+ if (!manifest || !hasIslands) {
3430
+ return html;
3431
+ }
3432
+ if (html.includes(MANIFEST_MARKER) || html.includes(ISLAND_STATE_MARKER)) {
3433
+ return html;
3434
+ }
3435
+ return injectHeadMarkup(html, buildIslandsHeadMarkup(manifest));
3436
+ };
3437
+ var injectIslandPageContextStream = (stream, options) => {
3438
+ const manifest = globalThis.__absoluteManifest;
3439
+ if (!manifest)
3440
+ return stream;
3441
+ const markup = buildIslandsHeadMarkup(manifest);
3442
+ if (options?.hasIslands === true) {
3443
+ return pipeStreamWithHeadInjection(stream, markup);
3444
+ }
3445
+ if (options?.hasIslands === false) {
3446
+ return stream;
3447
+ }
3448
+ return pipeStreamWithIslandMarkerDetection(stream, markup);
3449
+ };
3450
+ var setCurrentIslandManifest = (manifest) => {
3451
+ globalThis.__absoluteManifest = manifest;
3452
+ };
3453
+
3454
+ // src/vue/pageHandler.ts
3455
+ init_devRouteRegistrationCallsite();
3456
+
3457
+ // src/core/responseEnhancers.ts
3458
+ init_streamingSlots();
3459
+ var toResponse = async (responseLike) => responseLike;
3460
+ var cloneHeaders = (response) => {
3461
+ const headers = new Headers(response.headers);
3462
+ return headers;
3463
+ };
3464
+ var enhanceHtmlResponseWithStreamingSlots = (response, {
3465
+ nonce,
3466
+ onError,
3467
+ runtimePlacement,
3468
+ runtimePreludeScript,
3469
+ streamingSlots = [],
3470
+ policy
3471
+ } = {}) => {
3472
+ if (!response.body || streamingSlots.length === 0) {
3473
+ return response;
3474
+ }
3475
+ const body = appendStreamingSlotPatchesToStream(response.body, streamingSlots, {
3476
+ nonce,
3477
+ onError,
3478
+ policy,
3479
+ runtimePlacement,
3480
+ runtimePreludeScript
3481
+ });
3482
+ return new Response(body, {
3483
+ headers: cloneHeaders(response),
3484
+ status: response.status,
3485
+ statusText: response.statusText
3486
+ });
3487
+ };
3488
+ var withStreamingSlots = async (responseLike, options = {}) => enhanceHtmlResponseWithStreamingSlots(await toResponse(responseLike), options);
3489
+ var mergeStreamingSlots = (registered, explicit) => {
3490
+ const merged = new Map;
3491
+ for (const slot of registered)
3492
+ merged.set(slot.id, slot);
3493
+ for (const slot of explicit)
3494
+ merged.set(slot.id, slot);
3495
+ return [...merged.values()];
3496
+ };
3497
+ var withRegisteredStreamingSlots = async (renderResponse, options = {}) => {
3498
+ const { result, slots } = await runWithStreamingSlotRegistry(renderResponse);
3499
+ const explicit = options.streamingSlots ?? [];
3500
+ return withStreamingSlots(result, {
3501
+ ...options,
3502
+ streamingSlots: mergeStreamingSlots(slots, explicit)
3503
+ });
3504
+ };
3505
+
3506
+ // src/core/streamingSlotWarningScope.ts
3507
+ init_logger();
3508
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
3509
+ var STREAMING_SLOT_WARNING_STORAGE_KEY2 = Symbol.for("absolutejs.streamingSlotWarningAsyncLocalStorage");
3510
+ var isObjectRecord5 = (value) => Boolean(value) && typeof value === "object";
3511
+ var isAsyncLocalStorage3 = (value) => isObjectRecord5(value) && ("getStore" in value) && typeof value.getStore === "function" && ("run" in value) && typeof value.run === "function";
3512
+ var getWarningStorage = () => {
3513
+ const value = Reflect.get(globalThis, STREAMING_SLOT_WARNING_STORAGE_KEY2);
3514
+ if (value === null || typeof value === "undefined") {
3515
+ return;
3516
+ }
3517
+ return isAsyncLocalStorage3(value) ? value : undefined;
3518
+ };
3519
+ var ensureWarningStorage = () => {
3520
+ const existing = getWarningStorage();
3521
+ if (existing) {
3522
+ return existing;
3523
+ }
3524
+ const storage = new AsyncLocalStorage2;
3525
+ Reflect.set(globalThis, STREAMING_SLOT_WARNING_STORAGE_KEY2, storage);
3526
+ return storage;
3527
+ };
3528
+ var normalizeCallsitePath2 = (value) => value.replace(`${process.cwd()}/`, "").replace(process.cwd(), "").replace(/^\.\/+/, "");
3529
+ var formatWarningCallsite = (callsite) => {
3530
+ const match = callsite.match(/^(.*?)(:\d+:\d+)$/);
3531
+ if (!match) {
3532
+ return `\x1B[36m${callsite}\x1B[0m`;
3533
+ }
3534
+ return `\x1B[36m${match[1]}\x1B[33m${match[2]}\x1B[0m`;
3535
+ };
3536
+ var shouldIgnoreWarningFrame = (frame) => frame.includes("/node_modules/") || frame.includes("/dist/") || frame.includes("/src/react/pageHandler.") || frame.includes("/src/vue/pageHandler.") || frame.includes("/src/svelte/pageHandler.") || frame.includes("/src/angular/pageHandler.") || frame.includes("/src/core/streamingSlotWarningScope.");
3537
+ var getWarningLocation = (frame) => frame.match(/\((\/[^)]+:\d+:\d+)\)$/)?.[1] ?? frame.match(/at (\/[^ ]+:\d+:\d+)$/)?.[1];
3538
+ var extractCallsiteFromStack = (stack) => {
3539
+ const location = stack.split(`
3540
+ `).slice(1).map((line) => line.trim()).filter((frame) => !shouldIgnoreWarningFrame(frame)).map((frame) => getWarningLocation(frame)).find((frameLocation) => frameLocation !== undefined);
3541
+ return location ? normalizeCallsitePath2(location) : undefined;
3542
+ };
3543
+ var buildMissingCollectorWarning = (primitiveName, handlerCallsite) => `${primitiveName} rendered during SSR without streaming slot collection enabled. Add { collectStreamingSlots: true } to this page handler to enable out-of-order streaming for this route.${handlerCallsite ? ` Update ${formatWarningCallsite(handlerCallsite)}.` : ""}`;
3544
+ setStreamingSlotWarningController({
3545
+ maybeWarn: (primitiveName) => {
3546
+ const store = getWarningStorage()?.getStore();
3547
+ if (!store || store.hasWarned) {
3548
+ return;
3549
+ }
3550
+ store.hasWarned = true;
3551
+ logWarn(buildMissingCollectorWarning(primitiveName, store.handlerCallsite));
3552
+ }
3553
+ });
3554
+ var captureStreamingSlotWarningCallsite = () => {
3555
+ if (false) {}
3556
+ const { stack } = new Error;
3557
+ if (!stack) {
3558
+ return;
3559
+ }
3560
+ return extractCallsiteFromStack(stack);
3561
+ };
3562
+ var runWithStreamingSlotWarningScope = (task, metadata) => ensureWarningStorage().run({ handlerCallsite: metadata?.handlerCallsite, hasWarned: false }, task);
3563
+
3564
+ // src/vue/pageHandler.ts
3565
+ init_ssrCache();
3566
+
3567
+ // src/utils/ssrErrorPage.ts
3568
+ var ssrErrorPage = (framework, error) => {
3569
+ const frameworkColors2 = {
3570
+ angular: "#dd0031",
3571
+ html: "#e34c26",
3572
+ htmx: "#1a365d",
3573
+ react: "#61dafb",
3574
+ svelte: "#ff3e00",
3575
+ vue: "#42b883"
3576
+ };
3577
+ const accent = frameworkColors2[framework] ?? "#94a3b8";
3578
+ const label = framework.charAt(0).toUpperCase() + framework.slice(1);
3579
+ const message = error instanceof Error ? error.message : String(error);
3580
+ return `<!DOCTYPE html>
3581
+ <html>
3582
+ <head>
3583
+ <meta charset="utf-8">
3584
+ <meta name="viewport" content="width=device-width, initial-scale=1">
3585
+ <title>SSR Error - AbsoluteJS</title>
3586
+ <style>
3587
+ *{margin:0;padding:0;box-sizing:border-box}
3588
+ body{min-height:100vh;background:linear-gradient(135deg,rgba(15,23,42,0.98) 0%,rgba(30,41,59,0.98) 100%);color:#e2e8f0;font-family:"JetBrains Mono","Fira Code",ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;font-size:14px;line-height:1.6;display:flex;align-items:flex-start;justify-content:center;padding:32px}
3589
+ .card{max-width:720px;width:100%;background:rgba(30,41,59,0.6);border:1px solid rgba(71,85,105,0.5);border-radius:16px;box-shadow:0 25px 50px -12px rgba(0,0,0,0.5),0 0 0 1px rgba(255,255,255,0.05);overflow:hidden}
3590
+ .header{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:20px 24px;background:rgba(15,23,42,0.5);border-bottom:1px solid rgba(71,85,105,0.4)}
3591
+ .brand{font-weight:700;font-size:20px;color:#fff;letter-spacing:-0.02em}
3592
+ .badge{padding:5px 10px;border-radius:8px;font-size:12px;font-weight:600;background:${accent};color:#fff;opacity:0.95;box-shadow:0 2px 4px rgba(0,0,0,0.2)}
3593
+ .kind{color:#94a3b8;font-size:13px;font-weight:500}
3594
+ .content{padding:24px}
3595
+ .label{font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.08em;color:#94a3b8;margin-bottom:8px}
3596
+ .message{margin:0;padding:16px 20px;background:rgba(239,68,68,0.12);border:1px solid rgba(239,68,68,0.25);border-radius:10px;overflow-x:auto;white-space:pre-wrap;word-break:break-word;color:#fca5a5;font-size:13px;line-height:1.5}
3597
+ .hint{margin-top:20px;padding:12px 20px;background:rgba(71,85,105,0.3);border-radius:10px;border:1px solid rgba(71,85,105,0.4);color:#cbd5e1;font-size:13px}
3598
+ </style>
3599
+ </head>
3600
+ <body>
3601
+ <div class="card">
3602
+ <div class="header">
3603
+ <div style="display:flex;align-items:center;gap:12px">
3604
+ <span class="brand">AbsoluteJS</span>
3605
+ <span class="badge">${label}</span>
3606
+ </div>
3607
+ <span class="kind">Server Render Error</span>
3608
+ </div>
3609
+ <div class="content">
3610
+ <div class="label">What went wrong</div>
3611
+ <pre class="message">${message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")}</pre>
3612
+ <div class="hint">A component threw during server-side rendering. Check the terminal for the full stack trace.</div>
3613
+ </div>
3614
+ </div>
3615
+ </body>
3616
+ </html>`;
3617
+ };
3618
+
3619
+ // src/utils/resolveConvention.ts
3620
+ import { basename } from "path";
3621
+ var CONVENTIONS_KEY = "__absoluteConventions";
3622
+ var isConventionsMap = (value) => Boolean(value) && typeof value === "object";
3623
+ var getMap = () => {
3624
+ const value = Reflect.get(globalThis, CONVENTIONS_KEY);
3625
+ if (isConventionsMap(value))
3626
+ return value;
3627
+ const empty = {};
3628
+ return empty;
3629
+ };
3630
+ var derivePageName = (pagePath) => {
3631
+ const base = basename(pagePath);
3632
+ const dotIndex = base.indexOf(".");
3633
+ const name = dotIndex > 0 ? base.slice(0, dotIndex) : base;
3634
+ return toPascal(name);
3635
+ };
3636
+ var normalizeConventionPageName = (name) => toPascal(name).replace(/\d+$/, "");
3637
+ var resolveErrorConventionPath = (framework, pageName) => {
3638
+ const conventions = getMap()[framework];
3639
+ if (!conventions)
3640
+ return;
3641
+ const exact = conventions.pages?.[pageName]?.error;
3642
+ if (exact)
3643
+ return exact;
3644
+ const normalizedPageName = normalizeConventionPageName(pageName);
3645
+ for (const [candidate, page] of Object.entries(conventions.pages ?? {})) {
3646
+ if (normalizeConventionPageName(candidate) === normalizedPageName) {
3647
+ return page.error ?? conventions.defaults?.error;
3648
+ }
3649
+ }
3650
+ return conventions.defaults?.error;
3651
+ };
3652
+ var resolveNotFoundConventionPath = (framework) => getMap()[framework]?.defaults?.notFound;
3653
+ var hasErrorConvention = (framework) => {
3654
+ const conventions = getMap()[framework];
3655
+ if (!conventions)
3656
+ return false;
3657
+ if (conventions.defaults?.error)
3658
+ return true;
3659
+ return Object.values(conventions.pages ?? {}).some((page) => Boolean(page.error));
3660
+ };
3661
+ var setConventions = (map) => {
3662
+ Reflect.set(globalThis, CONVENTIONS_KEY, map);
3663
+ };
3664
+ var isDev = () => true;
3665
+ var buildErrorProps = (error) => {
3666
+ const message = error instanceof Error ? error.message : String(error);
3667
+ const stack = isDev() && error instanceof Error ? error.stack : undefined;
3668
+ return { error: { message, stack } };
3669
+ };
3670
+ var renderReactError = async (conventionPath, errorProps) => {
3671
+ const { createElement } = await import("react");
3672
+ const { renderToReadableStream } = await import("react-dom/server");
3673
+ const mod = await import(conventionPath);
3674
+ const [firstKey] = Object.keys(mod);
3675
+ const ErrorComponent = mod.default ?? (firstKey ? mod[firstKey] : undefined);
3676
+ const element = createElement(ErrorComponent, errorProps);
3677
+ const stream = await renderToReadableStream(element);
3678
+ return new Response(stream, {
3679
+ headers: { "Content-Type": "text/html" },
3680
+ status: 500
3681
+ });
3682
+ };
3683
+ var renderSvelteError = async (conventionPath, errorProps) => {
3684
+ const { render } = await import("svelte/server");
3685
+ const mod = await import(conventionPath);
3686
+ const ErrorComponent = mod.default;
3687
+ const { head, body } = render(ErrorComponent, {
3688
+ props: errorProps
3689
+ });
3690
+ const html = `<!DOCTYPE html><html><head>${head}</head><body>${body}</body></html>`;
3691
+ return new Response(html, {
3692
+ headers: { "Content-Type": "text/html" },
3693
+ status: 500
3694
+ });
3695
+ };
3696
+ var unescapeVueStyles = (ssrBody) => {
3697
+ let styles = "";
3698
+ const body = ssrBody.replace(/<style>([\s\S]*?)<\/style>/g, (_, css) => {
3699
+ styles += `<style>${css.replace(/&quot;/g, '"').replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">")}</style>`;
3700
+ return "";
3701
+ });
3702
+ return { body, styles };
3703
+ };
3704
+ var renderVueError = async (conventionPath, errorProps) => {
3705
+ const { createSSRApp, h: h4 } = await import("vue");
3706
+ const { renderToString } = await import("vue/server-renderer");
3707
+ const mod = await import(conventionPath);
3708
+ const ErrorComponent = mod.default;
3709
+ const app = createSSRApp({
3710
+ render: () => h4(ErrorComponent, errorProps)
3711
+ });
3712
+ const rawBody = await renderToString(app);
3713
+ const { styles, body } = unescapeVueStyles(rawBody);
3714
+ const html = `<!DOCTYPE html><html><head>${styles}</head><body><div id="root">${body}</div></body></html>`;
3715
+ return new Response(html, {
3716
+ headers: { "Content-Type": "text/html" },
3717
+ status: 500
3718
+ });
3719
+ };
3720
+ var renderAngularError = async (conventionPath, errorProps) => {
3721
+ const mod = await import(conventionPath);
3722
+ const renderError = mod.default ?? mod.renderError;
3723
+ if (typeof renderError !== "function")
3724
+ return null;
3725
+ const html = renderError(errorProps);
3726
+ return new Response(html, {
3727
+ headers: { "Content-Type": "text/html" },
3728
+ status: 500
3729
+ });
3730
+ };
3731
+ var logConventionRenderError = (framework, label, renderError) => {
3732
+ const message = renderError instanceof Error ? renderError.message : "";
3733
+ if (message.includes("Cannot find module") || message.includes("Cannot find package") || message.includes("not found in module")) {
3734
+ console.error(`[SSR] Convention ${label} page for ${framework} failed: missing framework package. Ensure the ${framework} runtime is installed (e.g. bun add ${framework === "react" ? "react react-dom" : framework}).`);
3735
+ return;
3736
+ }
3737
+ console.error(`[SSR] Failed to render ${framework} convention ${label} page:`, renderError);
3738
+ };
3739
+ var ERROR_RENDERERS = {
3740
+ angular: renderAngularError,
3741
+ react: renderReactError,
3742
+ svelte: renderSvelteError,
3743
+ vue: renderVueError
3744
+ };
3745
+ var renderConventionError = async (framework, pageName, error) => {
3746
+ let conventionPath = resolveErrorConventionPath(framework, pageName);
3747
+ if (!conventionPath && error instanceof Error && error.stack) {
3748
+ for (const match of error.stack.matchAll(/^\s*at\s+([A-Za-z_$][\w$]*)/gm)) {
3749
+ const candidate = match[1];
3750
+ if (!candidate)
3751
+ continue;
3752
+ conventionPath = resolveErrorConventionPath(framework, candidate);
3753
+ if (conventionPath)
3754
+ break;
3755
+ }
3756
+ }
3757
+ if (!conventionPath)
3758
+ return null;
3759
+ const errorProps = buildErrorProps(error);
3760
+ const renderer = ERROR_RENDERERS[framework];
3761
+ if (!renderer)
3762
+ return null;
3763
+ try {
3764
+ return await renderer(conventionPath, errorProps);
3765
+ } catch (renderError) {
3766
+ logConventionRenderError(framework, "error", renderError);
3767
+ }
3768
+ return null;
3769
+ };
3770
+ var renderReactNotFound = async (conventionPath) => {
3771
+ const { createElement } = await import("react");
3772
+ const { renderToReadableStream } = await import("react-dom/server");
3773
+ const mod = await import(conventionPath);
3774
+ const [nfKey] = Object.keys(mod);
3775
+ const NotFoundComponent = mod.default ?? (nfKey ? mod[nfKey] : undefined);
3776
+ const element = createElement(NotFoundComponent);
3777
+ const stream = await renderToReadableStream(element);
3778
+ return new Response(stream, {
3779
+ headers: { "Content-Type": "text/html" },
3780
+ status: 404
3781
+ });
3782
+ };
3783
+ var renderSvelteNotFound = async (conventionPath) => {
3784
+ const { render } = await import("svelte/server");
3785
+ const mod = await import(conventionPath);
3786
+ const NotFoundComponent = mod.default;
3787
+ const { head, body } = render(NotFoundComponent);
3788
+ const html = `<!DOCTYPE html><html><head>${head}</head><body>${body}</body></html>`;
3789
+ return new Response(html, {
3790
+ headers: { "Content-Type": "text/html" },
3791
+ status: 404
3792
+ });
3793
+ };
3794
+ var renderVueNotFound = async (conventionPath) => {
3795
+ const { createSSRApp, h: h4 } = await import("vue");
3796
+ const { renderToString } = await import("vue/server-renderer");
3797
+ const mod = await import(conventionPath);
3798
+ const NotFoundComponent = mod.default;
3799
+ const app = createSSRApp({
3800
+ render: () => h4(NotFoundComponent)
3801
+ });
3802
+ const rawBody = await renderToString(app);
3803
+ const { styles, body } = unescapeVueStyles(rawBody);
3804
+ const html = `<!DOCTYPE html><html><head>${styles}</head><body><div id="root">${body}</div></body></html>`;
3805
+ return new Response(html, {
3806
+ headers: { "Content-Type": "text/html" },
3807
+ status: 404
3808
+ });
3809
+ };
3810
+ var renderAngularNotFound = async (conventionPath) => {
3811
+ const mod = await import(conventionPath);
3812
+ const renderNotFound = mod.default ?? mod.renderNotFound;
3813
+ if (typeof renderNotFound !== "function")
3814
+ return null;
3815
+ const html = renderNotFound();
3816
+ return new Response(html, {
3817
+ headers: { "Content-Type": "text/html" },
3818
+ status: 404
3819
+ });
3820
+ };
3821
+ var NOT_FOUND_RENDERERS = {
3822
+ angular: renderAngularNotFound,
3823
+ react: renderReactNotFound,
3824
+ svelte: renderSvelteNotFound,
3825
+ vue: renderVueNotFound
3826
+ };
3827
+ var renderConventionNotFound = async (framework) => {
3828
+ const conventionPath = resolveNotFoundConventionPath(framework);
3829
+ if (!conventionPath)
3830
+ return null;
3831
+ const renderer = NOT_FOUND_RENDERERS[framework];
3832
+ if (!renderer)
3833
+ return null;
3834
+ try {
3835
+ return await renderer(conventionPath);
3836
+ } catch (renderError) {
3837
+ logConventionRenderError(framework, "not-found", renderError);
3838
+ }
3839
+ return null;
3840
+ };
3841
+ var NOT_FOUND_PRIORITY = [
3842
+ "react",
3843
+ "svelte",
3844
+ "vue",
3845
+ "angular"
3846
+ ];
3847
+ var renderFirstNotFound = async () => {
3848
+ const renderNext = async (frameworks) => {
3849
+ const [framework, ...remaining] = frameworks;
3850
+ if (!framework) {
3851
+ return null;
3852
+ }
3853
+ if (!getMap()[framework]?.defaults?.notFound) {
3854
+ return renderNext(remaining);
3855
+ }
3856
+ const response = await renderConventionNotFound(framework);
3857
+ if (response) {
3858
+ return response;
3859
+ }
3860
+ return renderNext(remaining);
3861
+ };
3862
+ return renderNext(NOT_FOUND_PRIORITY);
3863
+ };
3864
+
3865
+ // src/vue/pageHandler.ts
3866
+ var isRecord2 = (value) => typeof value === "object" && value !== null;
3867
+ var isGenericVueComponent = (value) => typeof value === "function" || isRecord2(value);
3868
+ var readHasIslands = (value) => {
3869
+ if (!isRecord2(value))
3870
+ return false;
3871
+ const hasIslands = value["__ABSOLUTE_PAGE_HAS_ISLANDS__"];
3872
+ return typeof hasIslands === "boolean" ? hasIslands : false;
3873
+ };
3874
+ var readDefaultExport = (value) => isRecord2(value) ? value.default : undefined;
3875
+ var resolveCurrentGeneratedVueModulePath = async (pagePath) => {
3876
+ const pageDirectory = dirname(pagePath);
3877
+ const expectedPrefix = `${basename2(pagePath, ".js").split(".")[0]}.`;
3878
+ try {
3879
+ const pageEntries = await readdir(pageDirectory, {
3880
+ withFileTypes: true
3881
+ });
3882
+ const matchingEntry = pageEntries.find((entry) => entry.isFile() && entry.name.endsWith(".js") && (entry.name === `${expectedPrefix.slice(0, EXCLUDE_LAST_OFFSET)}.js` || entry.name.startsWith(expectedPrefix)));
3883
+ if (!matchingEntry) {
3884
+ return pagePath;
3885
+ }
3886
+ return `${pageDirectory}/${matchingEntry.name}`;
3887
+ } catch {
3888
+ return pagePath;
3889
+ }
3890
+ };
3891
+ var buildDirtyResponse = (headTag, indexPath, maybeProps) => {
3892
+ const propsScript = `window.__INITIAL_PROPS__=${JSON.stringify(maybeProps ?? {})};`;
3893
+ const dirtyFlag = "window.__SSR_DIRTY__=true;";
3894
+ const html = `<!DOCTYPE html><html>${headTag}<body><div id="root"></div>` + `<script>${propsScript}${dirtyFlag}</script>` + `<script type="module" src="${indexPath}"></script>` + `</body></html>`;
3895
+ return new Response(html, {
3896
+ headers: { "Content-Type": "text/html" }
3897
+ });
3898
+ };
3899
+ var primeVueStream = async (stream) => {
3900
+ const reader = stream.getReader();
3901
+ const firstChunk = await reader.read();
3902
+ return { firstChunk, reader };
3903
+ };
3904
+ var handleVuePageRequest = async (input) => {
3905
+ const passedPageComponent = input.Page;
3906
+ const resolvedHeadTag = input.headTag ?? "<head></head>";
3907
+ const resolvedIndexPath = input.indexPath;
3908
+ const resolvedOptions = input;
3909
+ const resolvedPagePath = input.pagePath;
3910
+ const maybeProps = input.props;
3911
+ if (isSsrCacheDirty("vue")) {
3912
+ return buildDirtyResponse(resolvedHeadTag, resolvedIndexPath, maybeProps);
3913
+ }
3914
+ try {
3915
+ const handlerCallsite = resolvedOptions?.collectStreamingSlots === true ? undefined : getCurrentRouteRegistrationCallsite() ?? captureStreamingSlotWarningCallsite();
3916
+ const renderPageResponse = async () => {
3917
+ const resolvePageComponent = async () => {
3918
+ if (isGenericVueComponent(passedPageComponent)) {
3919
+ return {
3920
+ component: passedPageComponent,
3921
+ hasIslands: readHasIslands(passedPageComponent)
3922
+ };
3923
+ }
3924
+ const generatedPagePath = await resolveCurrentGeneratedVueModulePath(resolvedPagePath);
3925
+ const importedPageModule = await import(generatedPagePath);
3926
+ const importedPageComponent = readDefaultExport(importedPageModule) ?? importedPageModule;
3927
+ if (!isGenericVueComponent(importedPageComponent)) {
3928
+ throw new Error(`Invalid Vue page module: ${generatedPagePath}`);
3929
+ }
3930
+ return {
3931
+ component: importedPageComponent,
3932
+ hasIslands: readHasIslands(importedPageModule)
3933
+ };
3934
+ };
3935
+ const resolvedPage = await resolvePageComponent();
3936
+ const { createSSRApp, h: h4 } = await import("vue");
3937
+ const { renderToWebStream } = await import("vue/server-renderer");
3938
+ const app = createSSRApp({
3939
+ render: () => h4(resolvedPage.component, maybeProps ?? null)
3940
+ });
3941
+ const bodyStream = renderToWebStream(app);
3942
+ const { firstChunk, reader } = await primeVueStream(bodyStream);
3943
+ const head = `<!DOCTYPE html><html>${resolvedHeadTag}<body><div id="root">`;
3944
+ const tail = `</div><script>window.__INITIAL_PROPS__=${JSON.stringify(maybeProps ?? {})}</script><script type="module" src="${resolvedIndexPath}"></script></body></html>`;
3945
+ const stream = new ReadableStream({
3946
+ start(controller) {
3947
+ controller.enqueue(head);
3948
+ if (!firstChunk.done) {
3949
+ controller.enqueue(firstChunk.value);
3950
+ }
3951
+ if (firstChunk.done) {
3952
+ controller.enqueue(tail);
3953
+ controller.close();
3954
+ return;
3955
+ }
3956
+ const pumpLoop = () => {
3957
+ reader.read().then(({ done, value }) => done ? (controller.enqueue(tail), controller.close()) : (controller.enqueue(value), pumpLoop())).catch((err) => controller.error(err));
3958
+ };
3959
+ pumpLoop();
3960
+ }
3961
+ });
3962
+ const htmlStream = injectIslandPageContextStream(stream, {
3963
+ hasIslands: resolvedPage.hasIslands
3964
+ });
3965
+ return new Response(htmlStream, {
3966
+ headers: { "Content-Type": "text/html" }
3967
+ });
3968
+ };
3969
+ return await runWithStreamingSlotWarningScope(() => resolvedOptions?.collectStreamingSlots === true ? withRegisteredStreamingSlots(renderPageResponse, resolvedOptions) : renderPageResponse(), { handlerCallsite });
3970
+ } catch (error) {
3971
+ console.error("[SSR] Vue render error:", error);
3972
+ const pageName = derivePageName(resolvedPagePath);
3973
+ const conventionResponse = await renderConventionError("vue", pageName, error);
3974
+ if (conventionResponse)
3975
+ return conventionResponse;
3976
+ return new Response(ssrErrorPage("vue", error), {
3977
+ headers: { "Content-Type": "text/html" },
3978
+ status: 500
3979
+ });
3980
+ }
3981
+ };
49
3982
  // src/vue/Island.ts
50
- import { defineComponent, h, onServerPrefetch } from "vue";
51
- var defineRuntimeIslandComponent = (setup) => defineComponent({
3983
+ import { defineComponent as defineComponent4, h as h4, onServerPrefetch } from "vue";
3984
+
3985
+ // src/client/preserveIslandMarkup.ts
3986
+ init_islandMarkupAttributes();
3987
+ var getClaimMap = () => {
3988
+ if (typeof window === "undefined") {
3989
+ return null;
3990
+ }
3991
+ window.__ABS_CLAIMED_ISLAND_MARKUP__ ??= new Map;
3992
+ return window.__ABS_CLAIMED_ISLAND_MARKUP__;
3993
+ };
3994
+ var getSnapshotMap = () => {
3995
+ if (typeof window === "undefined") {
3996
+ return null;
3997
+ }
3998
+ window.__ABS_SERVER_ISLAND_HTML__ ??= new Map;
3999
+ return window.__ABS_SERVER_ISLAND_HTML__;
4000
+ };
4001
+ var getIslandSignature = (props) => {
4002
+ const attributes = getIslandMarkerAttributes(props);
4003
+ return [
4004
+ attributes["data-component"],
4005
+ attributes["data-framework"],
4006
+ attributes["data-hydrate"],
4007
+ attributes["data-props"]
4008
+ ].join("::");
4009
+ };
4010
+ var isMatchingIslandElement = (element, props) => {
4011
+ if (!(element instanceof HTMLElement)) {
4012
+ return false;
4013
+ }
4014
+ const attributes = getIslandMarkerAttributes(props);
4015
+ return element.dataset.island === "true" && element.dataset.component === attributes["data-component"] && element.dataset.framework === attributes["data-framework"] && (element.dataset.hydrate ?? "load") === attributes["data-hydrate"] && (element.dataset.props ?? "{}") === attributes["data-props"];
4016
+ };
4017
+ var snapshotIslandElement = (element, snapshotMap) => {
4018
+ const signature = [
4019
+ element.dataset.component,
4020
+ element.dataset.framework,
4021
+ element.dataset.hydrate ?? "load",
4022
+ element.dataset.props ?? "{}"
4023
+ ].join("::");
4024
+ const existing = snapshotMap.get(signature) ?? [];
4025
+ const attributes = Object.fromEntries(element.getAttributeNames().map((name) => [name, element.getAttribute(name) ?? ""]));
4026
+ existing.push({
4027
+ attributes,
4028
+ innerHTML: element.innerHTML
4029
+ });
4030
+ snapshotMap.set(signature, existing);
4031
+ };
4032
+ var initializeIslandMarkupSnapshot = () => {
4033
+ if (typeof document === "undefined") {
4034
+ return;
4035
+ }
4036
+ const snapshotMap = getSnapshotMap();
4037
+ if (!snapshotMap || snapshotMap.size > 0) {
4038
+ return;
4039
+ }
4040
+ const elements = Array.from(document.querySelectorAll('[data-island="true"]'));
4041
+ for (const element of elements) {
4042
+ snapshotIslandElement(element, snapshotMap);
4043
+ }
4044
+ };
4045
+ var preserveIslandMarkup = (props) => {
4046
+ if (typeof document === "undefined") {
4047
+ return {
4048
+ attributes: getIslandMarkerAttributes(props),
4049
+ innerHTML: ""
4050
+ };
4051
+ }
4052
+ const claimMap = getClaimMap();
4053
+ const snapshotMap = getSnapshotMap();
4054
+ const signature = getIslandSignature(props);
4055
+ const claimedCount = claimMap?.get(signature) ?? 0;
4056
+ const snapshotCandidate = snapshotMap?.get(signature)?.[claimedCount];
4057
+ const candidates = Array.from(document.querySelectorAll('[data-island="true"]')).filter((element) => isMatchingIslandElement(element, props));
4058
+ const candidate = candidates[claimedCount];
4059
+ if (claimMap) {
4060
+ claimMap.set(signature, claimedCount + 1);
4061
+ }
4062
+ return {
4063
+ attributes: snapshotCandidate?.attributes ?? getIslandMarkerAttributes(props),
4064
+ innerHTML: snapshotCandidate?.innerHTML ?? candidate?.innerHTML ?? ""
4065
+ };
4066
+ };
4067
+
4068
+ // src/vue/Island.ts
4069
+ init_islandMarkupAttributes();
4070
+ init_renderIslandMarkup();
4071
+ var defineRuntimeIslandComponent = (setup) => defineComponent4({
52
4072
  name: "AbsoluteIsland",
53
4073
  props: {
54
4074
  component: {
@@ -80,7 +4100,7 @@ var Island = defineRuntimeIslandComponent((props) => {
80
4100
  });
81
4101
  return () => {
82
4102
  const preserved = isBrowser ? preserveIslandMarkup(props) : null;
83
- return h("div", {
4103
+ return h4("div", {
84
4104
  ...preserved?.attributes ?? markerAttributes,
85
4105
  "data-allow-mismatch": "",
86
4106
  innerHTML: isBrowser ? preserved?.innerHTML : html
@@ -88,8 +4108,10 @@ var Island = defineRuntimeIslandComponent((props) => {
88
4108
  };
89
4109
  });
90
4110
  // src/vue/createIsland.ts
91
- import { defineComponent as defineComponent2, h as h2, onServerPrefetch as onServerPrefetch2 } from "vue";
92
- var defineRuntimeIslandComponent2 = (setup) => defineComponent2({
4111
+ init_islandMarkupAttributes();
4112
+ init_renderIslandMarkup();
4113
+ import { defineComponent as defineComponent5, h as h5, onServerPrefetch as onServerPrefetch2 } from "vue";
4114
+ var defineRuntimeIslandComponent2 = (setup) => defineComponent5({
93
4115
  name: "AbsoluteIsland",
94
4116
  props: {
95
4117
  component: {
@@ -119,12 +4141,150 @@ var createTypedIsland = (registry) => defineRuntimeIslandComponent2((props) => {
119
4141
  const result = await renderIslandResult(registry, props);
120
4142
  ({ attributes: markerAttributes, html } = result);
121
4143
  });
122
- return () => h2("div", {
4144
+ return () => h5("div", {
123
4145
  ...markerAttributes,
124
4146
  "data-allow-mismatch": "",
125
4147
  innerHTML: isBrowser ? undefined : html
126
4148
  });
127
4149
  });
4150
+ // src/vue/useIslandStore.ts
4151
+ import { customRef, onBeforeUnmount as onBeforeUnmount2 } from "vue";
4152
+
4153
+ // node_modules/zustand/esm/vanilla.mjs
4154
+ var createStoreImpl = (createState) => {
4155
+ let state;
4156
+ const listeners = /* @__PURE__ */ new Set;
4157
+ const setState = (partial, replace) => {
4158
+ const nextState = typeof partial === "function" ? partial(state) : partial;
4159
+ if (!Object.is(nextState, state)) {
4160
+ const previousState = state;
4161
+ state = (replace != null ? replace : typeof nextState !== "object" || nextState === null) ? nextState : Object.assign({}, state, nextState);
4162
+ listeners.forEach((listener) => listener(state, previousState));
4163
+ }
4164
+ };
4165
+ const getState = () => state;
4166
+ const getInitialState = () => initialState;
4167
+ const subscribe = (listener) => {
4168
+ listeners.add(listener);
4169
+ return () => listeners.delete(listener);
4170
+ };
4171
+ const api = { setState, getState, getInitialState, subscribe };
4172
+ const initialState = state = createState(setState, getState, api);
4173
+ return api;
4174
+ };
4175
+ var createStore = (createState) => createState ? createStoreImpl(createState) : createStoreImpl;
4176
+
4177
+ // node_modules/zustand/esm/middleware.mjs
4178
+ function combine(initialState, create) {
4179
+ return (...args) => Object.assign({}, initialState, create(...args));
4180
+ }
4181
+
4182
+ // src/client/islandStore.ts
4183
+ var getIslandStoreSnapshot = () => {
4184
+ globalThis.__ABS_ISLAND_STATE__ ??= {};
4185
+ return globalThis.__ABS_ISLAND_STATE__;
4186
+ };
4187
+ var getIslandStores = () => {
4188
+ globalThis.__ABS_ISLAND_STORES__ ??= new Map;
4189
+ return globalThis.__ABS_ISLAND_STORES__;
4190
+ };
4191
+ var isSerializableValue = (value) => typeof value !== "function" && value !== undefined;
4192
+ var toSerializableState = (state) => Object.fromEntries(Object.entries(state).filter(([, value]) => isSerializableValue(value)));
4193
+ var applySnapshot = (store, snapshot) => {
4194
+ if (!snapshot) {
4195
+ return;
4196
+ }
4197
+ store.setState({
4198
+ ...store.getState(),
4199
+ ...snapshot
4200
+ });
4201
+ };
4202
+ var getPeerStores = (storeInstances, ownerStore) => [...storeInstances].filter((peer) => peer.store !== ownerStore);
4203
+ var syncIslandSnapshot = (storeId, state, storeInstances, ownerStore) => {
4204
+ const nextSnapshot = toSerializableState(state);
4205
+ getIslandStoreSnapshot()[storeId] = nextSnapshot;
4206
+ for (const peerStore of getPeerStores(storeInstances, ownerStore)) {
4207
+ peerStore.applyExternalSnapshot(nextSnapshot);
4208
+ }
4209
+ };
4210
+ var createIslandStore = (storeId, initialState, createState) => {
4211
+ const store = createStore(combine(initialState, createState));
4212
+ const stores = getIslandStores();
4213
+ const storeInstances = stores.get(storeId) ?? new Set;
4214
+ const initialSnapshot = getIslandStoreSnapshot()[storeId];
4215
+ applySnapshot(store, initialSnapshot);
4216
+ let isApplyingExternalSnapshot = false;
4217
+ const applyExternalSnapshot = (snapshot) => {
4218
+ isApplyingExternalSnapshot = true;
4219
+ applySnapshot(store, snapshot);
4220
+ };
4221
+ storeInstances.add({
4222
+ applyExternalSnapshot,
4223
+ store
4224
+ });
4225
+ stores.set(storeId, storeInstances);
4226
+ syncIslandSnapshot(storeId, store.getState(), storeInstances, store);
4227
+ store.subscribe((state) => {
4228
+ if (isApplyingExternalSnapshot) {
4229
+ isApplyingExternalSnapshot = false;
4230
+ return;
4231
+ }
4232
+ syncIslandSnapshot(storeId, state, storeInstances, store);
4233
+ });
4234
+ return store;
4235
+ };
4236
+ var getIslandStoreServerSnapshot = (store, selector) => selector(store.getInitialState());
4237
+ var applySnapshotToStoreInstances = (storeId, instances, snapshot) => {
4238
+ for (const instance of instances) {
4239
+ instance.applyExternalSnapshot(snapshot[storeId] ?? {});
4240
+ }
4241
+ };
4242
+ var initializeIslandStores = (state) => {
4243
+ const currentSnapshot = getIslandStoreSnapshot();
4244
+ const nextSnapshot = {
4245
+ ...state,
4246
+ ...currentSnapshot
4247
+ };
4248
+ globalThis.__ABS_ISLAND_STATE__ = nextSnapshot;
4249
+ for (const [storeId, store] of getIslandStores()) {
4250
+ applySnapshotToStoreInstances(storeId, store, nextSnapshot);
4251
+ }
4252
+ };
4253
+ var readIslandStore = (store, selector) => selector(store.getState());
4254
+ var subscribeIslandStore = (store, selector, listener) => {
4255
+ let currentSelection = selector(store.getState());
4256
+ return store.subscribe((state) => {
4257
+ const nextSelection = selector(state);
4258
+ if (Object.is(nextSelection, currentSelection)) {
4259
+ return;
4260
+ }
4261
+ currentSelection = nextSelection;
4262
+ listener(nextSelection);
4263
+ });
4264
+ };
4265
+
4266
+ // src/vue/useIslandStore.ts
4267
+ var useIslandStore = (store, selector) => {
4268
+ let current = readIslandStore(store, selector);
4269
+ let unsubscribe;
4270
+ const state = customRef((track, trigger) => {
4271
+ unsubscribe = subscribeIslandStore(store, selector, (value) => {
4272
+ current = value;
4273
+ trigger();
4274
+ });
4275
+ return {
4276
+ get() {
4277
+ track();
4278
+ return current;
4279
+ },
4280
+ set() {}
4281
+ };
4282
+ });
4283
+ onBeforeUnmount2(() => {
4284
+ unsubscribe?.();
4285
+ });
4286
+ return state;
4287
+ };
128
4288
  export {
129
4289
  useIslandStore,
130
4290
  handleVuePageRequest,
@@ -135,5 +4295,5 @@ export {
135
4295
  Image
136
4296
  };
137
4297
 
138
- //# debugId=EAA0EECCB6DF7CBE64756E2164756E21
4298
+ //# debugId=3DBC449F9850B08A64756E2164756E21
139
4299
  //# sourceMappingURL=index.js.map