@absolutejs/absolute 0.19.0-beta.808 → 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 +1100 -40
  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/index.d.ts +1 -0
  38. package/dist/svelte/browser.js +247 -12
  39. package/dist/svelte/browser.js.map +10 -3
  40. package/dist/svelte/index.js +3732 -37
  41. package/dist/svelte/index.js.map +47 -4
  42. package/dist/svelte/server.js +2794 -21
  43. package/dist/svelte/server.js.map +27 -3
  44. package/dist/vue/browser.js +348 -12
  45. package/dist/vue/browser.js.map +12 -4
  46. package/dist/vue/components/Image.js +240 -7
  47. package/dist/vue/components/Image.js.map +6 -3
  48. package/dist/vue/components/index.js +544 -11
  49. package/dist/vue/components/index.js.map +9 -3
  50. package/dist/vue/index.js +4212 -52
  51. package/dist/vue/index.js.map +50 -4
  52. package/dist/vue/server.js +1849 -18
  53. package/dist/vue/server.js.map +21 -3
  54. package/package.json +1 -1
  55. package/dist/chunk-0867j0r0.js +0 -136
  56. package/dist/chunk-0867j0r0.js.map +0 -10
  57. package/dist/chunk-0kdc6r16.js +0 -20
  58. package/dist/chunk-0kdc6r16.js.map +0 -10
  59. package/dist/chunk-102fp7xe.js +0 -63
  60. package/dist/chunk-102fp7xe.js.map +0 -10
  61. package/dist/chunk-11zpfqz6.js +0 -19
  62. package/dist/chunk-11zpfqz6.js.map +0 -10
  63. package/dist/chunk-1rfh7hw9.js +0 -319
  64. package/dist/chunk-1rfh7hw9.js.map +0 -11
  65. package/dist/chunk-25v9t56f.js +0 -29
  66. package/dist/chunk-25v9t56f.js.map +0 -11
  67. package/dist/chunk-2f21eenc.js +0 -21
  68. package/dist/chunk-2f21eenc.js.map +0 -10
  69. package/dist/chunk-2ga2znex.js +0 -13
  70. package/dist/chunk-2ga2znex.js.map +0 -9
  71. package/dist/chunk-30yrw0f6.js +0 -33
  72. package/dist/chunk-30yrw0f6.js.map +0 -10
  73. package/dist/chunk-38jwhqcw.js +0 -4410
  74. package/dist/chunk-38jwhqcw.js.map +0 -28
  75. package/dist/chunk-3g91wb4f.js +0 -358
  76. package/dist/chunk-3g91wb4f.js.map +0 -10
  77. package/dist/chunk-3yjzpcne.js +0 -34
  78. package/dist/chunk-3yjzpcne.js.map +0 -10
  79. package/dist/chunk-41bf6aqt.js +0 -17
  80. package/dist/chunk-41bf6aqt.js.map +0 -9
  81. package/dist/chunk-4d39r92n.js +0 -81
  82. package/dist/chunk-4d39r92n.js.map +0 -10
  83. package/dist/chunk-5003emhv.js +0 -17
  84. package/dist/chunk-5003emhv.js.map +0 -10
  85. package/dist/chunk-5f67rsed.js +0 -466
  86. package/dist/chunk-5f67rsed.js.map +0 -10
  87. package/dist/chunk-5fhp1jap.js +0 -9169
  88. package/dist/chunk-5fhp1jap.js.map +0 -236
  89. package/dist/chunk-6pdj08z3.js +0 -73
  90. package/dist/chunk-6pdj08z3.js.map +0 -12
  91. package/dist/chunk-6qjbrt0k.js +0 -13
  92. package/dist/chunk-6qjbrt0k.js.map +0 -9
  93. package/dist/chunk-6sccb4jr.js +0 -14
  94. package/dist/chunk-6sccb4jr.js.map +0 -9
  95. package/dist/chunk-798spvzv.js +0 -50
  96. package/dist/chunk-798spvzv.js.map +0 -10
  97. package/dist/chunk-7fw6x3js.js +0 -131
  98. package/dist/chunk-7fw6x3js.js.map +0 -11
  99. package/dist/chunk-7kjj42xm.js +0 -11
  100. package/dist/chunk-7kjj42xm.js.map +0 -10
  101. package/dist/chunk-7mtstdqn.js +0 -90
  102. package/dist/chunk-7mtstdqn.js.map +0 -10
  103. package/dist/chunk-851whwc7.js +0 -17
  104. package/dist/chunk-851whwc7.js.map +0 -10
  105. package/dist/chunk-85n68sy6.js +0 -103
  106. package/dist/chunk-85n68sy6.js.map +0 -10
  107. package/dist/chunk-8kcfffry.js +0 -35
  108. package/dist/chunk-8kcfffry.js.map +0 -10
  109. package/dist/chunk-8qqxc1h2.js +0 -426
  110. package/dist/chunk-8qqxc1h2.js.map +0 -14
  111. package/dist/chunk-92fsjfpp.js +0 -1731
  112. package/dist/chunk-92fsjfpp.js.map +0 -11
  113. package/dist/chunk-93sqk7be.js +0 -139
  114. package/dist/chunk-93sqk7be.js.map +0 -12
  115. package/dist/chunk-94gvx0hg.js +0 -28
  116. package/dist/chunk-94gvx0hg.js.map +0 -10
  117. package/dist/chunk-9c5tj4k3.js +0 -130
  118. package/dist/chunk-9c5tj4k3.js.map +0 -10
  119. package/dist/chunk-9ve9jq72.js +0 -203
  120. package/dist/chunk-9ve9jq72.js.map +0 -10
  121. package/dist/chunk-9xrsjeem.js +0 -12
  122. package/dist/chunk-9xrsjeem.js.map +0 -9
  123. package/dist/chunk-a9mvyp04.js +0 -87
  124. package/dist/chunk-a9mvyp04.js.map +0 -10
  125. package/dist/chunk-b3gbnrwe.js +0 -21
  126. package/dist/chunk-b3gbnrwe.js.map +0 -10
  127. package/dist/chunk-bmgqm774.js +0 -65
  128. package/dist/chunk-bmgqm774.js.map +0 -9
  129. package/dist/chunk-bxfghpma.js +0 -69
  130. package/dist/chunk-bxfghpma.js.map +0 -10
  131. package/dist/chunk-c1jfjnka.js +0 -74
  132. package/dist/chunk-c1jfjnka.js.map +0 -10
  133. package/dist/chunk-cbkrwmvh.js +0 -80
  134. package/dist/chunk-cbkrwmvh.js.map +0 -10
  135. package/dist/chunk-cdxd7sy2.js +0 -71
  136. package/dist/chunk-cdxd7sy2.js.map +0 -10
  137. package/dist/chunk-cg95827x.js +0 -21
  138. package/dist/chunk-cg95827x.js.map +0 -10
  139. package/dist/chunk-cm0g4q6w.js +0 -149
  140. package/dist/chunk-cm0g4q6w.js.map +0 -10
  141. package/dist/chunk-cwfy538a.js +0 -51
  142. package/dist/chunk-cwfy538a.js.map +0 -9
  143. package/dist/chunk-d7mwkzry.js +0 -261
  144. package/dist/chunk-d7mwkzry.js.map +0 -10
  145. package/dist/chunk-d8w0qm28.js +0 -184
  146. package/dist/chunk-d8w0qm28.js.map +0 -11
  147. package/dist/chunk-d9c0am65.js +0 -12
  148. package/dist/chunk-d9c0am65.js.map +0 -10
  149. package/dist/chunk-daqghmg8.js +0 -12
  150. package/dist/chunk-daqghmg8.js.map +0 -9
  151. package/dist/chunk-e3r9fxaa.js +0 -149
  152. package/dist/chunk-e3r9fxaa.js.map +0 -10
  153. package/dist/chunk-e8eecyrq.js +0 -244
  154. package/dist/chunk-e8eecyrq.js.map +0 -10
  155. package/dist/chunk-ex2hxe0v.js +0 -160
  156. package/dist/chunk-ex2hxe0v.js.map +0 -11
  157. package/dist/chunk-fak944et.js +0 -91
  158. package/dist/chunk-fak944et.js.map +0 -10
  159. package/dist/chunk-ff70rnhd.js +0 -672
  160. package/dist/chunk-ff70rnhd.js.map +0 -15
  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-j88z31ep.js +0 -25
  180. package/dist/chunk-j88z31ep.js.map +0 -10
  181. package/dist/chunk-jn91vzkh.js +0 -66
  182. package/dist/chunk-jn91vzkh.js.map +0 -10
  183. package/dist/chunk-jpkjdgsk.js +0 -167
  184. package/dist/chunk-jpkjdgsk.js.map +0 -11
  185. package/dist/chunk-jwxt8gnp.js +0 -13
  186. package/dist/chunk-jwxt8gnp.js.map +0 -9
  187. package/dist/chunk-kk8w9rh5.js +0 -195
  188. package/dist/chunk-kk8w9rh5.js.map +0 -10
  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-pnscgw95.js +0 -90
  204. package/dist/chunk-pnscgw95.js.map +0 -10
  205. package/dist/chunk-pvpp4pvs.js +0 -17
  206. package/dist/chunk-pvpp4pvs.js.map +0 -10
  207. package/dist/chunk-qh75agse.js +0 -95
  208. package/dist/chunk-qh75agse.js.map +0 -10
  209. package/dist/chunk-qxq2zcty.js +0 -52
  210. package/dist/chunk-qxq2zcty.js.map +0 -10
  211. package/dist/chunk-r6e8pytx.js +0 -22
  212. package/dist/chunk-r6e8pytx.js.map +0 -9
  213. package/dist/chunk-r7jmgqnw.js +0 -114
  214. package/dist/chunk-r7jmgqnw.js.map +0 -10
  215. package/dist/chunk-s6defjk2.js +0 -116
  216. package/dist/chunk-s6defjk2.js.map +0 -10
  217. package/dist/chunk-sd39p726.js +0 -619
  218. package/dist/chunk-sd39p726.js.map +0 -10
  219. package/dist/chunk-swrnzs4c.js +0 -63
  220. package/dist/chunk-swrnzs4c.js.map +0 -10
  221. package/dist/chunk-tfe3sb44.js +0 -33
  222. package/dist/chunk-tfe3sb44.js.map +0 -10
  223. package/dist/chunk-tjr0kcev.js +0 -41
  224. package/dist/chunk-tjr0kcev.js.map +0 -9
  225. package/dist/chunk-tx9edm1x.js +0 -34
  226. package/dist/chunk-tx9edm1x.js.map +0 -10
  227. package/dist/chunk-txhm2vb5.js +0 -18
  228. package/dist/chunk-txhm2vb5.js.map +0 -9
  229. package/dist/chunk-v5vmsxmy.js +0 -526
  230. package/dist/chunk-v5vmsxmy.js.map +0 -12
  231. package/dist/chunk-vjhxm8n2.js +0 -29
  232. package/dist/chunk-vjhxm8n2.js.map +0 -9
  233. package/dist/chunk-vkrpm7kc.js +0 -247
  234. package/dist/chunk-vkrpm7kc.js.map +0 -12
  235. package/dist/chunk-w3m4m5we.js +0 -4925
  236. package/dist/chunk-w3m4m5we.js.map +0 -12
  237. package/dist/chunk-wrxtn9ve.js +0 -18
  238. package/dist/chunk-wrxtn9ve.js.map +0 -10
  239. package/dist/chunk-wwzvp0zn.js +0 -192
  240. package/dist/chunk-wwzvp0zn.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
@@ -1,28 +1,2801 @@
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/build/resolvePackageImport.ts
64
+ import { resolve, join } from "path";
65
+ import { existsSync, readFileSync } from "fs";
66
+ var resolveExportPath = (entry, conditions) => {
67
+ if (typeof entry === "string")
68
+ return entry;
69
+ if (!entry || typeof entry !== "object")
70
+ return null;
71
+ for (const condition of conditions) {
72
+ const target = Reflect.get(entry, condition);
73
+ if (typeof target === "string") {
74
+ return target;
75
+ }
76
+ }
77
+ return null;
78
+ }, resolvePackageImport = (specifier, conditions = ["import"]) => {
79
+ if (specifier.startsWith(".") || specifier.startsWith("/"))
80
+ return null;
81
+ const parts = specifier.split("/");
82
+ const isScoped = specifier.startsWith("@");
83
+ const packageName = isScoped ? `${parts[0]}/${parts[1]}` : parts[0];
84
+ const subpath = isScoped ? parts.slice(2).join("/") : parts.slice(1).join("/");
85
+ const exportKey = subpath ? `./${subpath}` : ".";
86
+ const currentPackageJsonPath = resolve(process.cwd(), "package.json");
87
+ const currentPackageJson = existsSync(currentPackageJsonPath) ? JSON.parse(readFileSync(currentPackageJsonPath, "utf-8")) : null;
88
+ const currentPackageDir = currentPackageJson?.name === packageName ? process.cwd() : null;
89
+ const packageDir = currentPackageDir ?? resolve(process.cwd(), "node_modules", packageName ?? "");
90
+ const packageJsonPath = join(packageDir, "package.json");
91
+ if (!existsSync(packageJsonPath))
92
+ return null;
93
+ try {
94
+ const packageJson = currentPackageDir && currentPackageJson ? currentPackageJson : JSON.parse(readFileSync(packageJsonPath, "utf-8"));
95
+ const { exports } = packageJson;
96
+ if (!exports)
97
+ return null;
98
+ const entry = exports[exportKey];
99
+ if (!entry)
100
+ return null;
101
+ const importPath = resolveExportPath(entry, conditions);
102
+ if (!importPath)
103
+ return null;
104
+ if (currentPackageDir && importPath.startsWith("./dist/")) {
105
+ const sourceCandidate = resolve(packageDir, importPath.replace(/^\.\/dist\//, "./src/"));
106
+ if (existsSync(sourceCandidate)) {
107
+ return sourceCandidate;
108
+ }
109
+ }
110
+ const resolved = resolve(packageDir, importPath);
111
+ return existsSync(resolved) ? resolved : null;
112
+ } catch {
113
+ return null;
114
+ }
115
+ };
116
+ var init_resolvePackageImport = () => {};
117
+
118
+ // src/constants.ts
119
+ 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;
120
+ var init_constants = __esm(() => {
121
+ IMAGE_DEFAULT_DEVICE_SIZES = [
122
+ 640,
123
+ 750,
124
+ 828,
125
+ 1080,
126
+ 1200,
127
+ 1920,
128
+ 2048,
129
+ 3840
130
+ ];
131
+ IMAGE_DEFAULT_IMAGE_SIZES = [16, 32, 48, 64, 96, 128, 256, 384];
132
+ MILLISECONDS_IN_A_MINUTE = MILLISECONDS_IN_A_SECOND * SECONDS_IN_A_MINUTE;
133
+ MILLISECONDS_IN_A_DAY = MILLISECONDS_IN_A_SECOND * SECONDS_IN_A_MINUTE * MINUTES_IN_AN_HOUR * HOURS_IN_DAY;
134
+ TWO_THIRDS = 2 / 3;
135
+ });
136
+
137
+ // src/svelte/lowerIslandSyntax.ts
138
+ var ISLAND_TAG_RE, extractBracedExpression = (text, braceStart) => {
139
+ let depth = 0;
140
+ for (let index = braceStart;index < text.length; index += 1) {
141
+ const char = text[index];
142
+ if (char === "{")
143
+ depth += 1;
144
+ if (char === "}")
145
+ depth -= 1;
146
+ if (depth === 0) {
147
+ return text.slice(braceStart + 1, index).trim();
148
+ }
149
+ }
150
+ return null;
151
+ }, extractIslandAttribute = (attributeString, name) => {
152
+ const quotedMatch = attributeString.match(new RegExp(`\\b${name}\\s*=\\s*["']([^"']+)["']`));
153
+ if (quotedMatch?.[1]) {
154
+ return { expression: JSON.stringify(quotedMatch[1]), found: true };
155
+ }
156
+ const attributeIndex = attributeString.search(new RegExp(`\\b${name}\\s*=\\s*\\{`));
157
+ if (attributeIndex < 0) {
158
+ return { expression: "", found: false };
159
+ }
160
+ const braceStart = attributeString.indexOf("{", attributeIndex);
161
+ if (braceStart < 0) {
162
+ return { expression: "", found: false };
163
+ }
164
+ const expression = extractBracedExpression(attributeString, braceStart);
165
+ if (expression === null) {
166
+ return { expression: "", found: false };
167
+ }
168
+ return { expression, found: true };
169
+ }, lowerSvelteIslandSyntax = (source, _mode = "server") => {
170
+ if (!source.includes("<Island")) {
171
+ return { code: source, transformed: false };
172
+ }
173
+ let islandIndex = 0;
174
+ const transformedMarkup = source.replace(ISLAND_TAG_RE, (fullMatch, attributeString) => {
175
+ const framework = extractIslandAttribute(attributeString, "framework");
176
+ const component = extractIslandAttribute(attributeString, "component");
177
+ if (!framework.found || !component.found) {
178
+ return fullMatch;
179
+ }
180
+ const hydrate = extractIslandAttribute(attributeString, "hydrate");
181
+ const props = extractIslandAttribute(attributeString, "props");
182
+ const slotId = `absolute-svelte-island-${islandIndex.toString(BASE_36_RADIX)}`;
183
+ islandIndex += 1;
184
+ 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 : "{}"} })`;
185
+ return `<div data-absolute-island-slot="${slotId}" style="display: contents">{@html ${resolveExpression}}</div>`;
186
+ });
187
+ const importLine = 'import { resolveIslandHtml as __absoluteResolveIslandHtml } from "@absolutejs/absolute/svelte";';
188
+ if (transformedMarkup.includes("<script")) {
189
+ return {
190
+ code: transformedMarkup.replace(/<script(\s[^>]*)?>/, (match) => `${match}
191
+ ${importLine}
192
+ `),
193
+ transformed: true
194
+ };
195
+ }
196
+ return {
197
+ code: `<script lang="ts">
198
+ ${importLine}
199
+ </script>
200
+ ${transformedMarkup}`,
201
+ transformed: true
202
+ };
203
+ };
204
+ var init_lowerIslandSyntax = __esm(() => {
205
+ init_constants();
206
+ ISLAND_TAG_RE = /<Island\b([\s\S]*?)\/>/g;
207
+ });
208
+
209
+ // src/svelte/lowerAwaitSlotSyntax.ts
210
+ var AWAIT_BLOCK_RE, escapeTemplateLiteral = (value) => value.replaceAll("\\", "\\\\").replaceAll("`", "\\`").replaceAll("${", "\\${"), markupToTemplateLiteral = (markup) => {
211
+ const escaped = escapeTemplateLiteral(markup.trim());
212
+ const withExpressions = escaped.replace(/\{([^{}]+)\}/g, (_, expression) => `\${${String(expression).trim()}}`);
213
+ return `\`${withExpressions}\``;
214
+ }, lowerSvelteAwaitSlotSyntax = (source) => {
215
+ if (!source.includes("{#await")) {
216
+ return { code: source, transformed: false };
217
+ }
218
+ let awaitIndex = 0;
219
+ let transformed = false;
220
+ const lowered = source.replace(AWAIT_BLOCK_RE, (fullMatch, awaitExpression, pendingMarkup, thenIdentifier, thenMarkup, catchIdentifier, catchMarkup) => {
221
+ const trimmedAwaitExpression = awaitExpression.trim();
222
+ if (!trimmedAwaitExpression) {
223
+ return fullMatch;
224
+ }
225
+ const slotId = `absolute-svelte-await-${awaitIndex.toString(BASE_36_RADIX)}`;
226
+ awaitIndex += 1;
227
+ transformed = true;
228
+ const thenValueIdentifier = thenIdentifier?.trim() || "__awaitValue";
229
+ const catchValueIdentifier = catchIdentifier?.trim() || "__awaitError";
230
+ const fallbackHtml = markupToTemplateLiteral(pendingMarkup);
231
+ const resolvedHtml = markupToTemplateLiteral(thenMarkup);
232
+ const rejectedHtml = typeof catchMarkup === "string" ? markupToTemplateLiteral(catchMarkup) : null;
233
+ const catchBranch = rejectedHtml ? `catch (${catchValueIdentifier}) { return ${rejectedHtml}; }` : "catch (_absoluteAwaitError) { throw _absoluteAwaitError; }";
234
+ return `<AbsoluteAwaitSlot id="${slotId}" fallbackHtml={${fallbackHtml}} resolve={async () => { try { const ${thenValueIdentifier} = await (${trimmedAwaitExpression}); return ${resolvedHtml}; } ${catchBranch} }} />`;
235
+ });
236
+ if (!transformed) {
237
+ return { code: source, transformed: false };
238
+ }
239
+ const importLine = 'import AbsoluteAwaitSlot from "@absolutejs/absolute/svelte/components/AwaitSlot.svelte";';
240
+ if (lowered.includes("<script")) {
241
+ return {
242
+ code: lowered.replace(/<script(\s[^>]*)?>/, (match) => `${match}
243
+ ${importLine}
244
+ `),
245
+ transformed: true
246
+ };
247
+ }
248
+ return {
249
+ code: `<script lang="ts">
250
+ ${importLine}
251
+ </script>
252
+ ${lowered}`,
253
+ transformed: true
254
+ };
255
+ };
256
+ var init_lowerAwaitSlotSyntax = __esm(() => {
257
+ init_constants();
258
+ 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;
259
+ });
260
+
261
+ // src/build/stylePreprocessor.ts
262
+ var exports_stylePreprocessor = {};
263
+ __export(exports_stylePreprocessor, {
264
+ stylePreprocessorPlugin: () => stylePreprocessorPlugin,
265
+ recordStyleOutput: () => recordStyleOutput,
266
+ isStylePath: () => isStylePath,
267
+ isStyleModulePath: () => isStyleModulePath,
268
+ isPreprocessableStylePath: () => isPreprocessableStylePath,
269
+ getStyleBaseName: () => getStyleBaseName,
270
+ getCssOutputExtension: () => getCssOutputExtension,
271
+ forgetStyleEntry: () => forgetStyleEntry,
272
+ findStyleEntriesImporting: () => findStyleEntriesImporting,
273
+ createSvelteStylePreprocessor: () => createSvelteStylePreprocessor,
274
+ createStyleTransformConfig: () => createStyleTransformConfig,
275
+ createStylePreprocessorPlugin: () => createStylePreprocessorPlugin,
276
+ compileStyleSource: () => compileStyleSource,
277
+ compileStyleFileIfNeededSync: () => compileStyleFileIfNeededSync,
278
+ compileStyleFileIfNeeded: () => compileStyleFileIfNeeded,
279
+ addStyleImporter: () => addStyleImporter
280
+ });
281
+ import { createHash } from "crypto";
282
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
283
+ import { readFile } from "fs/promises";
284
+ import { createRequire } from "module";
2
285
  import {
3
- handleSveltePageRequest
4
- } from "../chunk-0867j0r0.js";
5
- import"../chunk-gd6wmknh.js";
6
- import"../chunk-mtgf69xn.js";
7
- import"../chunk-v5vmsxmy.js";
8
- import"../chunk-c1jfjnka.js";
9
- import"../chunk-d9c0am65.js";
10
- import"../chunk-cbkrwmvh.js";
11
- import"../chunk-sd39p726.js";
12
- import"../chunk-gf0ygptk.js";
13
- import"../chunk-851whwc7.js";
14
- import"../chunk-p5504p14.js";
15
- import"../chunk-qxq2zcty.js";
16
- import"../chunk-s6defjk2.js";
17
- import"../chunk-9ve9jq72.js";
18
- import"../chunk-7fw6x3js.js";
19
- import"../chunk-mbazhahf.js";
20
- import"../chunk-xnt8c6h2.js";
21
- import"../chunk-qh75agse.js";
22
- import"../chunk-bmgqm774.js";
286
+ dirname,
287
+ extname,
288
+ isAbsolute,
289
+ join as join2,
290
+ relative,
291
+ resolve as resolve2
292
+ } from "path";
293
+ import { fileURLToPath } from "url";
294
+ 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) => {
295
+ const normalized = filePathOrLanguage.toLowerCase();
296
+ if (normalized === "scss" || normalized.endsWith(".scss"))
297
+ return "scss";
298
+ if (normalized === "sass" || normalized.endsWith(".sass"))
299
+ return "sass";
300
+ if (normalized === "less" || normalized.endsWith(".less"))
301
+ return "less";
302
+ if (normalized === "styl" || normalized === "stylus" || normalized.endsWith(".styl") || normalized.endsWith(".stylus"))
303
+ return "stylus";
304
+ return null;
305
+ }, missingDependencyError = (name, filePath) => new Error(`Unable to compile ${filePath}: install optional dependency "${name}" to use this stylesheet preprocessor.`), throwPreprocessorError = (error, filePath, language) => {
306
+ if (!(error instanceof Error)) {
307
+ throw new Error(`${language} compile failed in ${filePath}: ${String(error)}`);
308
+ }
309
+ const detail = error;
310
+ const sassLine = detail.span?.start?.line;
311
+ const sassCol = detail.span?.start?.column;
312
+ const line = detail.line ?? sassLine;
313
+ const column = detail.column ?? sassCol;
314
+ const location = typeof line === "number" ? `:${line}${typeof column === "number" ? `:${column}` : ""}` : "";
315
+ const message = detail.formatted ?? detail.message;
316
+ const wrapped = new Error(`${language} compile failed in ${filePath}${location}
317
+ ${message}`);
318
+ wrapped.cause = error;
319
+ throw wrapped;
320
+ }, requireOptionalPeerSync = (specifier) => {
321
+ try {
322
+ return requireFromCwd(specifier);
323
+ } catch {
324
+ return requireOptionalPeer(specifier);
325
+ }
326
+ }, normalizeLoadPaths = (filePath, paths = []) => [
327
+ dirname(filePath),
328
+ process.cwd(),
329
+ ...paths.map((path) => resolve2(process.cwd(), path))
330
+ ], tsconfigAliasCache, stripJsonComments = (source) => source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1"), normalizeAliasEntries = (aliases) => Object.entries(aliases ?? {}).map(([pattern, value]) => ({
331
+ pattern,
332
+ replacements: Array.isArray(value) ? value : [value]
333
+ })), readTsconfigAliases = () => {
334
+ const cwd = process.cwd();
335
+ if (tsconfigAliasCache?.cwd === cwd)
336
+ return tsconfigAliasCache;
337
+ const tsconfigPath = resolve2(cwd, "tsconfig.json");
338
+ const empty = { aliases: [], baseUrl: cwd, cwd };
339
+ if (!existsSync2(tsconfigPath)) {
340
+ tsconfigAliasCache = empty;
341
+ return empty;
342
+ }
343
+ try {
344
+ const parsed = JSON.parse(stripJsonComments(readFileSync2(tsconfigPath, "utf-8")));
345
+ const compilerOptions = parsed.compilerOptions ?? {};
346
+ const baseUrl = resolve2(cwd, compilerOptions.baseUrl ?? ".");
347
+ tsconfigAliasCache = {
348
+ aliases: normalizeAliasEntries(compilerOptions.paths),
349
+ baseUrl,
350
+ cwd
351
+ };
352
+ } catch {
353
+ tsconfigAliasCache = empty;
354
+ }
355
+ return tsconfigAliasCache;
356
+ }, getAliasEntries = (config) => {
357
+ const tsconfig = readTsconfigAliases();
358
+ return {
359
+ aliases: [
360
+ ...normalizeAliasEntries(config?.aliases),
361
+ ...tsconfig.aliases
362
+ ],
363
+ baseUrl: tsconfig.baseUrl
364
+ };
365
+ }, aliasPatternToRegExp = (pattern) => new RegExp(`^${pattern.split("*").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("(.+)")}$`), resolveAliasTargets = (specifier, config) => {
366
+ const { aliases, baseUrl } = getAliasEntries(config);
367
+ const targets = [];
368
+ for (const alias of aliases) {
369
+ const match = specifier.match(aliasPatternToRegExp(alias.pattern));
370
+ if (!match)
371
+ continue;
372
+ const wildcard = match[1] ?? "";
373
+ for (const replacement of alias.replacements) {
374
+ targets.push(resolve2(baseUrl, replacement.replace("*", wildcard)));
375
+ }
376
+ }
377
+ return targets;
378
+ }, getLanguageExtensions = (language) => {
379
+ if (language === "less")
380
+ return [".less", ".css"];
381
+ if (language === "stylus")
382
+ return [".styl", ".stylus", ".css"];
383
+ return [".scss", ".sass", ".css"];
384
+ }, getCandidatePaths = (basePath, language) => {
385
+ const ext = extname(basePath);
386
+ const paths = ext ? [basePath] : getLanguageExtensions(language).flatMap((extension) => [
387
+ `${basePath}${extension}`,
388
+ join2(basePath, `index${extension}`)
389
+ ]);
390
+ if (language === "scss" || language === "sass") {
391
+ return paths.flatMap((path) => {
392
+ const dir = dirname(path);
393
+ const base = path.slice(dir.length + 1);
394
+ return [path, join2(dir, `_${base}`)];
395
+ });
396
+ }
397
+ return paths;
398
+ }, resolveImportPath = (specifier, fromDirectory, loadPaths, language, config) => {
399
+ const rawCandidates = [
400
+ ...resolveAliasTargets(specifier, config),
401
+ isAbsolute(specifier) ? specifier : resolve2(fromDirectory, specifier),
402
+ ...loadPaths.map((path) => resolve2(path, specifier))
403
+ ];
404
+ for (const candidate of rawCandidates.flatMap((path) => getCandidatePaths(path, language))) {
405
+ if (existsSync2(candidate))
406
+ return candidate;
407
+ }
408
+ return null;
409
+ }, isExternalCssUrl = (url) => /^(?:[a-z][a-z0-9+.-]*:|\/\/|#|\/)/i.test(url), splitCssUrl = (url) => {
410
+ const markerIndex = url.search(/[?#]/);
411
+ if (markerIndex === -1)
412
+ return { marker: "", path: url };
413
+ return {
414
+ marker: url.slice(markerIndex),
415
+ path: url.slice(0, markerIndex)
416
+ };
417
+ }, rebaseCssUrls = (contents, sourceFile, entryFile) => {
418
+ const sourceDir = dirname(sourceFile);
419
+ const entryDir = dirname(entryFile);
420
+ if (sourceDir === entryDir)
421
+ return contents;
422
+ return contents.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/gi, (match, quote, rawUrl) => {
423
+ const trimmedUrl = rawUrl.trim();
424
+ if (!trimmedUrl || isExternalCssUrl(trimmedUrl))
425
+ return match;
426
+ const { marker, path } = splitCssUrl(trimmedUrl);
427
+ const rebased = relative(entryDir, resolve2(sourceDir, path)).replace(/\\/g, "/");
428
+ const normalized = rebased.startsWith(".") ? rebased : `./${rebased}`;
429
+ const nextQuote = quote || '"';
430
+ return `url(${nextQuote}${normalized}${marker}${nextQuote})`;
431
+ });
432
+ }, rewriteAliasedStyleImports = (contents, sourceFile, loadPaths, language, config) => contents.replace(/(@(?:use|forward|import|require)\s+)(["'])([^"']+)\2/g, (match, prefix, quote, specifier) => {
433
+ if (specifier.startsWith(".") || isAbsolute(specifier) || isExternalCssUrl(specifier))
434
+ return match;
435
+ const resolved = resolveImportPath(specifier, dirname(sourceFile), loadPaths, language, config);
436
+ return resolved ? `${prefix}${quote}${resolved}${quote}` : match;
437
+ }), preprocessLoadedStyle = (contents, sourceFile, entryFile, loadPaths = [], language, config) => {
438
+ const rebased = rebaseCssUrls(contents, sourceFile, entryFile);
439
+ return language ? rewriteAliasedStyleImports(rebased, sourceFile, loadPaths, language, config) : rebased;
440
+ }, extractCssModuleExports = (css) => {
441
+ const exports = {};
442
+ const nextCss = css.replace(/:export\s*\{([^}]*)\}/g, (_, body) => {
443
+ for (const declaration of body.split(";")) {
444
+ const separator = declaration.indexOf(":");
445
+ if (separator === -1)
446
+ continue;
447
+ const key = declaration.slice(0, separator).trim();
448
+ const value = declaration.slice(separator + 1).trim();
449
+ if (key && value)
450
+ exports[key] = value;
451
+ }
452
+ return "";
453
+ });
454
+ return { css: nextCss, exports };
455
+ }, getSassOptions = (config, language) => ({
456
+ ...config?.sass ?? {},
457
+ ...language === "scss" ? config?.scss ?? {} : {}
458
+ }), getLessOptions = (config) => config?.less ?? {}, getStylusOptions = (config) => config?.stylus ?? {}, createStyleTransformConfig = (stylePreprocessors, postcss) => postcss === undefined ? stylePreprocessors : { ...stylePreprocessors ?? {}, postcss }, withAdditionalData = (contents, additionalData) => additionalData ? `${additionalData}
459
+ ${contents}` : contents, normalizePostcssModule = (mod) => {
460
+ if (mod && typeof mod === "object" && "default" in mod) {
461
+ return mod.default ?? mod;
462
+ }
463
+ return mod;
464
+ }, loadPostcssConfigFile = async (configPath) => {
465
+ const resolved = resolve2(process.cwd(), configPath);
466
+ const loaded = resolved.endsWith(".cjs") || resolved.endsWith(".cts") ? requireOptionalPeerSync(resolved) : await importOptionalPeer(`${new URL(`file://${resolved}`).href}?t=${Date.now()}`);
467
+ const config = normalizePostcssModule(loaded);
468
+ const value = typeof config === "function" ? await config({
469
+ cwd: process.cwd(),
470
+ env: "development"
471
+ }) : config;
472
+ return normalizePostcssModule(value) ?? {};
473
+ }, normalizePostcssPlugins = (plugins) => {
474
+ if (!plugins)
475
+ return [];
476
+ if (Array.isArray(plugins))
477
+ return plugins.filter(Boolean);
478
+ const resolved = [];
479
+ for (const [specifier, options] of Object.entries(plugins)) {
480
+ if (options === false)
481
+ continue;
482
+ const mod = normalizePostcssModule(requireOptionalPeerSync(specifier));
483
+ const plugin = typeof mod === "function" ? mod(options === true ? undefined : options) : mod;
484
+ if (plugin)
485
+ resolved.push(plugin);
486
+ }
487
+ return resolved;
488
+ }, resolvePostcssConfig = async (config) => {
489
+ const inlineConfig = config?.postcss;
490
+ if (!inlineConfig)
491
+ return null;
492
+ const fileConfig = inlineConfig.config ? await loadPostcssConfigFile(inlineConfig.config) : {};
493
+ const plugins = [
494
+ ...normalizePostcssPlugins(fileConfig.plugins),
495
+ ...normalizePostcssPlugins(inlineConfig.plugins)
496
+ ];
497
+ if (plugins.length === 0)
498
+ return null;
499
+ return {
500
+ options: {
501
+ ...fileConfig.options ?? {},
502
+ ...inlineConfig.options ?? {}
503
+ },
504
+ plugins
505
+ };
506
+ }, runPostcss = async (css, filePath, config) => {
507
+ const postcssConfig = await resolvePostcssConfig(config);
508
+ if (!postcssConfig)
509
+ return css;
510
+ let postcssModule;
511
+ try {
512
+ postcssModule = await importOptionalPeer("postcss");
513
+ } catch {
514
+ throw missingDependencyError("postcss", filePath);
515
+ }
516
+ const postcss = postcssModule.default ?? postcssModule;
517
+ const result = await postcss(postcssConfig.plugins).process(css, {
518
+ from: filePath,
519
+ map: false,
520
+ ...postcssConfig.options
521
+ });
522
+ return result.css;
523
+ }, createSassImporter = (entryFile, loadPaths, language, config, deps) => ({
524
+ canonicalize(specifier, options) {
525
+ const fromDirectory = options.containingUrl ? dirname(fileURLToPath(options.containingUrl)) : dirname(entryFile);
526
+ const resolved = resolveImportPath(specifier, fromDirectory, loadPaths, language, config);
527
+ return resolved ? new URL(`file://${resolved}`) : null;
528
+ },
529
+ load(canonicalUrl) {
530
+ const filePath = fileURLToPath(canonicalUrl);
531
+ deps?.add(filePath);
532
+ const fileLanguage = getStyleLanguage(filePath);
533
+ if (fileLanguage !== "scss" && fileLanguage !== "sass" && fileLanguage !== null)
534
+ return null;
535
+ return {
536
+ contents: preprocessLoadedStyle(readFileSync2(filePath, "utf-8"), filePath, entryFile, loadPaths, language, config),
537
+ syntax: filePath.endsWith(".sass") ? "indented" : "scss"
538
+ };
539
+ }
540
+ }), createLessFileManager = (entryFile, loadPaths, config, deps) => ({
541
+ install(less, pluginManager) {
542
+ const baseManager = new less.FileManager;
543
+ const manager = Object.create(baseManager);
544
+ manager.supports = (filename, currentDirectory) => Boolean(resolveImportPath(filename, resolve2(currentDirectory), loadPaths, "less", config));
545
+ manager.loadFile = async (filename, currentDirectory) => {
546
+ const resolved = resolveImportPath(filename, resolve2(currentDirectory), loadPaths, "less", config);
547
+ if (!resolved) {
548
+ throw new Error(`Unable to resolve Less import "${filename}"`);
549
+ }
550
+ deps?.add(resolved);
551
+ return {
552
+ contents: preprocessLoadedStyle(await readFile(resolved, "utf-8"), resolved, entryFile, loadPaths, "less", config),
553
+ filename: resolved
554
+ };
555
+ };
556
+ pluginManager.addFileManager(manager);
557
+ }
558
+ }), renderStylus = async (contents, filePath, loadPaths, options, deps) => {
559
+ let stylus;
560
+ try {
561
+ const stylusModule = await importOptionalPeer("stylus");
562
+ stylus = stylusModule.default ?? stylusModule;
563
+ } catch {
564
+ throw missingDependencyError("stylus", filePath);
565
+ }
566
+ return new Promise((resolveCss, reject) => {
567
+ const renderer = stylus(contents);
568
+ renderer.set("filename", filePath);
569
+ for (const [key, value] of Object.entries(options.options ?? {})) {
570
+ renderer.set(key, value);
571
+ }
572
+ for (const path of loadPaths)
573
+ renderer.include(path);
574
+ renderer.render((error, css) => {
575
+ if (error) {
576
+ reject(error);
577
+ return;
578
+ }
579
+ if (deps) {
580
+ const stylusDeps = renderer.deps?.();
581
+ if (Array.isArray(stylusDeps)) {
582
+ for (const dep of stylusDeps)
583
+ deps.add(resolve2(dep));
584
+ }
585
+ }
586
+ resolveCss(css ?? "");
587
+ });
588
+ });
589
+ }, styleDependencyGraph, styleOutputHashes, recordStyleDeps = (entry, deps) => {
590
+ const key = resolve2(entry);
591
+ const stripped = new Set;
592
+ for (const dep of deps) {
593
+ const resolved = resolve2(dep);
594
+ if (resolved !== key)
595
+ stripped.add(resolved);
596
+ }
597
+ styleDependencyGraph.set(key, stripped);
598
+ }, addStyleImporter = (importerPath, stylePath) => {
599
+ const key = resolve2(importerPath);
600
+ const target = resolve2(stylePath);
601
+ const deps = styleDependencyGraph.get(key) ?? new Set;
602
+ deps.add(target);
603
+ styleDependencyGraph.set(key, deps);
604
+ }, findStyleEntriesImporting = (changedPath) => {
605
+ const target = resolve2(changedPath);
606
+ const importers = [];
607
+ for (const [entry, deps] of styleDependencyGraph) {
608
+ if (deps.has(target))
609
+ importers.push(entry);
610
+ }
611
+ return importers;
612
+ }, recordStyleOutput = (entry, css) => {
613
+ const key = resolve2(entry);
614
+ const hash = createHash("sha1").update(css).digest("hex");
615
+ const previous = styleOutputHashes.get(key);
616
+ styleOutputHashes.set(key, hash);
617
+ return previous !== hash;
618
+ }, forgetStyleEntry = (entry) => {
619
+ const key = resolve2(entry);
620
+ styleDependencyGraph.delete(key);
621
+ styleOutputHashes.delete(key);
622
+ }, compileStyleSource = async (filePath, source, languageHint, config) => {
623
+ const language = getStyleLanguage(languageHint ?? filePath);
624
+ const rawContents = source ?? await readFile(filePath, "utf-8");
625
+ const deps = new Set;
626
+ if (language === "scss" || language === "sass") {
627
+ const options = getSassOptions(config, language);
628
+ const packageName = options.implementation ?? "sass";
629
+ let sass;
630
+ try {
631
+ sass = await importOptionalPeer(packageName);
632
+ } catch {
633
+ throw missingDependencyError(packageName, filePath);
634
+ }
635
+ const contents = withAdditionalData(rawContents, options.additionalData);
636
+ const loadPaths = normalizeLoadPaths(filePath, options.loadPaths);
637
+ try {
638
+ const result = sass.compileString(contents, {
639
+ importers: [
640
+ createSassImporter(filePath, loadPaths, language, config, deps)
641
+ ],
642
+ loadPaths,
643
+ style: "expanded",
644
+ syntax: language === "sass" ? "indented" : "scss",
645
+ url: new URL(`file://${filePath}`)
646
+ });
647
+ const css = await runPostcss(result.css, filePath, config);
648
+ recordStyleDeps(filePath, deps);
649
+ return css;
650
+ } catch (error) {
651
+ throwPreprocessorError(error, filePath, language);
652
+ }
653
+ }
654
+ if (language === "less") {
655
+ const options = getLessOptions(config);
656
+ let lessModule;
657
+ try {
658
+ lessModule = await importOptionalPeer("less");
659
+ } catch {
660
+ throw missingDependencyError("less", filePath);
661
+ }
662
+ const less = lessModule.render ? lessModule : lessModule.default;
663
+ const render = less?.render;
664
+ if (!render)
665
+ throw missingDependencyError("less", filePath);
666
+ const contents = withAdditionalData(rawContents, options.additionalData);
667
+ const loadPaths = normalizeLoadPaths(filePath, options.paths);
668
+ try {
669
+ const result = await render(contents, {
670
+ ...options.options ?? {},
671
+ filename: filePath,
672
+ paths: loadPaths,
673
+ plugins: [
674
+ ...options.options?.plugins ?? [],
675
+ createLessFileManager(filePath, loadPaths, config, deps)
676
+ ]
677
+ });
678
+ const css = await runPostcss(result.css, filePath, config);
679
+ recordStyleDeps(filePath, deps);
680
+ return css;
681
+ } catch (error) {
682
+ throwPreprocessorError(error, filePath, "less");
683
+ }
684
+ }
685
+ if (language === "stylus") {
686
+ const options = getStylusOptions(config);
687
+ const loadPaths = normalizeLoadPaths(filePath, options.paths);
688
+ const contents = withAdditionalData(preprocessLoadedStyle(rawContents, filePath, filePath, loadPaths, "stylus", config), options.additionalData);
689
+ try {
690
+ const css = await runPostcss(await renderStylus(contents, filePath, loadPaths, options, deps), filePath, config);
691
+ recordStyleDeps(filePath, deps);
692
+ return css;
693
+ } catch (error) {
694
+ throwPreprocessorError(error, filePath, "stylus");
695
+ }
696
+ }
697
+ return runPostcss(rawContents, filePath, config);
698
+ }, createStylePreprocessorPlugin = (config) => ({
699
+ name: "absolute-style-preprocessor",
700
+ setup(build) {
701
+ const cssModuleSources = new Map;
702
+ build.onResolve({ filter: /^absolute-style-module:/ }, ({ path }) => ({
703
+ namespace: "absolute-style-module",
704
+ path: path.slice("absolute-style-module:".length)
705
+ }));
706
+ build.onLoad({ filter: /\.module\.css$/i, namespace: "absolute-style-module" }, async ({ path }) => {
707
+ const source = cssModuleSources.get(path);
708
+ if (!source) {
709
+ throw new Error(`Unable to resolve CSS module source for ${path}`);
710
+ }
711
+ return {
712
+ contents: source.css,
713
+ loader: "css"
714
+ };
715
+ });
716
+ build.onLoad({ filter: STYLE_EXTENSION_PATTERN }, async ({ path }) => {
717
+ if (isStyleModulePath(path)) {
718
+ const cssModulePath = path.replace(STYLE_EXTENSION_PATTERN, ".css");
719
+ const compiled = await compileStyleSource(path, undefined, undefined, config);
720
+ const { css, exports } = extractCssModuleExports(compiled);
721
+ cssModuleSources.set(cssModulePath, { css, exports });
722
+ 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}`)};`;
723
+ return {
724
+ contents: exportSource,
725
+ loader: "js"
726
+ };
727
+ }
728
+ return {
729
+ contents: await compileStyleSource(path, undefined, undefined, config),
730
+ loader: "css"
731
+ };
732
+ });
733
+ build.onLoad({ filter: CSS_EXTENSION_PATTERN }, async ({ path }) => ({
734
+ contents: await compileStyleSource(path, undefined, undefined, config),
735
+ loader: "css"
736
+ }));
737
+ }
738
+ }), stylePreprocessorPlugin, createSvelteStylePreprocessor = (config) => ({
739
+ style: async ({
740
+ attributes,
741
+ content,
742
+ filename
743
+ }) => {
744
+ const language = typeof attributes.lang === "string" ? attributes.lang : typeof attributes.type === "string" ? attributes.type.replace(/^text\//, "") : null;
745
+ if (!language || !STYLE_LANGUAGE_PATTERN.test(language))
746
+ return;
747
+ const path = filename ?? `style.${language}`;
748
+ return {
749
+ code: await compileStyleSource(path, content, language, config)
750
+ };
751
+ }
752
+ }), compileStyleFileIfNeeded = async (filePath, config) => {
753
+ if (!isPreprocessableStylePath(filePath)) {
754
+ return runPostcss(await readFile(filePath, "utf-8"), filePath, config);
755
+ }
756
+ return compileStyleSource(filePath, undefined, undefined, config);
757
+ }, compileStyleFileIfNeededSync = (filePath, config) => {
758
+ const rawContents = readFileSync2(filePath, "utf-8");
759
+ const language = getStyleLanguage(filePath);
760
+ if (config?.postcss) {
761
+ throw new Error(`Unable to compile ${filePath}: PostCSS preprocessing is async-only.`);
762
+ }
763
+ if (language === "scss" || language === "sass") {
764
+ const options = getSassOptions(config, language);
765
+ const packageName = options.implementation ?? "sass";
766
+ let sass;
767
+ try {
768
+ sass = requireOptionalPeerSync(packageName);
769
+ } catch {
770
+ throw missingDependencyError(packageName, filePath);
771
+ }
772
+ const contents = withAdditionalData(rawContents, options.additionalData);
773
+ const loadPaths = normalizeLoadPaths(filePath, options.loadPaths);
774
+ return sass.compileString(contents, {
775
+ importers: [
776
+ createSassImporter(filePath, loadPaths, language, config)
777
+ ],
778
+ loadPaths,
779
+ style: "expanded",
780
+ syntax: language === "sass" ? "indented" : "scss",
781
+ url: new URL(`file://${filePath}`)
782
+ }).css;
783
+ }
784
+ if (language === "less") {
785
+ 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.`);
786
+ }
787
+ if (language === "stylus") {
788
+ 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.`);
789
+ }
790
+ return rawContents;
791
+ }, getCssOutputExtension = (filePath) => isPreprocessableStylePath(filePath) ? ".css" : extname(filePath);
792
+ var init_stylePreprocessor = __esm(() => {
793
+ CSS_EXTENSION_PATTERN = /\.css$/i;
794
+ STYLE_EXTENSION_PATTERN = /\.(s[ac]ss|less|styl(?:us)?)$/i;
795
+ STYLE_MODULE_EXTENSION_PATTERN = /\.module\.(s[ac]ss|less|styl(?:us)?)$/i;
796
+ STYLE_LANGUAGE_PATTERN = /^(s[ac]ss|less|styl(?:us)?)$/i;
797
+ importOptionalPeer = new Function("specifier", "return import(specifier)");
798
+ requireOptionalPeer = new Function("specifier", "return require(specifier)");
799
+ requireFromCwd = createRequire(join2(process.cwd(), "package.json"));
800
+ styleDependencyGraph = new Map;
801
+ styleOutputHashes = new Map;
802
+ stylePreprocessorPlugin = createStylePreprocessorPlugin();
803
+ });
804
+
805
+ // src/core/svelteServerModule.ts
806
+ import { mkdir, readdir } from "fs/promises";
807
+ import { basename, dirname as dirname2, extname as extname2, join as join3, relative as relative2, resolve as resolve3 } from "path";
808
+ var serverCacheRoot, compiledModuleCache, originalSourcePathCache, transpiler, ensureRelativeImportPath = (from, target) => {
809
+ const importPath = relative2(dirname2(from), target).replace(/\\/g, "/");
810
+ return importPath.startsWith(".") ? importPath : `./${importPath}`;
811
+ }, processDirectoryEntries = (entries, dir, targetFileName, stack) => {
812
+ for (const entry of entries) {
813
+ const entryPath = join3(dir, entry.name);
814
+ if (entry.isDirectory())
815
+ stack.push(entryPath);
816
+ if (entry.isFile() && entry.name === targetFileName) {
817
+ return entryPath;
818
+ }
819
+ }
820
+ return null;
821
+ }, searchDirectoryLevel = async (dirs, targetFileName) => {
822
+ if (dirs.length === 0)
823
+ return null;
824
+ const nextStack = [];
825
+ const dirEntries = await Promise.all(dirs.map(async (dir) => ({
826
+ dir,
827
+ entries: await readdir(dir, {
828
+ encoding: "utf-8",
829
+ withFileTypes: true
830
+ })
831
+ })));
832
+ for (const { dir, entries } of dirEntries) {
833
+ const found = processDirectoryEntries(entries, dir, targetFileName, nextStack);
834
+ if (found)
835
+ return found;
836
+ }
837
+ return searchDirectoryLevel(nextStack, targetFileName);
838
+ }, findSourceFileByBasename = async (searchRoot, targetFileName) => searchDirectoryLevel([searchRoot], targetFileName), normalizeBuiltSvelteFileName = (sourcePath) => basename(sourcePath).replace(/-[a-z0-9]{6,}(?=\.svelte$)/i, ""), resolveOriginalSourcePath = async (sourcePath) => {
839
+ const cachedPath = originalSourcePathCache.get(sourcePath);
840
+ if (cachedPath !== undefined) {
841
+ return cachedPath;
842
+ }
843
+ if (!sourcePath.includes(`${join3(process.cwd(), "build")}${process.platform === "win32" ? "" : "/"}`) && !sourcePath.includes("/build/")) {
844
+ originalSourcePathCache.set(sourcePath, sourcePath);
845
+ return sourcePath;
846
+ }
847
+ const resolvedSourcePath = await findSourceFileByBasename(join3(process.cwd(), "src"), normalizeBuiltSvelteFileName(sourcePath));
848
+ const nextPath = resolvedSourcePath ?? sourcePath;
849
+ originalSourcePathCache.set(sourcePath, nextPath);
850
+ return nextPath;
851
+ }, resolveRelativeModule = async (spec, from) => {
852
+ if (!spec.startsWith(".")) {
853
+ return null;
854
+ }
855
+ const basePath = resolve3(dirname2(from), spec);
856
+ const candidates = [
857
+ basePath,
858
+ `${basePath}.ts`,
859
+ `${basePath}.js`,
860
+ `${basePath}.mjs`,
861
+ `${basePath}.cjs`,
862
+ `${basePath}.json`,
863
+ join3(basePath, "index.ts"),
864
+ join3(basePath, "index.js"),
865
+ join3(basePath, "index.mjs"),
866
+ join3(basePath, "index.cjs"),
867
+ join3(basePath, "index.json")
868
+ ];
869
+ const existResults = await Promise.all(candidates.map((candidate) => Bun.file(candidate).exists()));
870
+ const foundIndex = existResults.indexOf(true);
871
+ return foundIndex >= 0 ? candidates[foundIndex] ?? null : null;
872
+ }, getCachedModulePath = (sourcePath) => {
873
+ const relativeSourcePath = relative2(process.cwd(), sourcePath).replace(/\\/g, "/");
874
+ const normalizedSourcePath = relativeSourcePath.startsWith("..") ? sourcePath.replace(/[:\\/]/g, "_") : relativeSourcePath;
875
+ return join3(serverCacheRoot, `${normalizedSourcePath}.server.js`);
876
+ }, resolveSvelteImport = async (spec, from) => {
877
+ if (!spec.startsWith(".") && !spec.startsWith("/")) {
878
+ const resolved = resolvePackageImport(spec);
879
+ return resolved && resolved.endsWith(".svelte") ? resolved : null;
880
+ }
881
+ if (spec.startsWith("/")) {
882
+ return spec;
883
+ }
884
+ if (!spec.startsWith(".")) {
885
+ return null;
886
+ }
887
+ const explicitPath = resolve3(dirname2(from), spec);
888
+ if (extname2(explicitPath) === ".svelte") {
889
+ return explicitPath;
890
+ }
891
+ const candidate = `${explicitPath}.svelte`;
892
+ if (await Bun.file(candidate).exists() === true) {
893
+ return candidate;
894
+ }
895
+ return null;
896
+ }, writeIfChanged = async (path, content) => {
897
+ const targetFile = Bun.file(path);
898
+ const exists = await targetFile.exists();
899
+ if (exists) {
900
+ const currentContent = await targetFile.text();
901
+ if (currentContent === content) {
902
+ return;
903
+ }
904
+ }
905
+ await Bun.write(path, content);
906
+ }, compileSvelteServerModule = async (sourcePath) => {
907
+ const cachedModulePath = compiledModuleCache.get(sourcePath);
908
+ if (cachedModulePath) {
909
+ return cachedModulePath;
910
+ }
911
+ const resolutionSourcePath = await resolveOriginalSourcePath(sourcePath);
912
+ const source = await Bun.file(sourcePath).text();
913
+ const { compile, preprocess } = await import("svelte/compiler");
914
+ const loweredAwaitSource = lowerSvelteAwaitSlotSyntax(source);
915
+ const loweredSource = lowerSvelteIslandSyntax(loweredAwaitSource.code, "server");
916
+ const preprocessed = await preprocess(loweredSource.code, createSvelteStylePreprocessor());
917
+ let transpiled = sourcePath.endsWith(".ts") || sourcePath.endsWith(".svelte.ts") ? transpiler.transformSync(preprocessed.code) : preprocessed.code;
918
+ const childImportSpecs = Array.from(transpiled.matchAll(/from\s+['"]([^'"]+)['"]/g)).map((match) => match[1]).filter((value) => value !== undefined);
919
+ const resolvedChildModules = await Promise.all(childImportSpecs.map((spec) => resolveSvelteImport(spec, resolutionSourcePath)));
920
+ const resolvedModuleImports = await Promise.all(childImportSpecs.map((spec) => resolveRelativeModule(spec, resolutionSourcePath)));
921
+ const childModulePaths = new Map;
922
+ const rewrittenModulePaths = new Map;
923
+ const compiledChildren = await Promise.all(childImportSpecs.map(async (spec, index) => {
924
+ const resolvedChild = resolvedChildModules[index];
925
+ if (!spec || !resolvedChild)
926
+ return null;
927
+ return {
928
+ compiledPath: await compileSvelteServerModule(resolvedChild),
929
+ resolvedChild,
930
+ spec
931
+ };
932
+ }));
933
+ for (const result of compiledChildren) {
934
+ if (!result)
935
+ continue;
936
+ childModulePaths.set(result.spec, result.compiledPath);
937
+ childModulePaths.set(result.resolvedChild, result.compiledPath);
938
+ }
939
+ for (let index = 0;index < childImportSpecs.length; index += 1) {
940
+ const spec = childImportSpecs[index];
941
+ const resolvedModuleImport = resolvedModuleImports[index];
942
+ if (!spec || !resolvedModuleImport)
943
+ continue;
944
+ if (resolvedChildModules[index])
945
+ continue;
946
+ rewrittenModulePaths.set(spec, ensureRelativeImportPath(getCachedModulePath(sourcePath), resolvedModuleImport));
947
+ }
948
+ for (const [spec, resolvedModuleImport] of rewrittenModulePaths) {
949
+ transpiled = transpiled.replaceAll(spec, resolvedModuleImport);
950
+ }
951
+ let compiledCode = compile(transpiled, {
952
+ css: "injected",
953
+ experimental: {
954
+ async: loweredAwaitSource.transformed || loweredSource.transformed
955
+ },
956
+ filename: resolutionSourcePath,
957
+ generate: "server"
958
+ }).js.code;
959
+ for (const [spec, compiledChildPath] of childModulePaths) {
960
+ compiledCode = compiledCode.replaceAll(spec, ensureRelativeImportPath(getCachedModulePath(sourcePath), compiledChildPath));
961
+ }
962
+ for (const [spec, resolvedModuleImport] of rewrittenModulePaths) {
963
+ compiledCode = compiledCode.replaceAll(spec, resolvedModuleImport);
964
+ }
965
+ const compiledModulePath = getCachedModulePath(sourcePath);
966
+ await mkdir(dirname2(compiledModulePath), { recursive: true });
967
+ await writeIfChanged(compiledModulePath, compiledCode);
968
+ compiledModuleCache.set(sourcePath, compiledModulePath);
969
+ return compiledModulePath;
970
+ };
971
+ var init_svelteServerModule = __esm(() => {
972
+ init_resolvePackageImport();
973
+ init_lowerIslandSyntax();
974
+ init_lowerAwaitSlotSyntax();
975
+ init_stylePreprocessor();
976
+ serverCacheRoot = join3(process.cwd(), ".absolutejs", "islands", "svelte");
977
+ compiledModuleCache = new Map;
978
+ originalSourcePathCache = new Map;
979
+ transpiler = new Bun.Transpiler({
980
+ loader: "ts",
981
+ target: "browser"
982
+ });
983
+ });
984
+
985
+ // src/core/devRouteRegistrationCallsite.ts
986
+ var exports_devRouteRegistrationCallsite = {};
987
+ __export(exports_devRouteRegistrationCallsite, {
988
+ patchElysiaRouteRegistrationCallsites: () => patchElysiaRouteRegistrationCallsites,
989
+ getCurrentRouteRegistrationCallsite: () => getCurrentRouteRegistrationCallsite
990
+ });
991
+ import { AsyncLocalStorage } from "async_hooks";
992
+ import { Elysia } from "elysia";
993
+ var ROUTE_CALLSITE_STORAGE_KEY, ROUTE_CALLSITE_PATCHED_KEY, ROUTE_METHOD_NAMES, isObjectRecord3 = (value) => Boolean(value) && typeof value === "object", isAsyncLocalStorage2 = (value) => isObjectRecord3(value) && ("getStore" in value) && typeof value.getStore === "function" && ("run" in value) && typeof value.run === "function", isRouteMethod = (value) => typeof value === "function", getRouteCallsiteStorage = () => {
994
+ const value = Reflect.get(globalThis, ROUTE_CALLSITE_STORAGE_KEY);
995
+ if (value === null || typeof value === "undefined") {
996
+ return;
997
+ }
998
+ return isAsyncLocalStorage2(value) ? value : undefined;
999
+ }, ensureRouteCallsiteStorage = () => {
1000
+ const existing = getRouteCallsiteStorage();
1001
+ if (existing) {
1002
+ return existing;
1003
+ }
1004
+ const storage = new AsyncLocalStorage;
1005
+ Reflect.set(globalThis, ROUTE_CALLSITE_STORAGE_KEY, storage);
1006
+ return storage;
1007
+ }, 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) => {
1008
+ const location = stack.split(`
1009
+ `).slice(1).map((line) => line.trim()).filter((frame) => !shouldIgnoreRouteCallsiteFrame(frame)).map((frame) => getRouteCallsiteLocation(frame)).find((frameLocation) => frameLocation !== undefined);
1010
+ return location ? normalizeCallsitePath(location) : undefined;
1011
+ }, captureRouteRegistrationCallsite = () => {
1012
+ const { stack } = new Error;
1013
+ if (!stack) {
1014
+ return;
1015
+ }
1016
+ return extractRouteRegistrationCallsite(stack);
1017
+ }, wrapRouteHandlerWithCallsite = (handler, callsite) => {
1018
+ if (typeof handler !== "function" || !callsite) {
1019
+ return handler;
1020
+ }
1021
+ const storage = ensureRouteCallsiteStorage();
1022
+ const routeHandler = handler;
1023
+ return function wrappedRouteHandler(...args) {
1024
+ return storage.run({ callsite }, () => Reflect.apply(routeHandler, this, args));
1025
+ };
1026
+ }, createPatchedRouteMethod = (originalMethod) => function patchedRouteMethod(path, handler, ...rest) {
1027
+ const callsite = captureRouteRegistrationCallsite();
1028
+ return Reflect.apply(originalMethod, this, [
1029
+ path,
1030
+ wrapRouteHandlerWithCallsite(handler, callsite),
1031
+ ...rest
1032
+ ]);
1033
+ }, getCurrentRouteRegistrationCallsite = () => getRouteCallsiteStorage()?.getStore()?.callsite, patchElysiaRouteRegistrationCallsites = () => {
1034
+ if (false) {}
1035
+ if (Reflect.get(globalThis, ROUTE_CALLSITE_PATCHED_KEY) === true) {
1036
+ return;
1037
+ }
1038
+ const { prototype } = Elysia;
1039
+ ROUTE_METHOD_NAMES.forEach((methodName) => {
1040
+ const originalMethod = Reflect.get(prototype, methodName);
1041
+ if (!isRouteMethod(originalMethod))
1042
+ return;
1043
+ Reflect.set(prototype, methodName, createPatchedRouteMethod(originalMethod));
1044
+ });
1045
+ Reflect.set(globalThis, ROUTE_CALLSITE_PATCHED_KEY, true);
1046
+ };
1047
+ var init_devRouteRegistrationCallsite = __esm(() => {
1048
+ ROUTE_CALLSITE_STORAGE_KEY = Symbol.for("absolutejs.devRouteRegistrationCallsiteStorage");
1049
+ ROUTE_CALLSITE_PATCHED_KEY = Symbol.for("absolutejs.devRouteRegistrationCallsitePatched");
1050
+ ROUTE_METHOD_NAMES = [
1051
+ "all",
1052
+ "delete",
1053
+ "get",
1054
+ "head",
1055
+ "options",
1056
+ "patch",
1057
+ "post",
1058
+ "put"
1059
+ ];
1060
+ });
1061
+
1062
+ // src/client/streamSwap.ts
1063
+ var streamSwapRuntime = () => {
1064
+ const absoluteWindow = window;
1065
+ const SLOT_PATCH_EVENT = "absolutejs:slot-patch";
1066
+ if (absoluteWindow.__ABS_SLOT_RUNTIME__ === true)
1067
+ return;
1068
+ absoluteWindow.__ABS_SLOT_RUNTIME__ = true;
1069
+ absoluteWindow.__ABS_SLOT_CONSUMERS__ = absoluteWindow.__ABS_SLOT_CONSUMERS__ ?? {};
1070
+ absoluteWindow.__ABS_SLOT_PENDING__ = absoluteWindow.__ABS_SLOT_PENDING__ ?? {};
1071
+ const consumers = absoluteWindow.__ABS_SLOT_CONSUMERS__;
1072
+ const pending = absoluteWindow.__ABS_SLOT_PENDING__;
1073
+ const isObjectRecord4 = (value) => Boolean(value) && typeof value === "object";
1074
+ const isPatchedPendingEntry = (value) => {
1075
+ if (!isObjectRecord4(value))
1076
+ return false;
1077
+ return value.domPatched === true && "payload" in value;
1078
+ };
1079
+ const unwrapPendingPayload = (value) => isPatchedPendingEntry(value) ? value.payload : value;
1080
+ const canApplyImmediately = () => absoluteWindow.__ABS_SLOT_HYDRATION_PENDING__ !== true;
1081
+ const isAngularDeferPayload = (payload) => {
1082
+ if (!isObjectRecord4(payload))
1083
+ return false;
1084
+ return payload.kind === "angular-defer";
1085
+ };
1086
+ const isVueSuspensePayload = (payload) => {
1087
+ if (!isObjectRecord4(payload))
1088
+ return false;
1089
+ return payload.kind === "vue-suspense";
1090
+ };
1091
+ const resolveHtml = (payload) => {
1092
+ if (!isObjectRecord4(payload)) {
1093
+ return typeof payload === "string" ? payload : "";
1094
+ }
1095
+ if (typeof payload.html === "string") {
1096
+ return payload.html;
1097
+ }
1098
+ return "";
1099
+ };
1100
+ const apply = (id, pendingEntry) => {
1101
+ const payload = unwrapPendingPayload(pendingEntry);
1102
+ if (!canApplyImmediately()) {
1103
+ pending[id] = payload;
1104
+ return;
1105
+ }
1106
+ const consumer = consumers[id];
1107
+ if (typeof consumer !== "function") {
1108
+ applyToDom(id, payload, pendingEntry);
1109
+ return;
1110
+ }
1111
+ const handled = consumer(payload);
1112
+ if (handled !== false) {
1113
+ delete pending[id];
1114
+ return;
1115
+ }
1116
+ applyToDom(id, payload, pendingEntry);
1117
+ };
1118
+ const applyToDom = (id, payload, pendingEntry) => {
1119
+ if (isAngularDeferPayload(payload)) {
1120
+ pending[id] = payload;
1121
+ return;
1122
+ }
1123
+ const node = document.getElementById(id);
1124
+ if (!node) {
1125
+ pending[id] = payload;
1126
+ return;
1127
+ }
1128
+ const html = resolveHtml(payload);
1129
+ if (isVueSuspensePayload(payload) && isPatchedPendingEntry(pendingEntry)) {
1130
+ return;
1131
+ }
1132
+ node.innerHTML = html;
1133
+ node.setAttribute("data-absolute-slot-state", "resolved");
1134
+ window.dispatchEvent(new CustomEvent(SLOT_PATCH_EVENT, {
1135
+ detail: { html, id, payload }
1136
+ }));
1137
+ if (isVueSuspensePayload(payload)) {
1138
+ pending[id] = { domPatched: true, payload };
1139
+ return;
1140
+ }
1141
+ delete pending[id];
1142
+ };
1143
+ const flush = () => {
1144
+ for (const id in pending) {
1145
+ if (!Object.prototype.hasOwnProperty.call(pending, id))
1146
+ continue;
1147
+ apply(id, pending[id] ?? "");
1148
+ }
1149
+ };
1150
+ absoluteWindow.__ABS_SLOT_FLUSH__ = flush;
1151
+ absoluteWindow.__ABS_SLOT_ENQUEUE__ = (id, payload) => {
1152
+ apply(id, payload);
1153
+ };
1154
+ if (typeof MutationObserver === "function") {
1155
+ const observer = new MutationObserver(flush);
1156
+ const root = document.documentElement ?? document.body ?? document;
1157
+ observer.observe(root, { childList: true, subtree: true });
1158
+ }
1159
+ if (document.readyState === "loading") {
1160
+ document.addEventListener("DOMContentLoaded", flush, { once: true });
1161
+ }
1162
+ flush();
1163
+ }, stripFunctionWrapper = (value) => {
1164
+ const start = value.indexOf("{");
1165
+ const end = value.lastIndexOf("}");
1166
+ if (start < 0 || end <= start)
1167
+ return "";
1168
+ return value.slice(start + 1, end);
1169
+ }, getStreamSwapRuntimeScript = () => `(function(){${stripFunctionWrapper(streamSwapRuntime.toString())}})();`;
1170
+
1171
+ // src/utils/escapeScriptContent.ts
1172
+ var ESCAPE_LOOKUP, ESCAPE_REGEX, escapeScriptContent = (content) => content.replace(ESCAPE_REGEX, (char) => {
1173
+ const escaped = ESCAPE_LOOKUP[char];
1174
+ return escaped !== undefined ? escaped : char;
1175
+ });
1176
+ var init_escapeScriptContent = __esm(() => {
1177
+ ESCAPE_LOOKUP = {
1178
+ "\u2028": "\\u2028",
1179
+ "\u2029": "\\u2029",
1180
+ "<": "\\u003C"
1181
+ };
1182
+ ESCAPE_REGEX = /[<\u2028\u2029]/g;
1183
+ });
1184
+
1185
+ // src/utils/streamingSlots.ts
1186
+ 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) => {
1187
+ const closingBodyIndex = html.indexOf(CLOSING_BODY_TAG);
1188
+ if (closingBodyIndex >= 0) {
1189
+ return `${html.slice(0, closingBodyIndex)}${injection}${html.slice(closingBodyIndex)}`;
1190
+ }
1191
+ return `${html}${injection}`;
1192
+ }, injectHtmlIntoHead = (html, injection) => {
1193
+ const closingHeadIndex = html.indexOf(CLOSING_HEAD_TAG2);
1194
+ if (closingHeadIndex >= 0) {
1195
+ return `${html.slice(0, closingHeadIndex)}${injection}${html.slice(closingHeadIndex)}`;
1196
+ }
1197
+ return `${html}${injection}`;
1198
+ }, 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) => {
1199
+ const runtimeBody = [
1200
+ runtimePreludeScript?.trim() ? runtimePreludeScript.trim() : "",
1201
+ getStreamingSlotsRuntimeScript()
1202
+ ].filter(Boolean).join(";");
1203
+ return `<script${createNonceAttr(nonce)}>${escapeScriptContent(runtimeBody)}</script>`;
1204
+ }, toUint8 = (value, encoder) => encoder.encode(value), isRecord = (value) => Boolean(value) && typeof value === "object", isSafeHtmlLike = (value) => isRecord(value) && typeof value.changingThisBreaksApplicationSecurity === "string", normalizeSafeHtml = (value) => {
1205
+ if (isSafeHtmlLike(value)) {
1206
+ return value.changingThisBreaksApplicationSecurity;
1207
+ }
1208
+ return value;
1209
+ }, currentStreamingSlotPolicy, clonePolicy = (policy) => ({
1210
+ ...policy
1211
+ }), normalizeSlotBytes = (value, fallback) => {
1212
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
1213
+ return Math.floor(value);
1214
+ }
1215
+ return fallback;
1216
+ }, normalizeSlotText = (value, fallback) => {
1217
+ const normalizedValue = normalizeSafeHtml(value);
1218
+ return typeof normalizedValue === "string" ? normalizedValue : fallback;
1219
+ }, normalizeSlotError = (value, fallback = undefined) => {
1220
+ const safeValue = normalizeSafeHtml(value);
1221
+ if (typeof safeValue === "string")
1222
+ return safeValue;
1223
+ return fallback;
1224
+ }, hasPolicyValue = (policy, key) => Object.prototype.hasOwnProperty.call(policy, key), applyStreamingSlotPolicyOverrides = (base, overridePolicy = {}) => ({
1225
+ errorHtml: hasPolicyValue(overridePolicy, "errorHtml") ? normalizeSlotError(overridePolicy.errorHtml) : base.errorHtml,
1226
+ fallbackHtml: hasPolicyValue(overridePolicy, "fallbackHtml") ? normalizeSlotText(overridePolicy.fallbackHtml, "") : base.fallbackHtml,
1227
+ maxSlotHtmlSizeBytes: hasPolicyValue(overridePolicy, "maxSlotHtmlSizeBytes") ? normalizeSlotBytes(overridePolicy.maxSlotHtmlSizeBytes, base.maxSlotHtmlSizeBytes) : base.maxSlotHtmlSizeBytes,
1228
+ maxSlotsPerResponse: hasPolicyValue(overridePolicy, "maxSlotsPerResponse") ? normalizeSlotBytes(overridePolicy.maxSlotsPerResponse, base.maxSlotsPerResponse) : base.maxSlotsPerResponse,
1229
+ onError: hasPolicyValue(overridePolicy, "onError") ? overridePolicy.onError : base.onError,
1230
+ onSlotMetric: hasPolicyValue(overridePolicy, "onSlotMetric") ? overridePolicy.onSlotMetric : base.onSlotMetric,
1231
+ timeoutMs: hasPolicyValue(overridePolicy, "timeoutMs") ? normalizeSlotBytes(overridePolicy.timeoutMs, base.timeoutMs) : base.timeoutMs
1232
+ }), createCombinedSlotErrorHandler = (policyOnError, enhancerOnError) => {
1233
+ if (!policyOnError && !enhancerOnError)
1234
+ return;
1235
+ return (error, slot) => {
1236
+ policyOnError?.(error, slot);
1237
+ enhancerOnError?.(error, slot);
1238
+ };
1239
+ }, createCombinedSlotMetricHandler = (policyOnSlotMetric, callOnSlotMetric) => {
1240
+ if (!policyOnSlotMetric && !callOnSlotMetric)
1241
+ return;
1242
+ return (metric) => {
1243
+ policyOnSlotMetric?.(metric);
1244
+ callOnSlotMetric?.(metric);
1245
+ };
1246
+ }, resolveStreamingSlotPolicy = (overridePolicy = {}) => {
1247
+ const base = getStreamingSlotPolicy();
1248
+ return applyStreamingSlotPolicyOverrides(base, overridePolicy);
1249
+ }, getStreamingSlotPolicy = () => clonePolicy(currentStreamingSlotPolicy), setStreamingSlotPolicy = (policy = {}) => {
1250
+ const base = getStreamingSlotPolicy();
1251
+ currentStreamingSlotPolicy = applyStreamingSlotPolicyOverrides(base, policy);
1252
+ }, withStreamingSlotPolicy = async (policy, callback) => {
1253
+ const previous = getStreamingSlotPolicy();
1254
+ setStreamingSlotPolicy(policy);
1255
+ try {
1256
+ return await callback();
1257
+ } finally {
1258
+ currentStreamingSlotPolicy = previous;
1259
+ }
1260
+ }, emitSlotMetric = (metric, onSlotMetric) => {
1261
+ onSlotMetric?.(metric);
1262
+ }, createTimeoutError = (slot, timeoutMs) => {
1263
+ const error = Object.assign(new Error(`Streaming slot "${slot.id}" timed out after ${timeoutMs}ms`), { __absTimeout: true });
1264
+ return error;
1265
+ }, isSlotPatchPayloadObject = (value) => isRecord(value) && ("html" in value), isTimeoutError = (error) => isRecord(error) && error.__absTimeout === true, toStreamingSlot = (slot, policy) => ({
1266
+ errorHtml: slot.errorHtml === undefined ? policy.errorHtml : slot.errorHtml,
1267
+ fallbackHtml: normalizeSlotText(slot.fallbackHtml, policy.fallbackHtml),
1268
+ id: slot.id ?? createStreamingSlotId(),
1269
+ resolve: slot.resolve,
1270
+ timeoutMs: normalizeSlotBytes(slot.timeoutMs, policy.timeoutMs)
1271
+ }), prepareSlots = ({
1272
+ policy,
1273
+ slots,
1274
+ onError,
1275
+ onSlotMetric
1276
+ }) => {
1277
+ const preparedSlots = slots.map((slot) => toStreamingSlot(slot, policy));
1278
+ const emitPreparedSlotMetric = (slot) => {
1279
+ emitSlotMetric({
1280
+ slotId: slot.id,
1281
+ type: "prepared"
1282
+ }, onSlotMetric);
1283
+ };
1284
+ const dropPreparedSlot = (slot, reason) => {
1285
+ onError?.(new Error(reason), slot);
1286
+ emitSlotMetric({
1287
+ reason,
1288
+ slotId: slot.id,
1289
+ type: "dropped"
1290
+ }, onSlotMetric);
1291
+ };
1292
+ const { maxSlotsPerResponse } = policy;
1293
+ if (maxSlotsPerResponse === 0) {
1294
+ preparedSlots.forEach((slot) => dropPreparedSlot(slot, "maxSlotsPerResponse is 0"));
1295
+ return [];
1296
+ }
1297
+ if (preparedSlots.length <= maxSlotsPerResponse) {
1298
+ preparedSlots.forEach(emitPreparedSlotMetric);
1299
+ return preparedSlots;
1300
+ }
1301
+ const keptSlots = preparedSlots.slice(0, maxSlotsPerResponse);
1302
+ const droppedSlots = preparedSlots.slice(maxSlotsPerResponse);
1303
+ droppedSlots.forEach((slot) => {
1304
+ dropPreparedSlot(slot, `Streaming slot "${slot.id}" dropped because ${maxSlotsPerResponse} slots is the configured maximum`);
1305
+ });
1306
+ keptSlots.forEach(emitPreparedSlotMetric);
1307
+ return keptSlots;
1308
+ }, htmlByteLength = (value, encoder) => encoder.encode(value).length, normalizeSlotPatchPayload = (value) => {
1309
+ const safeValue = normalizeSafeHtml(value);
1310
+ if (isSlotPatchPayloadObject(safeValue) && typeof safeValue.html === "string") {
1311
+ return {
1312
+ ...safeValue,
1313
+ html: normalizeSlotText(safeValue.html, "")
1314
+ };
1315
+ }
1316
+ return typeof safeValue === "string" ? safeValue : `${safeValue}`;
1317
+ }, getPayloadHtml = (payload) => typeof payload === "string" ? payload : payload.html, enqueueEncodedText = (controller, encoder, value) => {
1318
+ if (value.length === 0) {
1319
+ return;
1320
+ }
1321
+ controller.enqueue(encoder.encode(value));
1322
+ }, readStreamingRuntimeChunk = async (reader) => {
1323
+ const { done, value } = await reader.read();
1324
+ if (done || !value) {
1325
+ return { done, value: undefined };
1326
+ }
1327
+ return { done, value };
1328
+ }, applyBaseWinnerState = (state, winner, handleResolved) => {
1329
+ if (!state.handled && winner.kind === "slot") {
1330
+ handleResolved(winner);
1331
+ }
1332
+ return state;
1333
+ }, resolveOversizedSlotPayload = (input) => {
1334
+ const {
1335
+ encoder,
1336
+ html,
1337
+ maxSlotHtmlSizeBytes,
1338
+ onError,
1339
+ onSlotMetric,
1340
+ slot,
1341
+ start
1342
+ } = input;
1343
+ const bytes = htmlByteLength(html, encoder);
1344
+ if (bytes <= maxSlotHtmlSizeBytes) {
1345
+ return null;
1346
+ }
1347
+ const error = new Error(`Streaming slot "${slot.id}" exceeded max payload size of ${maxSlotHtmlSizeBytes} bytes`);
1348
+ const durationMs = Date.now() - start;
1349
+ onError?.(error, slot);
1350
+ emitSlotMetric({
1351
+ bytes,
1352
+ durationMs,
1353
+ error,
1354
+ slotId: slot.id,
1355
+ type: "size_exceeded"
1356
+ }, onSlotMetric);
1357
+ const fallbackHtml = normalizeSlotError(slot.errorHtml, undefined);
1358
+ return {
1359
+ bytes: fallbackHtml === undefined ? 0 : htmlByteLength(fallbackHtml, encoder),
1360
+ durationMs,
1361
+ id: slot.id,
1362
+ payload: fallbackHtml === undefined ? null : fallbackHtml
1363
+ };
1364
+ }, raceWithTimeout = (promise, slot) => {
1365
+ const { timeoutMs } = slot;
1366
+ if (typeof timeoutMs !== "number" || timeoutMs <= 0) {
1367
+ return promise;
1368
+ }
1369
+ const { promise: timeoutPromise, reject } = Promise.withResolvers();
1370
+ setTimeout(() => {
1371
+ reject(createTimeoutError(slot, timeoutMs));
1372
+ }, timeoutMs);
1373
+ return Promise.race([promise, timeoutPromise]);
1374
+ }, resolveSlot = async (slot, onError, policy, onSlotMetric) => {
1375
+ const safePolicy = policy ?? getStreamingSlotPolicy();
1376
+ const encoder = new TextEncoder;
1377
+ const start = Date.now();
1378
+ try {
1379
+ const maybeAsyncValue = Promise.resolve(slot.resolve());
1380
+ const resolved = await raceWithTimeout(maybeAsyncValue, slot);
1381
+ const payload = normalizeSlotPatchPayload(resolved);
1382
+ const html = getPayloadHtml(payload);
1383
+ const oversizedResult = safePolicy.maxSlotHtmlSizeBytes > 0 ? resolveOversizedSlotPayload({
1384
+ encoder,
1385
+ html,
1386
+ maxSlotHtmlSizeBytes: safePolicy.maxSlotHtmlSizeBytes,
1387
+ onError,
1388
+ onSlotMetric,
1389
+ slot,
1390
+ start
1391
+ }) : null;
1392
+ if (oversizedResult) {
1393
+ return oversizedResult;
1394
+ }
1395
+ const durationMs = Date.now() - start;
1396
+ const bytes = htmlByteLength(html, encoder);
1397
+ emitSlotMetric({
1398
+ bytes,
1399
+ durationMs,
1400
+ slotId: slot.id,
1401
+ type: "resolved"
1402
+ }, onSlotMetric);
1403
+ return {
1404
+ bytes,
1405
+ durationMs,
1406
+ id: slot.id,
1407
+ payload
1408
+ };
1409
+ } catch (error) {
1410
+ const durationMs = Date.now() - start;
1411
+ onError?.(error, slot);
1412
+ emitSlotMetric({
1413
+ durationMs,
1414
+ error,
1415
+ slotId: slot.id,
1416
+ type: isTimeoutError(error) ? "timeout" : "error"
1417
+ }, onSlotMetric);
1418
+ const html = normalizeSlotError(slot.errorHtml, undefined);
1419
+ if (html) {
1420
+ return {
1421
+ bytes: htmlByteLength(html, encoder),
1422
+ durationMs,
1423
+ id: slot.id,
1424
+ payload: html
1425
+ };
1426
+ }
1427
+ return {
1428
+ bytes: 0,
1429
+ durationMs,
1430
+ id: slot.id,
1431
+ payload: null
1432
+ };
1433
+ }
1434
+ }, nextResolvedSlot = async (pending) => {
1435
+ const wrapped = pending.map((promise) => promise.then((result) => ({
1436
+ original: promise,
1437
+ result
1438
+ })));
1439
+ return Promise.race(wrapped);
1440
+ }, streamChunkToString2 = (value, decoder) => typeof value === "string" ? value : decoder.decode(value, { stream: true }), appendStreamingSlotPatchesToStream = (stream, slots = [], {
1441
+ injectRuntime = true,
1442
+ nonce,
1443
+ onError,
1444
+ onSlotMetric,
1445
+ policy,
1446
+ runtimePreludeScript,
1447
+ runtimePlacement = "head"
1448
+ } = {}) => {
1449
+ const resolvedPolicy = resolveStreamingSlotPolicy(policy);
1450
+ const combinedOnError = createCombinedSlotErrorHandler(resolvedPolicy.onError, onError);
1451
+ const combinedOnSlotMetric = createCombinedSlotMetricHandler(resolvedPolicy.onSlotMetric, onSlotMetric);
1452
+ const effectivePolicy = {
1453
+ ...resolvedPolicy,
1454
+ onSlotMetric: combinedOnSlotMetric
1455
+ };
1456
+ const preparedSlots = prepareSlots({
1457
+ onError: combinedOnError,
1458
+ onSlotMetric: combinedOnSlotMetric,
1459
+ policy: effectivePolicy,
1460
+ slots
1461
+ });
1462
+ if (preparedSlots.length === 0)
1463
+ return stream;
1464
+ const source = injectRuntime ? injectStreamingRuntimeIntoStream(stream, nonce, runtimePlacement, runtimePreludeScript) : stream;
1465
+ const encoder = new TextEncoder;
1466
+ const decoder = new TextDecoder;
1467
+ const reader = source.getReader();
1468
+ const pending = preparedSlots.map((slot) => resolveSlot(slot, combinedOnError, effectivePolicy, combinedOnSlotMetric));
1469
+ const createRaceCandidates = (baseDone, baseRead) => {
1470
+ const racers = [];
1471
+ if (!baseDone) {
1472
+ racers.push(baseRead.then(({ done, value }) => ({
1473
+ done,
1474
+ kind: "base",
1475
+ value
1476
+ })));
1477
+ }
1478
+ if (pending.length > 0) {
1479
+ racers.push(nextResolvedSlot(pending).then((resolved) => ({
1480
+ kind: "slot",
1481
+ ...resolved
1482
+ })));
1483
+ }
1484
+ return racers;
1485
+ };
1486
+ const flushTailLookbehind = (controller, tail) => {
1487
+ if (tail.length <= STREAM_TAIL_LOOKBEHIND) {
1488
+ return tail;
1489
+ }
1490
+ const content = tail.slice(0, tail.length - STREAM_TAIL_LOOKBEHIND);
1491
+ controller.enqueue(encoder.encode(content));
1492
+ return tail.slice(-STREAM_TAIL_LOOKBEHIND);
1493
+ };
1494
+ const finalizeCompletedBaseWinner = (controller, decodedTail, baseRead) => {
1495
+ const footerStart = decodedTail.search(CLOSING_PAGE_TAG_REGEX);
1496
+ if (footerStart < 0) {
1497
+ enqueueEncodedText(controller, encoder, decodedTail);
1498
+ return {
1499
+ baseDone: true,
1500
+ baseRead,
1501
+ footer: "",
1502
+ handled: true,
1503
+ tail: ""
1504
+ };
1505
+ }
1506
+ const content = decodedTail.slice(0, footerStart);
1507
+ const nextFooter = decodedTail.slice(footerStart);
1508
+ enqueueEncodedText(controller, encoder, content);
1509
+ return {
1510
+ baseDone: true,
1511
+ baseRead,
1512
+ footer: nextFooter,
1513
+ handled: true,
1514
+ tail: ""
1515
+ };
1516
+ };
1517
+ const handleBaseWinner = (controller, winner, baseRead, tail, footer) => {
1518
+ if (winner.kind !== "base") {
1519
+ return { baseDone: false, baseRead, footer, handled: false, tail };
1520
+ }
1521
+ if (winner.done) {
1522
+ return finalizeCompletedBaseWinner(controller, tail + decoder.decode(), baseRead);
1523
+ }
1524
+ if (!winner.value) {
1525
+ return { baseDone: false, baseRead, footer, handled: true, tail };
1526
+ }
1527
+ const nextTail = flushTailLookbehind(controller, tail + streamChunkToString2(winner.value, decoder));
1528
+ return {
1529
+ baseDone: false,
1530
+ baseRead: reader.read(),
1531
+ footer,
1532
+ handled: true,
1533
+ tail: nextTail
1534
+ };
1535
+ };
1536
+ const handleResolvedSlot = (controller, winner) => {
1537
+ const index = pending.indexOf(winner.original);
1538
+ if (index >= 0)
1539
+ pending.splice(index, 1);
1540
+ if (winner.result.payload === null) {
1541
+ return;
1542
+ }
1543
+ emitSlotMetric({
1544
+ bytes: winner.result.bytes,
1545
+ durationMs: winner.result.durationMs,
1546
+ slotId: winner.result.id,
1547
+ type: "patched"
1548
+ }, combinedOnSlotMetric);
1549
+ controller.enqueue(encoder.encode(renderStreamingSlotPatchTag(winner.result.id, winner.result.payload, nonce)));
1550
+ };
1551
+ const runPatchedStreamLoop = async (controller) => {
1552
+ let baseDone = false;
1553
+ let baseRead = reader.read();
1554
+ let tail = "";
1555
+ let footer = "";
1556
+ const readNextRaceWinner = async () => {
1557
+ const racers = createRaceCandidates(baseDone, baseRead);
1558
+ if (racers.length === 0) {
1559
+ return footer;
1560
+ }
1561
+ const winner = await Promise.race(racers);
1562
+ const baseWinnerState = applyBaseWinnerState(handleBaseWinner(controller, winner, baseRead, tail, footer), winner, (slotWinner) => {
1563
+ handleResolvedSlot(controller, slotWinner);
1564
+ });
1565
+ ({ baseDone, baseRead, footer, tail } = baseWinnerState);
1566
+ if (baseDone && pending.length === 0) {
1567
+ return footer;
1568
+ }
1569
+ return readNextRaceWinner();
1570
+ };
1571
+ return readNextRaceWinner();
1572
+ };
1573
+ return new ReadableStream({
1574
+ async start(controller) {
1575
+ try {
1576
+ const footer = await runPatchedStreamLoop(controller);
1577
+ enqueueEncodedText(controller, encoder, footer);
1578
+ controller.close();
1579
+ } catch (error) {
1580
+ controller.error(error);
1581
+ }
1582
+ }
1583
+ });
1584
+ }, injectStreamingRuntimeIntoStream = (stream, nonce, runtimePlacement = "head", runtimePreludeScript) => {
1585
+ const runtimeTag = renderStreamingSlotsRuntimeTag(nonce, runtimePreludeScript);
1586
+ const encoder = new TextEncoder;
1587
+ const decoder = new TextDecoder;
1588
+ const closingTag = runtimePlacement === "body" ? CLOSING_BODY_TAG : CLOSING_HEAD_TAG2;
1589
+ const lookbehind = (runtimePlacement === "body" ? CLOSING_BODY_TAG_LENGTH : CLOSING_HEAD_TAG_LENGTH) - 1;
1590
+ const flushRuntimeLookbehind = (controller, pending) => {
1591
+ if (pending.length <= lookbehind) {
1592
+ return pending;
1593
+ }
1594
+ const safeText = pending.slice(0, pending.length - lookbehind);
1595
+ controller.enqueue(encoder.encode(safeText));
1596
+ return pending.slice(-lookbehind);
1597
+ };
1598
+ const injectRuntimeIntoPending = (pending) => runtimePlacement === "body" ? injectHtmlIntoBody(pending, runtimeTag) : injectHtmlIntoHead(pending, runtimeTag);
1599
+ const processRuntimePending = (controller, pending, injected) => {
1600
+ if (injected) {
1601
+ controller.enqueue(encoder.encode(pending));
1602
+ return { injected, pending: "" };
1603
+ }
1604
+ const closingTagIndex = pending.indexOf(closingTag);
1605
+ if (closingTagIndex >= 0) {
1606
+ const withRuntime = `${pending.slice(0, closingTagIndex)}${runtimeTag}${pending.slice(closingTagIndex)}`;
1607
+ controller.enqueue(encoder.encode(withRuntime));
1608
+ return { injected: true, pending: "" };
1609
+ }
1610
+ return {
1611
+ injected,
1612
+ pending: flushRuntimeLookbehind(controller, pending)
1613
+ };
1614
+ };
1615
+ return new ReadableStream({
1616
+ async start(controller) {
1617
+ const reader = stream.getReader();
1618
+ let injected = false;
1619
+ let pending = "";
1620
+ const enqueuePending = () => enqueueEncodedText(controller, encoder, pending);
1621
+ const consumeRuntimeChunk = async () => {
1622
+ const { done, value } = await readStreamingRuntimeChunk(reader);
1623
+ if (done || !value) {
1624
+ return done;
1625
+ }
1626
+ pending += streamChunkToString2(value, decoder);
1627
+ ({ injected, pending } = processRuntimePending(controller, pending, injected));
1628
+ return false;
1629
+ };
1630
+ const runRuntimeInjectionLoop = async () => {
1631
+ const done = await consumeRuntimeChunk();
1632
+ if (done) {
1633
+ return;
1634
+ }
1635
+ await runRuntimeInjectionLoop();
1636
+ };
1637
+ try {
1638
+ await runRuntimeInjectionLoop();
1639
+ pending += decoder.decode();
1640
+ pending = injected ? pending : injectRuntimeIntoPending(pending);
1641
+ enqueuePending();
1642
+ controller.close();
1643
+ } catch (error) {
1644
+ controller.error(error);
1645
+ }
1646
+ }
1647
+ });
1648
+ }, streamOutOfOrderSlots = ({
1649
+ footerHtml = "",
1650
+ headerHtml = "",
1651
+ nonce,
1652
+ policy,
1653
+ onSlotMetric,
1654
+ onError,
1655
+ slots
1656
+ }) => {
1657
+ const resolvedPolicy = resolveStreamingSlotPolicy(policy);
1658
+ const combinedOnError = createCombinedSlotErrorHandler(resolvedPolicy.onError, onError);
1659
+ const combinedOnSlotMetric = createCombinedSlotMetricHandler(resolvedPolicy.onSlotMetric, onSlotMetric);
1660
+ const effectivePolicy = {
1661
+ ...resolvedPolicy,
1662
+ onSlotMetric: combinedOnSlotMetric
1663
+ };
1664
+ const preparedSlots = prepareSlots({
1665
+ onError: combinedOnError,
1666
+ onSlotMetric: combinedOnSlotMetric,
1667
+ policy: effectivePolicy,
1668
+ slots
1669
+ });
1670
+ const encoder = new TextEncoder;
1671
+ const createPendingSlots = (controller) => preparedSlots.map((slot) => {
1672
+ const fallback = renderStreamingSlotPlaceholder(slot.id, normalizeSlotText(slot.fallbackHtml, ""));
1673
+ controller.enqueue(toUint8(fallback, encoder));
1674
+ return resolveSlot(slot, combinedOnError, effectivePolicy, combinedOnSlotMetric);
1675
+ });
1676
+ const handleResolvedPreparedSlot = async (controller, pending) => {
1677
+ const { original, result } = await nextResolvedSlot(pending);
1678
+ const index = pending.indexOf(original);
1679
+ if (index >= 0)
1680
+ pending.splice(index, 1);
1681
+ if (result.payload === null) {
1682
+ return;
1683
+ }
1684
+ emitSlotMetric({
1685
+ bytes: result.bytes,
1686
+ durationMs: result.durationMs,
1687
+ slotId: result.id,
1688
+ type: "patched"
1689
+ }, combinedOnSlotMetric);
1690
+ controller.enqueue(toUint8(renderStreamingSlotPatchTag(result.id, result.payload, nonce), encoder));
1691
+ };
1692
+ const streamPreparedSlots = async (controller) => {
1693
+ const pending = createPendingSlots(controller);
1694
+ const streamNextPreparedSlot = async () => {
1695
+ if (pending.length === 0) {
1696
+ return;
1697
+ }
1698
+ await handleResolvedPreparedSlot(controller, pending);
1699
+ await streamNextPreparedSlot();
1700
+ };
1701
+ await streamNextPreparedSlot();
1702
+ };
1703
+ const resolveHeaderHtml = () => {
1704
+ const needsRuntimeTag = preparedSlots.length > 0 && !headerHtml.includes(STREAMING_RUNTIME_GLOBAL);
1705
+ if (!needsRuntimeTag) {
1706
+ return headerHtml;
1707
+ }
1708
+ return injectHtmlIntoHead(headerHtml, renderStreamingSlotsRuntimeTag(nonce));
1709
+ };
1710
+ return new ReadableStream({
1711
+ async start(controller) {
1712
+ try {
1713
+ const header = resolveHeaderHtml();
1714
+ controller.enqueue(toUint8(header, encoder));
1715
+ await streamPreparedSlots(controller);
1716
+ enqueueEncodedText(controller, encoder, footerHtml);
1717
+ controller.close();
1718
+ } catch (error) {
1719
+ controller.error(error);
1720
+ }
1721
+ }
1722
+ });
1723
+ };
1724
+ var init_streamingSlots = __esm(() => {
1725
+ init_constants();
1726
+ init_escapeScriptContent();
1727
+ CLOSING_BODY_TAG_LENGTH = CLOSING_BODY_TAG.length;
1728
+ CLOSING_HEAD_TAG_LENGTH = CLOSING_HEAD_TAG2.length;
1729
+ CLOSING_PAGE_TAG_REGEX = /<\/body>\s*<\/html>\s*$/i;
1730
+ currentStreamingSlotPolicy = {
1731
+ errorHtml: undefined,
1732
+ fallbackHtml: "",
1733
+ maxSlotHtmlSizeBytes: STREAMING_SLOT_MAX_HTML_BYTES,
1734
+ maxSlotsPerResponse: STREAMING_SLOT_MAX_PER_RESPONSE,
1735
+ timeoutMs: STREAMING_SLOT_TIMEOUT_MS
1736
+ };
1737
+ });
1738
+
1739
+ // src/utils/getDurationString.ts
1740
+ var getDurationString = (duration) => {
1741
+ let durationString;
1742
+ if (duration < MILLISECONDS_IN_A_SECOND) {
1743
+ durationString = `${duration.toFixed(TIME_PRECISION)}ms`;
1744
+ } else if (duration < MILLISECONDS_IN_A_MINUTE) {
1745
+ durationString = `${(duration / MILLISECONDS_IN_A_SECOND).toFixed(TIME_PRECISION)}s`;
1746
+ } else {
1747
+ const totalSeconds = Math.round(duration / MILLISECONDS_IN_A_SECOND);
1748
+ const minutes = Math.floor(totalSeconds / 60);
1749
+ const seconds = totalSeconds % 60;
1750
+ durationString = seconds === 0 ? `${minutes}m` : `${minutes}m ${seconds}s`;
1751
+ }
1752
+ return durationString;
1753
+ };
1754
+ var init_getDurationString = __esm(() => {
1755
+ init_constants();
1756
+ });
1757
+
1758
+ // src/utils/startupBanner.ts
1759
+ var colors, MONTHS, formatTimestamp = () => {
1760
+ const now = new Date;
1761
+ const month = MONTHS[now.getMonth()];
1762
+ const day = now.getDate().toString().padStart(2, "0");
1763
+ let hours = now.getHours();
1764
+ const minutes = now.getMinutes().toString().padStart(2, "0");
1765
+ const seconds = now.getSeconds().toString().padStart(2, "0");
1766
+ const ampm = hours >= HOURS_IN_HALF_DAY ? "PM" : "AM";
1767
+ hours = hours % HOURS_IN_HALF_DAY || HOURS_IN_HALF_DAY;
1768
+ return `${month} ${day} ${hours}:${minutes}:${seconds} ${ampm}`;
1769
+ }, startupBanner = (options) => {
1770
+ const {
1771
+ version,
1772
+ readyDuration,
1773
+ buildDuration,
1774
+ port,
1775
+ host,
1776
+ networkUrl,
1777
+ protocol = "http"
1778
+ } = options;
1779
+ const name = `${colors.cyan}${colors.bold}ABSOLUTEJS${colors.reset}`;
1780
+ const ver = `${colors.dim}v${version}${colors.reset}`;
1781
+ const time = `${colors.dim}ready in${colors.reset} ${colors.bold}${getDurationString(readyDuration)}${colors.reset}`;
1782
+ const build = typeof buildDuration === "number" && Number.isFinite(buildDuration) ? ` ${colors.dim}(build ${getDurationString(buildDuration)})${colors.reset}` : "";
1783
+ console.log("");
1784
+ console.log(` ${name} ${ver} ${time}${build}`);
1785
+ console.log("");
1786
+ console.log(` ${colors.green}\u279C${colors.reset} ${colors.bold}Local:${colors.reset} ${protocol}://${host === "0.0.0.0" ? "localhost" : host}:${port}/`);
1787
+ if (networkUrl) {
1788
+ console.log(` ${colors.green}\u279C${colors.reset} ${colors.bold}Network:${colors.reset} ${networkUrl}`);
1789
+ }
1790
+ console.log("");
1791
+ };
1792
+ var init_startupBanner = __esm(() => {
1793
+ init_constants();
1794
+ init_getDurationString();
1795
+ colors = {
1796
+ bold: "\x1B[1m",
1797
+ cyan: "\x1B[36m",
1798
+ dim: "\x1B[2m",
1799
+ green: "\x1B[32m",
1800
+ reset: "\x1B[0m"
1801
+ };
1802
+ MONTHS = [
1803
+ "Jan",
1804
+ "Feb",
1805
+ "Mar",
1806
+ "Apr",
1807
+ "May",
1808
+ "Jun",
1809
+ "Jul",
1810
+ "Aug",
1811
+ "Sep",
1812
+ "Oct",
1813
+ "Nov",
1814
+ "Dec"
1815
+ ];
1816
+ });
1817
+
1818
+ // src/utils/logger.ts
1819
+ var colors2, frameworkColors, formatPath = (filePath) => {
1820
+ const cwd = process.cwd();
1821
+ let relative3 = filePath.startsWith(cwd) ? filePath.slice(cwd.length + 1) : filePath;
1822
+ relative3 = relative3.replace(/\\/g, "/");
1823
+ if (!relative3.startsWith("/")) {
1824
+ relative3 = `/${relative3}`;
1825
+ }
1826
+ return relative3;
1827
+ }, getFrameworkColor = (framework) => frameworkColors[framework] || colors2.white, log = (action, options) => {
1828
+ const timestamp = `${colors2.dim}${formatTimestamp()}${colors2.reset}`;
1829
+ const tag = `${colors2.cyan}[hmr]${colors2.reset}`;
1830
+ let message = action;
1831
+ if (options?.path) {
1832
+ const pathColor = options.framework ? getFrameworkColor(options.framework) : colors2.white;
1833
+ message += ` ${pathColor}${formatPath(options.path)}${colors2.reset}`;
1834
+ }
1835
+ if (options?.duration !== undefined) {
1836
+ message += ` ${colors2.dim}(${options.duration}ms)${colors2.reset}`;
1837
+ }
1838
+ console.log(`${timestamp} ${tag} ${message}`);
1839
+ }, logCssUpdate = (path, framework, duration) => {
1840
+ log("css update", { duration, framework: framework ?? "css", path });
1841
+ }, logError = (message, error) => {
1842
+ const timestamp = `${colors2.dim}${formatTimestamp()}${colors2.reset}`;
1843
+ const tag = `${colors2.red}[hmr]${colors2.reset}`;
1844
+ const errorMsg = error instanceof Error ? error.message : error;
1845
+ const fullMessage = `${colors2.red}error${colors2.reset} ${message}${errorMsg ? `: ${errorMsg}` : ""}`;
1846
+ console.error(`${timestamp} ${tag} ${fullMessage}`);
1847
+ }, logHmrUpdate = (path, framework, duration) => {
1848
+ log("hmr update", { duration, framework, path });
1849
+ }, logScriptUpdate = (path, framework, duration) => {
1850
+ log("script update", { duration, framework, path });
1851
+ }, logServerReload = () => {
1852
+ log(`${colors2.cyan}server module reloaded${colors2.reset}`);
1853
+ }, logWarn = (message) => {
1854
+ const timestamp = `${colors2.dim}${formatTimestamp()}${colors2.reset}`;
1855
+ const tag = `${colors2.yellow}[hmr]${colors2.reset}`;
1856
+ console.log(`${timestamp} ${tag} ${colors2.yellow}warning ${message}${colors2.reset}`);
1857
+ };
1858
+ var init_logger = __esm(() => {
1859
+ init_startupBanner();
1860
+ colors2 = {
1861
+ blue: "\x1B[34m",
1862
+ bold: "\x1B[1m",
1863
+ cyan: "\x1B[36m",
1864
+ dim: "\x1B[2m",
1865
+ green: "\x1B[32m",
1866
+ magenta: "\x1B[35m",
1867
+ red: "\x1B[31m",
1868
+ reset: "\x1B[0m",
1869
+ white: "\x1B[37m",
1870
+ yellow: "\x1B[33m"
1871
+ };
1872
+ frameworkColors = {
1873
+ angular: colors2.magenta,
1874
+ assets: colors2.dim,
1875
+ css: colors2.cyan,
1876
+ html: colors2.white,
1877
+ htmx: colors2.white,
1878
+ react: colors2.blue,
1879
+ svelte: colors2.yellow,
1880
+ vue: colors2.green
1881
+ };
1882
+ });
1883
+
1884
+ // src/core/ssrCache.ts
1885
+ var dirtyFrameworks, isSsrCacheDirty = (framework) => dirtyFrameworks.has(framework), markSsrCacheDirty = (framework) => {
1886
+ dirtyFrameworks.add(framework);
1887
+ };
1888
+ var init_ssrCache = __esm(() => {
1889
+ dirtyFrameworks = new Set;
1890
+ });
1891
+
1892
+ // src/utils/stringModifiers.ts
1893
+ 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) => {
1894
+ if (!str.includes("-") && !str.includes("_")) {
1895
+ return str.charAt(0).toUpperCase() + str.slice(1);
1896
+ }
1897
+ return normalizeSlug(str).split(/[-_]/).filter(Boolean).map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1).toLowerCase()).join("");
1898
+ }, toScreamingSnake = (str) => str.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toUpperCase();
1899
+
1900
+ // src/svelte/renderToReadableStream.ts
1901
+ var exports_renderToReadableStream = {};
1902
+ __export(exports_renderToReadableStream, {
1903
+ renderToReadableStream: () => renderToReadableStream,
1904
+ SVELTE_PAGE_ROOT_ID: () => SVELTE_PAGE_ROOT_ID
1905
+ });
1906
+ var SVELTE_PAGE_ROOT_ID = "__absolute_svelte_root__", renderToReadableStream = async (component, props, {
1907
+ bootstrapScriptContent,
1908
+ bootstrapScripts = [],
1909
+ bootstrapModules = [],
1910
+ nonce,
1911
+ onError = console.error,
1912
+ progressiveChunkSize = DEFAULT_CHUNK_SIZE,
1913
+ signal,
1914
+ headContent,
1915
+ bodyContent
1916
+ } = {}) => {
1917
+ try {
1918
+ const { render } = await import("svelte/server");
1919
+ const renderComponent = render;
1920
+ const rendered = typeof props === "undefined" ? await renderComponent(component) : await renderComponent(component, { props });
1921
+ const { head, body } = rendered;
1922
+ const nonceAttr = nonce ? ` nonce="${nonce}"` : "";
1923
+ const scripts = (bootstrapScriptContent ? `<script${nonceAttr}>${escapeScriptContent(bootstrapScriptContent)}</script>` : "") + bootstrapScripts.map((src) => `<script${nonceAttr} src="${src}"></script>`).join("") + bootstrapModules.map((src) => `<script${nonceAttr} type="module" src="${src}"></script>`).join("");
1924
+ const encoder = new TextEncoder;
1925
+ const full = encoder.encode(`<!DOCTYPE html><html lang="en"><head>${head}${headContent ?? ""}</head><body><div id="${SVELTE_PAGE_ROOT_ID}">${body}</div>${scripts}${bodyContent ?? ""}</body></html>`);
1926
+ let offset = 0;
1927
+ return new ReadableStream({
1928
+ type: "bytes",
1929
+ cancel(reason) {
1930
+ onError?.(reason);
1931
+ },
1932
+ pull(controller) {
1933
+ if (signal?.aborted) {
1934
+ controller.close();
1935
+ return;
1936
+ }
1937
+ if (offset >= full.length) {
1938
+ controller.close();
1939
+ return;
1940
+ }
1941
+ const end = Math.min(offset + progressiveChunkSize, full.length);
1942
+ controller.enqueue(full.subarray(offset, end));
1943
+ offset = end;
1944
+ }
1945
+ });
1946
+ } catch (error) {
1947
+ onError?.(error);
1948
+ throw error;
1949
+ }
1950
+ };
1951
+ var init_renderToReadableStream = __esm(() => {
1952
+ init_constants();
1953
+ init_escapeScriptContent();
1954
+ });
1955
+
1956
+ // src/core/streamingSlotRegistrar.ts
1957
+ var STREAMING_SLOT_REGISTRAR_KEY = Symbol.for("absolutejs.streamingSlotRegistrar");
1958
+ var STREAMING_SLOT_WARNING_STORAGE_KEY = Symbol.for("absolutejs.streamingSlotWarningController");
1959
+ var STREAMING_SLOT_COLLECTION_STORAGE_KEY = Symbol.for("absolutejs.streamingSlotCollectionController");
1960
+ var getRegisteredStreamingSlotRegistrar = () => {
1961
+ const value = Reflect.get(globalThis, STREAMING_SLOT_REGISTRAR_KEY);
1962
+ if (typeof value === "function" || value === null) {
1963
+ return value;
1964
+ }
1965
+ return;
1966
+ };
1967
+ var isObjectRecord = (value) => Boolean(value) && typeof value === "object";
1968
+ var isStreamingSlotWarningController = (value) => isObjectRecord(value) && ("maybeWarn" in value) && typeof value.maybeWarn === "function";
1969
+ var isStreamingSlotCollectionController = (value) => isObjectRecord(value) && ("isCollecting" in value) && typeof value.isCollecting === "function";
1970
+ var getWarningController = () => {
1971
+ const value = Reflect.get(globalThis, STREAMING_SLOT_WARNING_STORAGE_KEY);
1972
+ if (value === null || typeof value === "undefined")
1973
+ return;
1974
+ return isStreamingSlotWarningController(value) ? value : undefined;
1975
+ };
1976
+ var getCollectionController = () => {
1977
+ const value = Reflect.get(globalThis, STREAMING_SLOT_COLLECTION_STORAGE_KEY);
1978
+ if (value === null || typeof value === "undefined")
1979
+ return;
1980
+ return isStreamingSlotCollectionController(value) ? value : undefined;
1981
+ };
1982
+ var hasRegisteredStreamingSlotRegistrar = () => typeof getRegisteredStreamingSlotRegistrar() === "function";
1983
+ var isStreamingSlotCollectionActive = () => getCollectionController()?.isCollecting() === true;
1984
+ var registerStreamingSlot = (slot) => {
1985
+ getRegisteredStreamingSlotRegistrar()?.(slot);
1986
+ };
1987
+ var setStreamingSlotCollectionController = (controller) => {
1988
+ Reflect.set(globalThis, STREAMING_SLOT_COLLECTION_STORAGE_KEY, controller);
1989
+ };
1990
+ var setStreamingSlotRegistrar = (nextRegistrar) => {
1991
+ Reflect.set(globalThis, STREAMING_SLOT_REGISTRAR_KEY, nextRegistrar);
1992
+ };
1993
+ var setStreamingSlotWarningController = (controller) => {
1994
+ Reflect.set(globalThis, STREAMING_SLOT_WARNING_STORAGE_KEY, controller);
1995
+ };
1996
+ var warnMissingStreamingSlotCollector = (primitiveName) => {
1997
+ if (isStreamingSlotCollectionActive()) {
1998
+ return;
1999
+ }
2000
+ getWarningController()?.maybeWarn(primitiveName);
2001
+ };
2002
+
2003
+ // src/core/streamingSlotRegistry.ts
2004
+ var STREAMING_SLOT_STORAGE_KEY = Symbol.for("absolutejs.streamingSlotAsyncLocalStorage");
2005
+ var isObjectRecord2 = (value) => Boolean(value) && typeof value === "object";
2006
+ var isAsyncLocalStorage = (value) => isObjectRecord2(value) && ("getStore" in value) && typeof value.getStore === "function" && ("run" in value) && typeof value.run === "function";
2007
+ var getStorageGlobal = () => {
2008
+ const value = Reflect.get(globalThis, STREAMING_SLOT_STORAGE_KEY);
2009
+ if (value === null || typeof value === "undefined") {
2010
+ return value;
2011
+ }
2012
+ return isAsyncLocalStorage(value) ? value : undefined;
2013
+ };
2014
+ var isServerRuntime = () => typeof process !== "undefined" && typeof process.versions?.node === "string";
2015
+ var ensureAsyncLocalStorage = async () => {
2016
+ const storage = getStorageGlobal();
2017
+ if (typeof storage !== "undefined") {
2018
+ return storage;
2019
+ }
2020
+ if (!isServerRuntime()) {
2021
+ Reflect.set(globalThis, STREAMING_SLOT_STORAGE_KEY, null);
2022
+ return getStorageGlobal();
2023
+ }
2024
+ const mod = await import("async_hooks");
2025
+ Reflect.set(globalThis, STREAMING_SLOT_STORAGE_KEY, new mod.AsyncLocalStorage);
2026
+ return getStorageGlobal();
2027
+ };
2028
+ var getActiveSlotStore = () => {
2029
+ const storage = getStorageGlobal();
2030
+ if (!storage)
2031
+ return;
2032
+ return storage.getStore();
2033
+ };
2034
+ var registerStreamingSlot2 = (slot) => {
2035
+ const store = getActiveSlotStore();
2036
+ if (!store)
2037
+ return;
2038
+ store.set(slot.id, slot);
2039
+ };
2040
+ setStreamingSlotRegistrar(registerStreamingSlot2);
2041
+ setStreamingSlotCollectionController({
2042
+ isCollecting: () => getActiveSlotStore() !== undefined
2043
+ });
2044
+ var hasActiveStreamingSlotRegistry = () => getActiveSlotStore() !== undefined;
2045
+ var runWithStreamingSlotRegistry = async (task) => {
2046
+ const storage = await ensureAsyncLocalStorage();
2047
+ if (!storage) {
2048
+ const slots = [];
2049
+ return {
2050
+ result: await task(),
2051
+ slots
2052
+ };
2053
+ }
2054
+ return storage.run(new Map, async () => {
2055
+ const result = await task();
2056
+ const store = storage.getStore();
2057
+ return {
2058
+ result,
2059
+ slots: store ? [...store.values()] : []
2060
+ };
2061
+ });
2062
+ };
2063
+
2064
+ // src/svelte/pageHandler.ts
2065
+ init_svelteServerModule();
2066
+
2067
+ // src/core/islandPageContext.ts
2068
+ init_constants();
2069
+ var BOOTSTRAP_MANIFEST_KEY = "BootstrapClient";
2070
+ var ISLAND_MARKER = 'data-island="true"';
2071
+ var MANIFEST_MARKER = "__ABSOLUTE_MANIFEST__";
2072
+ var ISLAND_STATE_MARKER = "__ABS_ISLAND_STATE__";
2073
+ var CLOSING_HEAD_TAG = "</head>";
2074
+ var buildIslandsHeadMarkup = (manifest) => {
2075
+ const manifestScript = `<script>window.__ABSOLUTE_MANIFEST__ = ${JSON.stringify(manifest)}</script>`;
2076
+ const islandStateScript = `<script>window.__ABS_ISLAND_STATE__ = ${JSON.stringify(globalThis.__ABS_ISLAND_STATE__ ?? {})}</script>`;
2077
+ const bootstrapPath = manifest[BOOTSTRAP_MANIFEST_KEY];
2078
+ const bootstrapScript = bootstrapPath ? `<script type="module" src="${bootstrapPath}"></script>` : "";
2079
+ return `${manifestScript}${islandStateScript}${bootstrapScript}`;
2080
+ };
2081
+ var injectHeadMarkup = (html, markup) => {
2082
+ const closingHeadIndex = html.indexOf("</head>");
2083
+ if (closingHeadIndex >= 0) {
2084
+ return `${html.slice(0, closingHeadIndex)}${markup}${html.slice(closingHeadIndex)}`;
2085
+ }
2086
+ const openingBodyIndex = html.indexOf("<body");
2087
+ if (openingBodyIndex >= 0) {
2088
+ const bodyStart = html.indexOf(">", openingBodyIndex);
2089
+ if (bodyStart >= 0) {
2090
+ return `${html.slice(0, openingBodyIndex)}<head>${markup}</head>${html.slice(openingBodyIndex)}`;
2091
+ }
2092
+ }
2093
+ return `<!DOCTYPE html><html><head>${markup}</head><body>${html}</body></html>`;
2094
+ };
2095
+ var streamChunkToString = (value, decoder) => typeof value === "string" ? value : decoder.decode(value, { stream: true });
2096
+ var flushSafePendingText = (controller, encoder, pending, lookbehind) => {
2097
+ if (pending.length <= lookbehind) {
2098
+ return pending;
2099
+ }
2100
+ const safeText = pending.slice(0, pending.length - lookbehind);
2101
+ controller.enqueue(encoder.encode(safeText));
2102
+ return pending.slice(-lookbehind);
2103
+ };
2104
+ var updateInjectedState = (consumed, injected, pending) => {
2105
+ if (consumed.done) {
2106
+ return { done: true, injected, pending };
2107
+ }
2108
+ return {
2109
+ done: false,
2110
+ injected: consumed.injected,
2111
+ pending: consumed.pending
2112
+ };
2113
+ };
2114
+ var readStreamChunk = async (reader) => {
2115
+ const { done, value } = await reader.read();
2116
+ if (done || !value) {
2117
+ return { done, value: undefined };
2118
+ }
2119
+ return { done, value };
2120
+ };
2121
+ var pipeStreamWithHeadInjection = (stream, markup) => {
2122
+ const encoder = new TextEncoder;
2123
+ const decoder = new TextDecoder;
2124
+ const lookbehind = CLOSING_HEAD_TAG.length - 1;
2125
+ const processPending = (controller, pending, injected) => {
2126
+ if (injected) {
2127
+ controller.enqueue(encoder.encode(pending));
2128
+ return { injected, pending: "" };
2129
+ }
2130
+ const headIndex = pending.indexOf(CLOSING_HEAD_TAG);
2131
+ if (headIndex >= 0) {
2132
+ const next = `${pending.slice(0, headIndex)}${markup}${pending.slice(headIndex)}`;
2133
+ controller.enqueue(encoder.encode(next));
2134
+ return { injected: true, pending: "" };
2135
+ }
2136
+ return {
2137
+ injected,
2138
+ pending: flushSafePendingText(controller, encoder, pending, lookbehind)
2139
+ };
2140
+ };
2141
+ const finishHeadInjectionStream = (controller, pending, injected) => {
2142
+ let finalPending = pending + decoder.decode();
2143
+ if (!injected) {
2144
+ finalPending = injectHeadMarkup(finalPending, markup);
2145
+ }
2146
+ if (finalPending.length > 0) {
2147
+ controller.enqueue(encoder.encode(finalPending));
2148
+ }
2149
+ controller.close();
2150
+ };
2151
+ const consumeHeadChunk = async (controller, reader, pending, injected) => {
2152
+ const { done, value } = await readStreamChunk(reader);
2153
+ if (done || !value) {
2154
+ return { done, injected, pending };
2155
+ }
2156
+ const processed = processPending(controller, pending + streamChunkToString(value, decoder), injected);
2157
+ return {
2158
+ done,
2159
+ injected: processed.injected,
2160
+ pending: processed.pending
2161
+ };
2162
+ };
2163
+ const runHeadInjectionLoop = async (controller, reader) => {
2164
+ const consumeNextHeadChunk = async (injected, pending) => {
2165
+ const consumed = await consumeHeadChunk(controller, reader, pending, injected);
2166
+ const nextState = updateInjectedState(consumed, injected, pending);
2167
+ if (nextState.done) {
2168
+ return { injected, pending };
2169
+ }
2170
+ return consumeNextHeadChunk(nextState.injected, nextState.pending);
2171
+ };
2172
+ return consumeNextHeadChunk(false, "");
2173
+ };
2174
+ return new ReadableStream({
2175
+ async start(controller) {
2176
+ const reader = stream.getReader();
2177
+ try {
2178
+ const { injected, pending } = await runHeadInjectionLoop(controller, reader);
2179
+ finishHeadInjectionStream(controller, pending, injected);
2180
+ } catch (error) {
2181
+ controller.error(error);
2182
+ }
2183
+ }
2184
+ });
2185
+ };
2186
+ var pipeStreamWithIslandMarkerDetection = (stream, markup) => {
2187
+ const encoder = new TextEncoder;
2188
+ const decoder = new TextDecoder;
2189
+ const lookbehind = Math.max(ISLAND_MARKER.length, BYTES_PER_KILOBYTE);
2190
+ const processPending = (controller, pending, injected) => {
2191
+ if (injected) {
2192
+ controller.enqueue(encoder.encode(pending));
2193
+ return { injected, pending: "" };
2194
+ }
2195
+ const markerIndex = pending.indexOf(ISLAND_MARKER);
2196
+ if (markerIndex >= 0) {
2197
+ const tagStart = pending.lastIndexOf("<", markerIndex);
2198
+ const injectAt = tagStart >= 0 ? tagStart : markerIndex;
2199
+ const next = `${pending.slice(0, injectAt)}${markup}${pending.slice(injectAt)}`;
2200
+ controller.enqueue(encoder.encode(next));
2201
+ return { injected: true, pending: "" };
2202
+ }
2203
+ return {
2204
+ injected,
2205
+ pending: flushSafePendingText(controller, encoder, pending, lookbehind)
2206
+ };
2207
+ };
2208
+ const finishIslandMarkerStream = (controller, pending) => {
2209
+ const finalPending = pending + decoder.decode();
2210
+ if (finalPending.length > 0) {
2211
+ controller.enqueue(encoder.encode(finalPending));
2212
+ }
2213
+ controller.close();
2214
+ };
2215
+ const consumeIslandChunk = async (controller, reader, pending, injected) => {
2216
+ const { done, value } = await readStreamChunk(reader);
2217
+ if (done || !value) {
2218
+ return { done, injected, pending };
2219
+ }
2220
+ const processed = processPending(controller, pending + streamChunkToString(value, decoder), injected);
2221
+ return {
2222
+ done,
2223
+ injected: processed.injected,
2224
+ pending: processed.pending
2225
+ };
2226
+ };
2227
+ const runIslandMarkerLoop = async (controller, reader) => {
2228
+ const consumeNextIslandChunk = async (injected, pending) => {
2229
+ const consumed = await consumeIslandChunk(controller, reader, pending, injected);
2230
+ const nextState = updateInjectedState(consumed, injected, pending);
2231
+ if (nextState.done) {
2232
+ return { injected, pending };
2233
+ }
2234
+ return consumeNextIslandChunk(nextState.injected, nextState.pending);
2235
+ };
2236
+ return consumeNextIslandChunk(false, "");
2237
+ };
2238
+ return new ReadableStream({
2239
+ async start(controller) {
2240
+ const reader = stream.getReader();
2241
+ try {
2242
+ const { pending } = await runIslandMarkerLoop(controller, reader);
2243
+ finishIslandMarkerStream(controller, pending);
2244
+ } catch (error) {
2245
+ controller.error(error);
2246
+ }
2247
+ }
2248
+ });
2249
+ };
2250
+ var htmlContainsIslands = (html) => html.includes(ISLAND_MARKER);
2251
+ var injectIslandPageContext = (html, options) => {
2252
+ const manifest = globalThis.__absoluteManifest;
2253
+ const hasIslands = options?.hasIslands ?? htmlContainsIslands(html);
2254
+ if (!manifest || !hasIslands) {
2255
+ return html;
2256
+ }
2257
+ if (html.includes(MANIFEST_MARKER) || html.includes(ISLAND_STATE_MARKER)) {
2258
+ return html;
2259
+ }
2260
+ return injectHeadMarkup(html, buildIslandsHeadMarkup(manifest));
2261
+ };
2262
+ var injectIslandPageContextStream = (stream, options) => {
2263
+ const manifest = globalThis.__absoluteManifest;
2264
+ if (!manifest)
2265
+ return stream;
2266
+ const markup = buildIslandsHeadMarkup(manifest);
2267
+ if (options?.hasIslands === true) {
2268
+ return pipeStreamWithHeadInjection(stream, markup);
2269
+ }
2270
+ if (options?.hasIslands === false) {
2271
+ return stream;
2272
+ }
2273
+ return pipeStreamWithIslandMarkerDetection(stream, markup);
2274
+ };
2275
+ var setCurrentIslandManifest = (manifest) => {
2276
+ globalThis.__absoluteManifest = manifest;
2277
+ };
2278
+
2279
+ // src/svelte/pageHandler.ts
2280
+ init_devRouteRegistrationCallsite();
2281
+
2282
+ // src/core/responseEnhancers.ts
2283
+ init_streamingSlots();
2284
+ var toResponse = async (responseLike) => responseLike;
2285
+ var cloneHeaders = (response) => {
2286
+ const headers = new Headers(response.headers);
2287
+ return headers;
2288
+ };
2289
+ var enhanceHtmlResponseWithStreamingSlots = (response, {
2290
+ nonce,
2291
+ onError,
2292
+ runtimePlacement,
2293
+ runtimePreludeScript,
2294
+ streamingSlots = [],
2295
+ policy
2296
+ } = {}) => {
2297
+ if (!response.body || streamingSlots.length === 0) {
2298
+ return response;
2299
+ }
2300
+ const body = appendStreamingSlotPatchesToStream(response.body, streamingSlots, {
2301
+ nonce,
2302
+ onError,
2303
+ policy,
2304
+ runtimePlacement,
2305
+ runtimePreludeScript
2306
+ });
2307
+ return new Response(body, {
2308
+ headers: cloneHeaders(response),
2309
+ status: response.status,
2310
+ statusText: response.statusText
2311
+ });
2312
+ };
2313
+ var withStreamingSlots = async (responseLike, options = {}) => enhanceHtmlResponseWithStreamingSlots(await toResponse(responseLike), options);
2314
+ var mergeStreamingSlots = (registered, explicit) => {
2315
+ const merged = new Map;
2316
+ for (const slot of registered)
2317
+ merged.set(slot.id, slot);
2318
+ for (const slot of explicit)
2319
+ merged.set(slot.id, slot);
2320
+ return [...merged.values()];
2321
+ };
2322
+ var withRegisteredStreamingSlots = async (renderResponse, options = {}) => {
2323
+ const { result, slots } = await runWithStreamingSlotRegistry(renderResponse);
2324
+ const explicit = options.streamingSlots ?? [];
2325
+ return withStreamingSlots(result, {
2326
+ ...options,
2327
+ streamingSlots: mergeStreamingSlots(slots, explicit)
2328
+ });
2329
+ };
2330
+
2331
+ // src/core/streamingSlotWarningScope.ts
2332
+ init_logger();
2333
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
2334
+ var STREAMING_SLOT_WARNING_STORAGE_KEY2 = Symbol.for("absolutejs.streamingSlotWarningAsyncLocalStorage");
2335
+ var isObjectRecord4 = (value) => Boolean(value) && typeof value === "object";
2336
+ var isAsyncLocalStorage3 = (value) => isObjectRecord4(value) && ("getStore" in value) && typeof value.getStore === "function" && ("run" in value) && typeof value.run === "function";
2337
+ var getWarningStorage = () => {
2338
+ const value = Reflect.get(globalThis, STREAMING_SLOT_WARNING_STORAGE_KEY2);
2339
+ if (value === null || typeof value === "undefined") {
2340
+ return;
2341
+ }
2342
+ return isAsyncLocalStorage3(value) ? value : undefined;
2343
+ };
2344
+ var ensureWarningStorage = () => {
2345
+ const existing = getWarningStorage();
2346
+ if (existing) {
2347
+ return existing;
2348
+ }
2349
+ const storage = new AsyncLocalStorage2;
2350
+ Reflect.set(globalThis, STREAMING_SLOT_WARNING_STORAGE_KEY2, storage);
2351
+ return storage;
2352
+ };
2353
+ var normalizeCallsitePath2 = (value) => value.replace(`${process.cwd()}/`, "").replace(process.cwd(), "").replace(/^\.\/+/, "");
2354
+ var formatWarningCallsite = (callsite) => {
2355
+ const match = callsite.match(/^(.*?)(:\d+:\d+)$/);
2356
+ if (!match) {
2357
+ return `\x1B[36m${callsite}\x1B[0m`;
2358
+ }
2359
+ return `\x1B[36m${match[1]}\x1B[33m${match[2]}\x1B[0m`;
2360
+ };
2361
+ 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.");
2362
+ var getWarningLocation = (frame) => frame.match(/\((\/[^)]+:\d+:\d+)\)$/)?.[1] ?? frame.match(/at (\/[^ ]+:\d+:\d+)$/)?.[1];
2363
+ var extractCallsiteFromStack = (stack) => {
2364
+ const location = stack.split(`
2365
+ `).slice(1).map((line) => line.trim()).filter((frame) => !shouldIgnoreWarningFrame(frame)).map((frame) => getWarningLocation(frame)).find((frameLocation) => frameLocation !== undefined);
2366
+ return location ? normalizeCallsitePath2(location) : undefined;
2367
+ };
2368
+ 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)}.` : ""}`;
2369
+ setStreamingSlotWarningController({
2370
+ maybeWarn: (primitiveName) => {
2371
+ const store = getWarningStorage()?.getStore();
2372
+ if (!store || store.hasWarned) {
2373
+ return;
2374
+ }
2375
+ store.hasWarned = true;
2376
+ logWarn(buildMissingCollectorWarning(primitiveName, store.handlerCallsite));
2377
+ }
2378
+ });
2379
+ var captureStreamingSlotWarningCallsite = () => {
2380
+ if (false) {}
2381
+ const { stack } = new Error;
2382
+ if (!stack) {
2383
+ return;
2384
+ }
2385
+ return extractCallsiteFromStack(stack);
2386
+ };
2387
+ var runWithStreamingSlotWarningScope = (task, metadata) => ensureWarningStorage().run({ handlerCallsite: metadata?.handlerCallsite, hasWarned: false }, task);
2388
+
2389
+ // src/svelte/pageHandler.ts
2390
+ init_ssrCache();
2391
+
2392
+ // src/utils/ssrErrorPage.ts
2393
+ var ssrErrorPage = (framework, error) => {
2394
+ const frameworkColors2 = {
2395
+ angular: "#dd0031",
2396
+ html: "#e34c26",
2397
+ htmx: "#1a365d",
2398
+ react: "#61dafb",
2399
+ svelte: "#ff3e00",
2400
+ vue: "#42b883"
2401
+ };
2402
+ const accent = frameworkColors2[framework] ?? "#94a3b8";
2403
+ const label = framework.charAt(0).toUpperCase() + framework.slice(1);
2404
+ const message = error instanceof Error ? error.message : String(error);
2405
+ return `<!DOCTYPE html>
2406
+ <html>
2407
+ <head>
2408
+ <meta charset="utf-8">
2409
+ <meta name="viewport" content="width=device-width, initial-scale=1">
2410
+ <title>SSR Error - AbsoluteJS</title>
2411
+ <style>
2412
+ *{margin:0;padding:0;box-sizing:border-box}
2413
+ 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}
2414
+ .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}
2415
+ .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)}
2416
+ .brand{font-weight:700;font-size:20px;color:#fff;letter-spacing:-0.02em}
2417
+ .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)}
2418
+ .kind{color:#94a3b8;font-size:13px;font-weight:500}
2419
+ .content{padding:24px}
2420
+ .label{font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.08em;color:#94a3b8;margin-bottom:8px}
2421
+ .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}
2422
+ .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}
2423
+ </style>
2424
+ </head>
2425
+ <body>
2426
+ <div class="card">
2427
+ <div class="header">
2428
+ <div style="display:flex;align-items:center;gap:12px">
2429
+ <span class="brand">AbsoluteJS</span>
2430
+ <span class="badge">${label}</span>
2431
+ </div>
2432
+ <span class="kind">Server Render Error</span>
2433
+ </div>
2434
+ <div class="content">
2435
+ <div class="label">What went wrong</div>
2436
+ <pre class="message">${message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")}</pre>
2437
+ <div class="hint">A component threw during server-side rendering. Check the terminal for the full stack trace.</div>
2438
+ </div>
2439
+ </div>
2440
+ </body>
2441
+ </html>`;
2442
+ };
2443
+
2444
+ // src/utils/resolveConvention.ts
2445
+ import { basename as basename2 } from "path";
2446
+ var CONVENTIONS_KEY = "__absoluteConventions";
2447
+ var isConventionsMap = (value) => Boolean(value) && typeof value === "object";
2448
+ var getMap = () => {
2449
+ const value = Reflect.get(globalThis, CONVENTIONS_KEY);
2450
+ if (isConventionsMap(value))
2451
+ return value;
2452
+ const empty = {};
2453
+ return empty;
2454
+ };
2455
+ var derivePageName = (pagePath) => {
2456
+ const base = basename2(pagePath);
2457
+ const dotIndex = base.indexOf(".");
2458
+ const name = dotIndex > 0 ? base.slice(0, dotIndex) : base;
2459
+ return toPascal(name);
2460
+ };
2461
+ var normalizeConventionPageName = (name) => toPascal(name).replace(/\d+$/, "");
2462
+ var resolveErrorConventionPath = (framework, pageName) => {
2463
+ const conventions = getMap()[framework];
2464
+ if (!conventions)
2465
+ return;
2466
+ const exact = conventions.pages?.[pageName]?.error;
2467
+ if (exact)
2468
+ return exact;
2469
+ const normalizedPageName = normalizeConventionPageName(pageName);
2470
+ for (const [candidate, page] of Object.entries(conventions.pages ?? {})) {
2471
+ if (normalizeConventionPageName(candidate) === normalizedPageName) {
2472
+ return page.error ?? conventions.defaults?.error;
2473
+ }
2474
+ }
2475
+ return conventions.defaults?.error;
2476
+ };
2477
+ var resolveNotFoundConventionPath = (framework) => getMap()[framework]?.defaults?.notFound;
2478
+ var hasErrorConvention = (framework) => {
2479
+ const conventions = getMap()[framework];
2480
+ if (!conventions)
2481
+ return false;
2482
+ if (conventions.defaults?.error)
2483
+ return true;
2484
+ return Object.values(conventions.pages ?? {}).some((page) => Boolean(page.error));
2485
+ };
2486
+ var setConventions = (map) => {
2487
+ Reflect.set(globalThis, CONVENTIONS_KEY, map);
2488
+ };
2489
+ var isDev = () => true;
2490
+ var buildErrorProps = (error) => {
2491
+ const message = error instanceof Error ? error.message : String(error);
2492
+ const stack = isDev() && error instanceof Error ? error.stack : undefined;
2493
+ return { error: { message, stack } };
2494
+ };
2495
+ var renderReactError = async (conventionPath, errorProps) => {
2496
+ const { createElement } = await import("react");
2497
+ const { renderToReadableStream } = await import("react-dom/server");
2498
+ const mod = await import(conventionPath);
2499
+ const [firstKey] = Object.keys(mod);
2500
+ const ErrorComponent = mod.default ?? (firstKey ? mod[firstKey] : undefined);
2501
+ const element = createElement(ErrorComponent, errorProps);
2502
+ const stream = await renderToReadableStream(element);
2503
+ return new Response(stream, {
2504
+ headers: { "Content-Type": "text/html" },
2505
+ status: 500
2506
+ });
2507
+ };
2508
+ var renderSvelteError = async (conventionPath, errorProps) => {
2509
+ const { render } = await import("svelte/server");
2510
+ const mod = await import(conventionPath);
2511
+ const ErrorComponent = mod.default;
2512
+ const { head, body } = render(ErrorComponent, {
2513
+ props: errorProps
2514
+ });
2515
+ const html = `<!DOCTYPE html><html><head>${head}</head><body>${body}</body></html>`;
2516
+ return new Response(html, {
2517
+ headers: { "Content-Type": "text/html" },
2518
+ status: 500
2519
+ });
2520
+ };
2521
+ var unescapeVueStyles = (ssrBody) => {
2522
+ let styles = "";
2523
+ const body = ssrBody.replace(/<style>([\s\S]*?)<\/style>/g, (_, css) => {
2524
+ styles += `<style>${css.replace(/&quot;/g, '"').replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">")}</style>`;
2525
+ return "";
2526
+ });
2527
+ return { body, styles };
2528
+ };
2529
+ var renderVueError = async (conventionPath, errorProps) => {
2530
+ const { createSSRApp, h } = await import("vue");
2531
+ const { renderToString } = await import("vue/server-renderer");
2532
+ const mod = await import(conventionPath);
2533
+ const ErrorComponent = mod.default;
2534
+ const app = createSSRApp({
2535
+ render: () => h(ErrorComponent, errorProps)
2536
+ });
2537
+ const rawBody = await renderToString(app);
2538
+ const { styles, body } = unescapeVueStyles(rawBody);
2539
+ const html = `<!DOCTYPE html><html><head>${styles}</head><body><div id="root">${body}</div></body></html>`;
2540
+ return new Response(html, {
2541
+ headers: { "Content-Type": "text/html" },
2542
+ status: 500
2543
+ });
2544
+ };
2545
+ var renderAngularError = async (conventionPath, errorProps) => {
2546
+ const mod = await import(conventionPath);
2547
+ const renderError = mod.default ?? mod.renderError;
2548
+ if (typeof renderError !== "function")
2549
+ return null;
2550
+ const html = renderError(errorProps);
2551
+ return new Response(html, {
2552
+ headers: { "Content-Type": "text/html" },
2553
+ status: 500
2554
+ });
2555
+ };
2556
+ var logConventionRenderError = (framework, label, renderError) => {
2557
+ const message = renderError instanceof Error ? renderError.message : "";
2558
+ if (message.includes("Cannot find module") || message.includes("Cannot find package") || message.includes("not found in module")) {
2559
+ 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}).`);
2560
+ return;
2561
+ }
2562
+ console.error(`[SSR] Failed to render ${framework} convention ${label} page:`, renderError);
2563
+ };
2564
+ var ERROR_RENDERERS = {
2565
+ angular: renderAngularError,
2566
+ react: renderReactError,
2567
+ svelte: renderSvelteError,
2568
+ vue: renderVueError
2569
+ };
2570
+ var renderConventionError = async (framework, pageName, error) => {
2571
+ let conventionPath = resolveErrorConventionPath(framework, pageName);
2572
+ if (!conventionPath && error instanceof Error && error.stack) {
2573
+ for (const match of error.stack.matchAll(/^\s*at\s+([A-Za-z_$][\w$]*)/gm)) {
2574
+ const candidate = match[1];
2575
+ if (!candidate)
2576
+ continue;
2577
+ conventionPath = resolveErrorConventionPath(framework, candidate);
2578
+ if (conventionPath)
2579
+ break;
2580
+ }
2581
+ }
2582
+ if (!conventionPath)
2583
+ return null;
2584
+ const errorProps = buildErrorProps(error);
2585
+ const renderer = ERROR_RENDERERS[framework];
2586
+ if (!renderer)
2587
+ return null;
2588
+ try {
2589
+ return await renderer(conventionPath, errorProps);
2590
+ } catch (renderError) {
2591
+ logConventionRenderError(framework, "error", renderError);
2592
+ }
2593
+ return null;
2594
+ };
2595
+ var renderReactNotFound = async (conventionPath) => {
2596
+ const { createElement } = await import("react");
2597
+ const { renderToReadableStream } = await import("react-dom/server");
2598
+ const mod = await import(conventionPath);
2599
+ const [nfKey] = Object.keys(mod);
2600
+ const NotFoundComponent = mod.default ?? (nfKey ? mod[nfKey] : undefined);
2601
+ const element = createElement(NotFoundComponent);
2602
+ const stream = await renderToReadableStream(element);
2603
+ return new Response(stream, {
2604
+ headers: { "Content-Type": "text/html" },
2605
+ status: 404
2606
+ });
2607
+ };
2608
+ var renderSvelteNotFound = async (conventionPath) => {
2609
+ const { render } = await import("svelte/server");
2610
+ const mod = await import(conventionPath);
2611
+ const NotFoundComponent = mod.default;
2612
+ const { head, body } = render(NotFoundComponent);
2613
+ const html = `<!DOCTYPE html><html><head>${head}</head><body>${body}</body></html>`;
2614
+ return new Response(html, {
2615
+ headers: { "Content-Type": "text/html" },
2616
+ status: 404
2617
+ });
2618
+ };
2619
+ var renderVueNotFound = async (conventionPath) => {
2620
+ const { createSSRApp, h } = await import("vue");
2621
+ const { renderToString } = await import("vue/server-renderer");
2622
+ const mod = await import(conventionPath);
2623
+ const NotFoundComponent = mod.default;
2624
+ const app = createSSRApp({
2625
+ render: () => h(NotFoundComponent)
2626
+ });
2627
+ const rawBody = await renderToString(app);
2628
+ const { styles, body } = unescapeVueStyles(rawBody);
2629
+ const html = `<!DOCTYPE html><html><head>${styles}</head><body><div id="root">${body}</div></body></html>`;
2630
+ return new Response(html, {
2631
+ headers: { "Content-Type": "text/html" },
2632
+ status: 404
2633
+ });
2634
+ };
2635
+ var renderAngularNotFound = async (conventionPath) => {
2636
+ const mod = await import(conventionPath);
2637
+ const renderNotFound = mod.default ?? mod.renderNotFound;
2638
+ if (typeof renderNotFound !== "function")
2639
+ return null;
2640
+ const html = renderNotFound();
2641
+ return new Response(html, {
2642
+ headers: { "Content-Type": "text/html" },
2643
+ status: 404
2644
+ });
2645
+ };
2646
+ var NOT_FOUND_RENDERERS = {
2647
+ angular: renderAngularNotFound,
2648
+ react: renderReactNotFound,
2649
+ svelte: renderSvelteNotFound,
2650
+ vue: renderVueNotFound
2651
+ };
2652
+ var renderConventionNotFound = async (framework) => {
2653
+ const conventionPath = resolveNotFoundConventionPath(framework);
2654
+ if (!conventionPath)
2655
+ return null;
2656
+ const renderer = NOT_FOUND_RENDERERS[framework];
2657
+ if (!renderer)
2658
+ return null;
2659
+ try {
2660
+ return await renderer(conventionPath);
2661
+ } catch (renderError) {
2662
+ logConventionRenderError(framework, "not-found", renderError);
2663
+ }
2664
+ return null;
2665
+ };
2666
+ var NOT_FOUND_PRIORITY = [
2667
+ "react",
2668
+ "svelte",
2669
+ "vue",
2670
+ "angular"
2671
+ ];
2672
+ var renderFirstNotFound = async () => {
2673
+ const renderNext = async (frameworks) => {
2674
+ const [framework, ...remaining] = frameworks;
2675
+ if (!framework) {
2676
+ return null;
2677
+ }
2678
+ if (!getMap()[framework]?.defaults?.notFound) {
2679
+ return renderNext(remaining);
2680
+ }
2681
+ const response = await renderConventionNotFound(framework);
2682
+ if (response) {
2683
+ return response;
2684
+ }
2685
+ return renderNext(remaining);
2686
+ };
2687
+ return renderNext(NOT_FOUND_PRIORITY);
2688
+ };
2689
+
2690
+ // src/svelte/pageHandler.ts
2691
+ var isRecord2 = (value) => typeof value === "object" && value !== null;
2692
+ var isGenericSvelteComponent = (value) => typeof value === "function" || isRecord2(value);
2693
+ var readHasIslands = (value) => {
2694
+ if (!isRecord2(value))
2695
+ return false;
2696
+ const hasIslands = value["__ABSOLUTE_PAGE_HAS_ISLANDS__"];
2697
+ return typeof hasIslands === "boolean" ? hasIslands : false;
2698
+ };
2699
+ var readDefaultExport = (value) => isRecord2(value) ? value.default : undefined;
2700
+ var buildDirtyResponse = (indexPath, props) => {
2701
+ const propsScript = `window.__ABS_SLOT_HYDRATION_PENDING__=true;window.__INITIAL_PROPS__=${JSON.stringify(props)};${indexPath ? `import(${JSON.stringify(indexPath)});` : ""}`;
2702
+ const dirtyFlag = "window.__SSR_DIRTY__=true;";
2703
+ const html = `<!DOCTYPE html><html><head></head><body><script>${propsScript}${dirtyFlag}</script></body></html>`;
2704
+ return new Response(html, {
2705
+ headers: { "Content-Type": "text/html" }
2706
+ });
2707
+ };
2708
+ var primeSvelteStream = async (stream) => {
2709
+ const reader = stream.getReader();
2710
+ const firstChunk = await reader.read();
2711
+ return { firstChunk, reader };
2712
+ };
2713
+ var restorePrimedStream = (firstChunk, reader) => new ReadableStream({
2714
+ start(controller) {
2715
+ if (!firstChunk.done) {
2716
+ controller.enqueue(firstChunk.value);
2717
+ }
2718
+ if (firstChunk.done) {
2719
+ controller.close();
2720
+ return;
2721
+ }
2722
+ const pumpLoop = () => {
2723
+ reader.read().then(({ done, value }) => done ? controller.close() : (controller.enqueue(value), pumpLoop())).catch((err) => controller.error(err));
2724
+ };
2725
+ pumpLoop();
2726
+ }
2727
+ });
2728
+ var handleSveltePageRequest = async (input) => {
2729
+ const resolvedIndexPath = input.indexPath;
2730
+ const resolvedOptions = input;
2731
+ const resolvedPagePath = input.pagePath;
2732
+ const resolvedProps = input.props;
2733
+ if (isSsrCacheDirty("svelte")) {
2734
+ return buildDirtyResponse(resolvedIndexPath, resolvedProps);
2735
+ }
2736
+ try {
2737
+ const handlerCallsite = resolvedOptions?.collectStreamingSlots === true ? undefined : getCurrentRouteRegistrationCallsite() ?? captureStreamingSlotWarningCallsite();
2738
+ const renderPageResponse = async () => {
2739
+ const resolvePageComponent = async () => {
2740
+ const loadCompiledSourcePath = async (sourcePath) => {
2741
+ const compiledModulePath = await compileSvelteServerModule(sourcePath);
2742
+ const loadedModule = await import(compiledModulePath);
2743
+ const loadedComponent = readDefaultExport(loadedModule) ?? loadedModule;
2744
+ if (!isGenericSvelteComponent(loadedComponent)) {
2745
+ throw new Error(`Invalid compiled Svelte page module: ${sourcePath}`);
2746
+ }
2747
+ return {
2748
+ component: loadedComponent,
2749
+ hasIslands: readHasIslands(loadedModule)
2750
+ };
2751
+ };
2752
+ const importedPageModule = await import(resolvedPagePath);
2753
+ const importedPageComponent = readDefaultExport(importedPageModule) ?? importedPageModule;
2754
+ if (typeof importedPageComponent === "string" && importedPageComponent.endsWith(".svelte")) {
2755
+ return loadCompiledSourcePath(importedPageComponent);
2756
+ }
2757
+ if (!isGenericSvelteComponent(importedPageComponent)) {
2758
+ throw new Error(`Invalid Svelte page module: ${resolvedPagePath}`);
2759
+ }
2760
+ return {
2761
+ component: importedPageComponent,
2762
+ hasIslands: readHasIslands(importedPageModule)
2763
+ };
2764
+ };
2765
+ const { renderToReadableStream: renderToReadableStream2 } = await Promise.resolve().then(() => (init_renderToReadableStream(), exports_renderToReadableStream));
2766
+ const resolvedPage = await resolvePageComponent();
2767
+ const stream = await renderToReadableStream2(resolvedPage.component, resolvedProps, {
2768
+ bodyContent: resolvedOptions?.bodyContent,
2769
+ bootstrapScriptContent: `window.__ABS_SLOT_HYDRATION_PENDING__=true;window.__INITIAL_PROPS__=${JSON.stringify(resolvedProps)};${resolvedIndexPath ? `import(${JSON.stringify(resolvedIndexPath)});` : ""}`,
2770
+ headContent: resolvedOptions?.headContent
2771
+ });
2772
+ const htmlStream = injectIslandPageContextStream(stream, {
2773
+ hasIslands: resolvedPage.hasIslands ? true : undefined
2774
+ });
2775
+ const { firstChunk, reader } = await primeSvelteStream(htmlStream);
2776
+ return new Response(restorePrimedStream(firstChunk, reader), {
2777
+ headers: { "Content-Type": "text/html" }
2778
+ });
2779
+ };
2780
+ return await runWithStreamingSlotWarningScope(() => resolvedOptions?.collectStreamingSlots === true ? withRegisteredStreamingSlots(renderPageResponse, {
2781
+ ...resolvedOptions,
2782
+ runtimePlacement: resolvedOptions.runtimePlacement ?? "body"
2783
+ }) : renderPageResponse(), { handlerCallsite });
2784
+ } catch (error) {
2785
+ console.error("[SSR] Svelte render error:", error);
2786
+ const pageName = derivePageName(resolvedPagePath);
2787
+ const conventionResponse = await renderConventionError("svelte", pageName, error);
2788
+ if (conventionResponse)
2789
+ return conventionResponse;
2790
+ return new Response(ssrErrorPage("svelte", error), {
2791
+ headers: { "Content-Type": "text/html" },
2792
+ status: 500
2793
+ });
2794
+ }
2795
+ };
23
2796
  export {
24
2797
  handleSveltePageRequest
25
2798
  };
26
2799
 
27
- //# debugId=568793BD692A09F264756E2164756E21
2800
+ //# debugId=B8C8F2877A6C528964756E2164756E21
28
2801
  //# sourceMappingURL=server.js.map