@despia-native/kernel 0.0.0-coming-soon.0 → 0.3.0

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 (661) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +1414 -0
  3. package/README.md +16 -1
  4. package/dist/.dsx-build-stamp.json +7 -0
  5. package/dist/api-cohort.d.ts +27 -0
  6. package/dist/api-cohort.d.ts.map +1 -0
  7. package/dist/api-cohort.js +94 -0
  8. package/dist/api-cohort.js.map +1 -0
  9. package/dist/api.d.ts +454 -0
  10. package/dist/api.d.ts.map +1 -0
  11. package/dist/api.js +2442 -0
  12. package/dist/api.js.map +1 -0
  13. package/dist/app-consts.d.ts +10 -0
  14. package/dist/app-consts.d.ts.map +1 -0
  15. package/dist/app-consts.js +39 -0
  16. package/dist/app-consts.js.map +1 -0
  17. package/dist/app-update.d.ts +12 -0
  18. package/dist/app-update.d.ts.map +1 -0
  19. package/dist/app-update.js +32 -0
  20. package/dist/app-update.js.map +1 -0
  21. package/dist/aria.d.ts +152 -0
  22. package/dist/aria.d.ts.map +1 -0
  23. package/dist/aria.js +524 -0
  24. package/dist/aria.js.map +1 -0
  25. package/dist/audio-core.d.ts +260 -0
  26. package/dist/audio-core.d.ts.map +1 -0
  27. package/dist/audio-core.js +1440 -0
  28. package/dist/audio-core.js.map +1 -0
  29. package/dist/audio-edit.d.ts +100 -0
  30. package/dist/audio-edit.d.ts.map +1 -0
  31. package/dist/audio-edit.js +489 -0
  32. package/dist/audio-edit.js.map +1 -0
  33. package/dist/audio-mix.d.ts +84 -0
  34. package/dist/audio-mix.d.ts.map +1 -0
  35. package/dist/audio-mix.js +393 -0
  36. package/dist/audio-mix.js.map +1 -0
  37. package/dist/auth-proof.d.ts +145 -0
  38. package/dist/auth-proof.d.ts.map +1 -0
  39. package/dist/auth-proof.js +644 -0
  40. package/dist/auth-proof.js.map +1 -0
  41. package/dist/availability-explain.d.ts +3 -0
  42. package/dist/availability-explain.d.ts.map +1 -0
  43. package/dist/availability-explain.js +322 -0
  44. package/dist/availability-explain.js.map +1 -0
  45. package/dist/availability.d.ts +246 -0
  46. package/dist/availability.d.ts.map +1 -0
  47. package/dist/availability.js +615 -0
  48. package/dist/availability.js.map +1 -0
  49. package/dist/background.d.ts +116 -0
  50. package/dist/background.d.ts.map +1 -0
  51. package/dist/background.js +235 -0
  52. package/dist/background.js.map +1 -0
  53. package/dist/boot-tables-flag.d.ts +2 -0
  54. package/dist/boot-tables-flag.d.ts.map +1 -0
  55. package/dist/boot-tables-flag.js +16 -0
  56. package/dist/boot-tables-flag.js.map +1 -0
  57. package/dist/boot-tables.d.ts +40 -0
  58. package/dist/boot-tables.d.ts.map +1 -0
  59. package/dist/boot-tables.js +102 -0
  60. package/dist/boot-tables.js.map +1 -0
  61. package/dist/border-edges.d.ts +5 -0
  62. package/dist/border-edges.d.ts.map +1 -0
  63. package/dist/border-edges.js +47 -0
  64. package/dist/border-edges.js.map +1 -0
  65. package/dist/bus.d.ts +1203 -0
  66. package/dist/bus.d.ts.map +1 -0
  67. package/dist/bus.js +2647 -0
  68. package/dist/bus.js.map +1 -0
  69. package/dist/calendar-core.d.ts +143 -0
  70. package/dist/calendar-core.d.ts.map +1 -0
  71. package/dist/calendar-core.js +372 -0
  72. package/dist/calendar-core.js.map +1 -0
  73. package/dist/call-value.d.ts +16 -0
  74. package/dist/call-value.d.ts.map +1 -0
  75. package/dist/call-value.js +54 -0
  76. package/dist/call-value.js.map +1 -0
  77. package/dist/camera-core.d.ts +222 -0
  78. package/dist/camera-core.d.ts.map +1 -0
  79. package/dist/camera-core.js +980 -0
  80. package/dist/camera-core.js.map +1 -0
  81. package/dist/canvas-core.d.ts +404 -0
  82. package/dist/canvas-core.d.ts.map +1 -0
  83. package/dist/canvas-core.js +2186 -0
  84. package/dist/canvas-core.js.map +1 -0
  85. package/dist/capture-core.d.ts +74 -0
  86. package/dist/capture-core.d.ts.map +1 -0
  87. package/dist/capture-core.js +158 -0
  88. package/dist/capture-core.js.map +1 -0
  89. package/dist/compile/codegen.d.ts +146 -0
  90. package/dist/compile/codegen.d.ts.map +1 -0
  91. package/dist/compile/codegen.js +1949 -0
  92. package/dist/compile/codegen.js.map +1 -0
  93. package/dist/compile/jstier.d.ts +44 -0
  94. package/dist/compile/jstier.d.ts.map +1 -0
  95. package/dist/compile/jstier.js +181 -0
  96. package/dist/compile/jstier.js.map +1 -0
  97. package/dist/compile/tier-door.d.ts +41 -0
  98. package/dist/compile/tier-door.d.ts.map +1 -0
  99. package/dist/compile/tier-door.js +167 -0
  100. package/dist/compile/tier-door.js.map +1 -0
  101. package/dist/compile/tier-realm.d.ts +49 -0
  102. package/dist/compile/tier-realm.d.ts.map +1 -0
  103. package/dist/compile/tier-realm.js +368 -0
  104. package/dist/compile/tier-realm.js.map +1 -0
  105. package/dist/compile/tier.d.ts +23 -0
  106. package/dist/compile/tier.d.ts.map +1 -0
  107. package/dist/compile/tier.js +157 -0
  108. package/dist/compile/tier.js.map +1 -0
  109. package/dist/compose-core.d.ts +86 -0
  110. package/dist/compose-core.d.ts.map +1 -0
  111. package/dist/compose-core.js +112 -0
  112. package/dist/compose-core.js.map +1 -0
  113. package/dist/config-validate.d.ts +31 -0
  114. package/dist/config-validate.d.ts.map +1 -0
  115. package/dist/config-validate.js +147 -0
  116. package/dist/config-validate.js.map +1 -0
  117. package/dist/config-values.d.ts +106 -0
  118. package/dist/config-values.d.ts.map +1 -0
  119. package/dist/config-values.js +340 -0
  120. package/dist/config-values.js.map +1 -0
  121. package/dist/contacts-core.d.ts +127 -0
  122. package/dist/contacts-core.d.ts.map +1 -0
  123. package/dist/contacts-core.js +211 -0
  124. package/dist/contacts-core.js.map +1 -0
  125. package/dist/content-transition.d.ts +58 -0
  126. package/dist/content-transition.d.ts.map +1 -0
  127. package/dist/content-transition.js +94 -0
  128. package/dist/content-transition.js.map +1 -0
  129. package/dist/controls-core.d.ts +227 -0
  130. package/dist/controls-core.d.ts.map +1 -0
  131. package/dist/controls-core.js +652 -0
  132. package/dist/controls-core.js.map +1 -0
  133. package/dist/cookies.d.ts +78 -0
  134. package/dist/cookies.d.ts.map +1 -0
  135. package/dist/cookies.js +265 -0
  136. package/dist/cookies.js.map +1 -0
  137. package/dist/corner-shape-core.d.ts +69 -0
  138. package/dist/corner-shape-core.d.ts.map +1 -0
  139. package/dist/corner-shape-core.js +261 -0
  140. package/dist/corner-shape-core.js.map +1 -0
  141. package/dist/crypto-core.d.ts +57 -0
  142. package/dist/crypto-core.d.ts.map +1 -0
  143. package/dist/crypto-core.js +128 -0
  144. package/dist/crypto-core.js.map +1 -0
  145. package/dist/dataviz.d.ts +436 -0
  146. package/dist/dataviz.d.ts.map +1 -0
  147. package/dist/dataviz.js +956 -0
  148. package/dist/dataviz.js.map +1 -0
  149. package/dist/debug.d.ts +293 -0
  150. package/dist/debug.d.ts.map +1 -0
  151. package/dist/debug.js +767 -0
  152. package/dist/debug.js.map +1 -0
  153. package/dist/device-ownership.d.ts +50 -0
  154. package/dist/device-ownership.d.ts.map +1 -0
  155. package/dist/device-ownership.js +105 -0
  156. package/dist/device-ownership.js.map +1 -0
  157. package/dist/effects.d.ts +86 -0
  158. package/dist/effects.d.ts.map +1 -0
  159. package/dist/effects.js +98 -0
  160. package/dist/effects.js.map +1 -0
  161. package/dist/element.d.ts +108 -0
  162. package/dist/element.d.ts.map +1 -0
  163. package/dist/element.js +63 -0
  164. package/dist/element.js.map +1 -0
  165. package/dist/file-watch.d.ts +16 -0
  166. package/dist/file-watch.d.ts.map +1 -0
  167. package/dist/file-watch.js +49 -0
  168. package/dist/file-watch.js.map +1 -0
  169. package/dist/filepaths.d.ts +72 -0
  170. package/dist/filepaths.d.ts.map +1 -0
  171. package/dist/filepaths.js +271 -0
  172. package/dist/filepaths.js.map +1 -0
  173. package/dist/film.d.ts +264 -0
  174. package/dist/film.d.ts.map +1 -0
  175. package/dist/film.js +313 -0
  176. package/dist/film.js.map +1 -0
  177. package/dist/fonts.d.ts +66 -0
  178. package/dist/fonts.d.ts.map +1 -0
  179. package/dist/fonts.js +135 -0
  180. package/dist/fonts.js.map +1 -0
  181. package/dist/forms.d.ts +191 -0
  182. package/dist/forms.d.ts.map +1 -0
  183. package/dist/forms.js +663 -0
  184. package/dist/forms.js.map +1 -0
  185. package/dist/geo.d.ts +289 -0
  186. package/dist/geo.d.ts.map +1 -0
  187. package/dist/geo.js +460 -0
  188. package/dist/geo.js.map +1 -0
  189. package/dist/handler-announce.d.ts +46 -0
  190. package/dist/handler-announce.d.ts.map +1 -0
  191. package/dist/handler-announce.js +96 -0
  192. package/dist/handler-announce.js.map +1 -0
  193. package/dist/handoff.d.ts +71 -0
  194. package/dist/handoff.d.ts.map +1 -0
  195. package/dist/handoff.js +250 -0
  196. package/dist/handoff.js.map +1 -0
  197. package/dist/identity-durability.d.ts +76 -0
  198. package/dist/identity-durability.d.ts.map +1 -0
  199. package/dist/identity-durability.js +150 -0
  200. package/dist/identity-durability.js.map +1 -0
  201. package/dist/image-core.d.ts +240 -0
  202. package/dist/image-core.d.ts.map +1 -0
  203. package/dist/image-core.js +618 -0
  204. package/dist/image-core.js.map +1 -0
  205. package/dist/image-schemes.d.ts +10 -0
  206. package/dist/image-schemes.d.ts.map +1 -0
  207. package/dist/image-schemes.js +28 -0
  208. package/dist/image-schemes.js.map +1 -0
  209. package/dist/index.d.ts +143 -0
  210. package/dist/index.d.ts.map +1 -0
  211. package/dist/index.js +299 -0
  212. package/dist/index.js.map +1 -0
  213. package/dist/ink-core.d.ts +53 -0
  214. package/dist/ink-core.d.ts.map +1 -0
  215. package/dist/ink-core.js +119 -0
  216. package/dist/ink-core.js.map +1 -0
  217. package/dist/input.d.ts +148 -0
  218. package/dist/input.d.ts.map +1 -0
  219. package/dist/input.js +358 -0
  220. package/dist/input.js.map +1 -0
  221. package/dist/integrity.d.ts +63 -0
  222. package/dist/integrity.d.ts.map +1 -0
  223. package/dist/integrity.js +150 -0
  224. package/dist/integrity.js.map +1 -0
  225. package/dist/intents.d.ts +95 -0
  226. package/dist/intents.d.ts.map +1 -0
  227. package/dist/intents.js +282 -0
  228. package/dist/intents.js.map +1 -0
  229. package/dist/interpolate-core.d.ts +37 -0
  230. package/dist/interpolate-core.d.ts.map +1 -0
  231. package/dist/interpolate-core.js +443 -0
  232. package/dist/interpolate-core.js.map +1 -0
  233. package/dist/jse/color.d.ts +12 -0
  234. package/dist/jse/color.d.ts.map +1 -0
  235. package/dist/jse/color.js +196 -0
  236. package/dist/jse/color.js.map +1 -0
  237. package/dist/jse/core.d.ts +54 -0
  238. package/dist/jse/core.d.ts.map +1 -0
  239. package/dist/jse/core.js +1519 -0
  240. package/dist/jse/core.js.map +1 -0
  241. package/dist/jse/dispatch.d.ts +28 -0
  242. package/dist/jse/dispatch.d.ts.map +1 -0
  243. package/dist/jse/dispatch.js +116 -0
  244. package/dist/jse/dispatch.js.map +1 -0
  245. package/dist/jse/highlight-grammar.d.ts +15 -0
  246. package/dist/jse/highlight-grammar.d.ts.map +1 -0
  247. package/dist/jse/highlight-grammar.js +161 -0
  248. package/dist/jse/highlight-grammar.js.map +1 -0
  249. package/dist/jse/highlight-grammars.generated.d.ts +2 -0
  250. package/dist/jse/highlight-grammars.generated.d.ts.map +1 -0
  251. package/dist/jse/highlight-grammars.generated.js +4 -0
  252. package/dist/jse/highlight-grammars.generated.js.map +1 -0
  253. package/dist/jse/highlight.d.ts +37 -0
  254. package/dist/jse/highlight.d.ts.map +1 -0
  255. package/dist/jse/highlight.js +323 -0
  256. package/dist/jse/highlight.js.map +1 -0
  257. package/dist/jse/jse.d.ts +674 -0
  258. package/dist/jse/jse.d.ts.map +1 -0
  259. package/dist/jse/jse.js +5841 -0
  260. package/dist/jse/jse.js.map +1 -0
  261. package/dist/jse/pathmatch.d.ts +10 -0
  262. package/dist/jse/pathmatch.d.ts.map +1 -0
  263. package/dist/jse/pathmatch.js +73 -0
  264. package/dist/jse/pathmatch.js.map +1 -0
  265. package/dist/jse/regex.d.ts +33 -0
  266. package/dist/jse/regex.d.ts.map +1 -0
  267. package/dist/jse/regex.js +375 -0
  268. package/dist/jse/regex.js.map +1 -0
  269. package/dist/jse/stdlib.d.ts +8 -0
  270. package/dist/jse/stdlib.d.ts.map +1 -0
  271. package/dist/jse/stdlib.js +765 -0
  272. package/dist/jse/stdlib.js.map +1 -0
  273. package/dist/jse/tokens.d.ts +102 -0
  274. package/dist/jse/tokens.d.ts.map +1 -0
  275. package/dist/jse/tokens.js +982 -0
  276. package/dist/jse/tokens.js.map +1 -0
  277. package/dist/jse/values.d.ts +206 -0
  278. package/dist/jse/values.d.ts.map +1 -0
  279. package/dist/jse/values.js +846 -0
  280. package/dist/jse/values.js.map +1 -0
  281. package/dist/keyboard.d.ts +196 -0
  282. package/dist/keyboard.d.ts.map +1 -0
  283. package/dist/keyboard.js +186 -0
  284. package/dist/keyboard.js.map +1 -0
  285. package/dist/label-choices.d.ts +3 -0
  286. package/dist/label-choices.d.ts.map +1 -0
  287. package/dist/label-choices.js +168 -0
  288. package/dist/label-choices.js.map +1 -0
  289. package/dist/language.d.ts +33 -0
  290. package/dist/language.d.ts.map +1 -0
  291. package/dist/language.js +50 -0
  292. package/dist/language.js.map +1 -0
  293. package/dist/length-units.d.ts +30 -0
  294. package/dist/length-units.d.ts.map +1 -0
  295. package/dist/length-units.js +83 -0
  296. package/dist/length-units.js.map +1 -0
  297. package/dist/lightsensor.d.ts +48 -0
  298. package/dist/lightsensor.d.ts.map +1 -0
  299. package/dist/lightsensor.js +97 -0
  300. package/dist/lightsensor.js.map +1 -0
  301. package/dist/link-refresh.d.ts +27 -0
  302. package/dist/link-refresh.d.ts.map +1 -0
  303. package/dist/link-refresh.js +166 -0
  304. package/dist/link-refresh.js.map +1 -0
  305. package/dist/link.d.ts +57 -0
  306. package/dist/link.d.ts.map +1 -0
  307. package/dist/link.js +333 -0
  308. package/dist/link.js.map +1 -0
  309. package/dist/linkpreview.d.ts +114 -0
  310. package/dist/linkpreview.d.ts.map +1 -0
  311. package/dist/linkpreview.js +439 -0
  312. package/dist/linkpreview.js.map +1 -0
  313. package/dist/list-presence.d.ts +32 -0
  314. package/dist/list-presence.d.ts.map +1 -0
  315. package/dist/list-presence.js +48 -0
  316. package/dist/list-presence.js.map +1 -0
  317. package/dist/live-stream.d.ts +27 -0
  318. package/dist/live-stream.d.ts.map +1 -0
  319. package/dist/live-stream.js +274 -0
  320. package/dist/live-stream.js.map +1 -0
  321. package/dist/livelogs.d.ts +134 -0
  322. package/dist/livelogs.d.ts.map +1 -0
  323. package/dist/livelogs.js +409 -0
  324. package/dist/livelogs.js.map +1 -0
  325. package/dist/logs.d.ts +80 -0
  326. package/dist/logs.d.ts.map +1 -0
  327. package/dist/logs.js +206 -0
  328. package/dist/logs.js.map +1 -0
  329. package/dist/mcp/apps.d.ts +82 -0
  330. package/dist/mcp/apps.d.ts.map +1 -0
  331. package/dist/mcp/apps.js +219 -0
  332. package/dist/mcp/apps.js.map +1 -0
  333. package/dist/mcp/entities.d.ts +25 -0
  334. package/dist/mcp/entities.d.ts.map +1 -0
  335. package/dist/mcp/entities.js +71 -0
  336. package/dist/mcp/entities.js.map +1 -0
  337. package/dist/mcp/result.d.ts +73 -0
  338. package/dist/mcp/result.d.ts.map +1 -0
  339. package/dist/mcp/result.js +119 -0
  340. package/dist/mcp/result.js.map +1 -0
  341. package/dist/mcp/webmcp.d.ts +162 -0
  342. package/dist/mcp/webmcp.d.ts.map +1 -0
  343. package/dist/mcp/webmcp.js +214 -0
  344. package/dist/mcp/webmcp.js.map +1 -0
  345. package/dist/mcp.d.ts +5 -0
  346. package/dist/mcp.d.ts.map +1 -0
  347. package/dist/mcp.js +14 -0
  348. package/dist/mcp.js.map +1 -0
  349. package/dist/media-core.d.ts +191 -0
  350. package/dist/media-core.d.ts.map +1 -0
  351. package/dist/media-core.js +446 -0
  352. package/dist/media-core.js.map +1 -0
  353. package/dist/media-timeline-core.d.ts +94 -0
  354. package/dist/media-timeline-core.d.ts.map +1 -0
  355. package/dist/media-timeline-core.js +620 -0
  356. package/dist/media-timeline-core.js.map +1 -0
  357. package/dist/message.d.ts +42 -0
  358. package/dist/message.d.ts.map +1 -0
  359. package/dist/message.js +582 -0
  360. package/dist/message.js.map +1 -0
  361. package/dist/missing-element.d.ts +29 -0
  362. package/dist/missing-element.d.ts.map +1 -0
  363. package/dist/missing-element.js +76 -0
  364. package/dist/missing-element.js.map +1 -0
  365. package/dist/motion-core.d.ts +160 -0
  366. package/dist/motion-core.d.ts.map +1 -0
  367. package/dist/motion-core.js +752 -0
  368. package/dist/motion-core.js.map +1 -0
  369. package/dist/motion-pose.d.ts +65 -0
  370. package/dist/motion-pose.d.ts.map +1 -0
  371. package/dist/motion-pose.js +143 -0
  372. package/dist/motion-pose.js.map +1 -0
  373. package/dist/motion.d.ts +132 -0
  374. package/dist/motion.d.ts.map +1 -0
  375. package/dist/motion.js +260 -0
  376. package/dist/motion.js.map +1 -0
  377. package/dist/mount-core.d.ts +203 -0
  378. package/dist/mount-core.d.ts.map +1 -0
  379. package/dist/mount-core.js +437 -0
  380. package/dist/mount-core.js.map +1 -0
  381. package/dist/net-core.d.ts +110 -0
  382. package/dist/net-core.d.ts.map +1 -0
  383. package/dist/net-core.js +225 -0
  384. package/dist/net-core.js.map +1 -0
  385. package/dist/notify.d.ts +399 -0
  386. package/dist/notify.d.ts.map +1 -0
  387. package/dist/notify.js +964 -0
  388. package/dist/notify.js.map +1 -0
  389. package/dist/orientation-binding.d.ts +39 -0
  390. package/dist/orientation-binding.d.ts.map +1 -0
  391. package/dist/orientation-binding.js +64 -0
  392. package/dist/orientation-binding.js.map +1 -0
  393. package/dist/orientation.d.ts +55 -0
  394. package/dist/orientation.d.ts.map +1 -0
  395. package/dist/orientation.js +89 -0
  396. package/dist/orientation.js.map +1 -0
  397. package/dist/ota.d.ts +52 -0
  398. package/dist/ota.d.ts.map +1 -0
  399. package/dist/ota.js +122 -0
  400. package/dist/ota.js.map +1 -0
  401. package/dist/passkeys.d.ts +91 -0
  402. package/dist/passkeys.d.ts.map +1 -0
  403. package/dist/passkeys.js +307 -0
  404. package/dist/passkeys.js.map +1 -0
  405. package/dist/payment.d.ts +85 -0
  406. package/dist/payment.d.ts.map +1 -0
  407. package/dist/payment.js +270 -0
  408. package/dist/payment.js.map +1 -0
  409. package/dist/pending-presenter.d.ts +31 -0
  410. package/dist/pending-presenter.d.ts.map +1 -0
  411. package/dist/pending-presenter.js +119 -0
  412. package/dist/pending-presenter.js.map +1 -0
  413. package/dist/permission-core.d.ts +59 -0
  414. package/dist/permission-core.d.ts.map +1 -0
  415. package/dist/permission-core.js +102 -0
  416. package/dist/permission-core.js.map +1 -0
  417. package/dist/persist.d.ts +169 -0
  418. package/dist/persist.d.ts.map +1 -0
  419. package/dist/persist.js +361 -0
  420. package/dist/persist.js.map +1 -0
  421. package/dist/phase-plan.d.ts +114 -0
  422. package/dist/phase-plan.d.ts.map +1 -0
  423. package/dist/phase-plan.js +837 -0
  424. package/dist/phase-plan.js.map +1 -0
  425. package/dist/playback-core.d.ts +64 -0
  426. package/dist/playback-core.d.ts.map +1 -0
  427. package/dist/playback-core.js +176 -0
  428. package/dist/playback-core.js.map +1 -0
  429. package/dist/player-sources.d.ts +12 -0
  430. package/dist/player-sources.d.ts.map +1 -0
  431. package/dist/player-sources.js +44 -0
  432. package/dist/player-sources.js.map +1 -0
  433. package/dist/proxy-denylist.d.ts +11 -0
  434. package/dist/proxy-denylist.d.ts.map +1 -0
  435. package/dist/proxy-denylist.js +44 -0
  436. package/dist/proxy-denylist.js.map +1 -0
  437. package/dist/public-config.d.ts +20 -0
  438. package/dist/public-config.d.ts.map +1 -0
  439. package/dist/public-config.js +109 -0
  440. package/dist/public-config.js.map +1 -0
  441. package/dist/qoe-core.d.ts +72 -0
  442. package/dist/qoe-core.d.ts.map +1 -0
  443. package/dist/qoe-core.js +113 -0
  444. package/dist/qoe-core.js.map +1 -0
  445. package/dist/reactive-request.d.ts +80 -0
  446. package/dist/reactive-request.d.ts.map +1 -0
  447. package/dist/reactive-request.js +192 -0
  448. package/dist/reactive-request.js.map +1 -0
  449. package/dist/read-cache.d.ts +129 -0
  450. package/dist/read-cache.d.ts.map +1 -0
  451. package/dist/read-cache.js +566 -0
  452. package/dist/read-cache.js.map +1 -0
  453. package/dist/recorder-core.d.ts +57 -0
  454. package/dist/recorder-core.d.ts.map +1 -0
  455. package/dist/recorder-core.js +136 -0
  456. package/dist/recorder-core.js.map +1 -0
  457. package/dist/ref.d.ts +41 -0
  458. package/dist/ref.d.ts.map +1 -0
  459. package/dist/ref.js +98 -0
  460. package/dist/ref.js.map +1 -0
  461. package/dist/refusal.d.ts +82 -0
  462. package/dist/refusal.d.ts.map +1 -0
  463. package/dist/refusal.js +218 -0
  464. package/dist/refusal.js.map +1 -0
  465. package/dist/region-insets.d.ts +61 -0
  466. package/dist/region-insets.d.ts.map +1 -0
  467. package/dist/region-insets.js +67 -0
  468. package/dist/region-insets.js.map +1 -0
  469. package/dist/rive-core.d.ts +323 -0
  470. package/dist/rive-core.d.ts.map +1 -0
  471. package/dist/rive-core.js +677 -0
  472. package/dist/rive-core.js.map +1 -0
  473. package/dist/runner.d.ts +595 -0
  474. package/dist/runner.d.ts.map +1 -0
  475. package/dist/runner.js +4094 -0
  476. package/dist/runner.js.map +1 -0
  477. package/dist/scene/a11y.d.ts +11 -0
  478. package/dist/scene/a11y.d.ts.map +1 -0
  479. package/dist/scene/a11y.js +67 -0
  480. package/dist/scene/a11y.js.map +1 -0
  481. package/dist/scene/anim.d.ts +149 -0
  482. package/dist/scene/anim.d.ts.map +1 -0
  483. package/dist/scene/anim.js +396 -0
  484. package/dist/scene/anim.js.map +1 -0
  485. package/dist/scene/bind.d.ts +33 -0
  486. package/dist/scene/bind.d.ts.map +1 -0
  487. package/dist/scene/bind.js +66 -0
  488. package/dist/scene/bind.js.map +1 -0
  489. package/dist/scene/collide.d.ts +56 -0
  490. package/dist/scene/collide.d.ts.map +1 -0
  491. package/dist/scene/collide.js +146 -0
  492. package/dist/scene/collide.js.map +1 -0
  493. package/dist/scene/frame.d.ts +22 -0
  494. package/dist/scene/frame.d.ts.map +1 -0
  495. package/dist/scene/frame.js +57 -0
  496. package/dist/scene/frame.js.map +1 -0
  497. package/dist/scene/gltf.d.ts +79 -0
  498. package/dist/scene/gltf.d.ts.map +1 -0
  499. package/dist/scene/gltf.js +409 -0
  500. package/dist/scene/gltf.js.map +1 -0
  501. package/dist/scene/ir.d.ts +293 -0
  502. package/dist/scene/ir.d.ts.map +1 -0
  503. package/dist/scene/ir.js +692 -0
  504. package/dist/scene/ir.js.map +1 -0
  505. package/dist/scene/math.d.ts +50 -0
  506. package/dist/scene/math.d.ts.map +1 -0
  507. package/dist/scene/math.js +180 -0
  508. package/dist/scene/math.js.map +1 -0
  509. package/dist/scene/orbit.d.ts +19 -0
  510. package/dist/scene/orbit.d.ts.map +1 -0
  511. package/dist/scene/orbit.js +60 -0
  512. package/dist/scene/orbit.js.map +1 -0
  513. package/dist/scene/physics.d.ts +228 -0
  514. package/dist/scene/physics.d.ts.map +1 -0
  515. package/dist/scene/physics.js +1500 -0
  516. package/dist/scene/physics.js.map +1 -0
  517. package/dist/scene/registry.d.ts +85 -0
  518. package/dist/scene/registry.d.ts.map +1 -0
  519. package/dist/scene/registry.js +75 -0
  520. package/dist/scene/registry.js.map +1 -0
  521. package/dist/scene/skin.d.ts +82 -0
  522. package/dist/scene/skin.d.ts.map +1 -0
  523. package/dist/scene/skin.js +351 -0
  524. package/dist/scene/skin.js.map +1 -0
  525. package/dist/scene/sprite.d.ts +36 -0
  526. package/dist/scene/sprite.d.ts.map +1 -0
  527. package/dist/scene/sprite.js +107 -0
  528. package/dist/scene/sprite.js.map +1 -0
  529. package/dist/scene/viewer.d.ts +96 -0
  530. package/dist/scene/viewer.d.ts.map +1 -0
  531. package/dist/scene/viewer.js +235 -0
  532. package/dist/scene/viewer.js.map +1 -0
  533. package/dist/scoped-slots.d.ts +9 -0
  534. package/dist/scoped-slots.d.ts.map +1 -0
  535. package/dist/scoped-slots.js +42 -0
  536. package/dist/scoped-slots.js.map +1 -0
  537. package/dist/screen.d.ts +109 -0
  538. package/dist/screen.d.ts.map +1 -0
  539. package/dist/screen.js +309 -0
  540. package/dist/screen.js.map +1 -0
  541. package/dist/scroll.d.ts +525 -0
  542. package/dist/scroll.d.ts.map +1 -0
  543. package/dist/scroll.js +1226 -0
  544. package/dist/scroll.js.map +1 -0
  545. package/dist/settings-plane.d.ts +58 -0
  546. package/dist/settings-plane.d.ts.map +1 -0
  547. package/dist/settings-plane.js +86 -0
  548. package/dist/settings-plane.js.map +1 -0
  549. package/dist/share-inbox.d.ts +56 -0
  550. package/dist/share-inbox.d.ts.map +1 -0
  551. package/dist/share-inbox.js +114 -0
  552. package/dist/share-inbox.js.map +1 -0
  553. package/dist/shared-transition.d.ts +152 -0
  554. package/dist/shared-transition.d.ts.map +1 -0
  555. package/dist/shared-transition.js +257 -0
  556. package/dist/shared-transition.js.map +1 -0
  557. package/dist/sheet-content-padding.d.ts +24 -0
  558. package/dist/sheet-content-padding.d.ts.map +1 -0
  559. package/dist/sheet-content-padding.js +32 -0
  560. package/dist/sheet-content-padding.js.map +1 -0
  561. package/dist/shot-devices.d.ts +36 -0
  562. package/dist/shot-devices.d.ts.map +1 -0
  563. package/dist/shot-devices.js +90 -0
  564. package/dist/shot-devices.js.map +1 -0
  565. package/dist/shot-guards.d.ts +100 -0
  566. package/dist/shot-guards.d.ts.map +1 -0
  567. package/dist/shot-guards.js +260 -0
  568. package/dist/shot-guards.js.map +1 -0
  569. package/dist/shot-scope.d.ts +140 -0
  570. package/dist/shot-scope.d.ts.map +1 -0
  571. package/dist/shot-scope.js +302 -0
  572. package/dist/shot-scope.js.map +1 -0
  573. package/dist/slot-partition.d.ts +9 -0
  574. package/dist/slot-partition.d.ts.map +1 -0
  575. package/dist/slot-partition.js +38 -0
  576. package/dist/slot-partition.js.map +1 -0
  577. package/dist/snackbar.d.ts +165 -0
  578. package/dist/snackbar.d.ts.map +1 -0
  579. package/dist/snackbar.js +220 -0
  580. package/dist/snackbar.js.map +1 -0
  581. package/dist/socket.d.ts +96 -0
  582. package/dist/socket.d.ts.map +1 -0
  583. package/dist/socket.js +370 -0
  584. package/dist/socket.js.map +1 -0
  585. package/dist/spotlight.d.ts +77 -0
  586. package/dist/spotlight.d.ts.map +1 -0
  587. package/dist/spotlight.js +174 -0
  588. package/dist/spotlight.js.map +1 -0
  589. package/dist/state-primitive.d.ts +37 -0
  590. package/dist/state-primitive.d.ts.map +1 -0
  591. package/dist/state-primitive.js +91 -0
  592. package/dist/state-primitive.js.map +1 -0
  593. package/dist/store-query.d.ts +25 -0
  594. package/dist/store-query.d.ts.map +1 -0
  595. package/dist/store-query.js +88 -0
  596. package/dist/store-query.js.map +1 -0
  597. package/dist/store-value.d.ts +48 -0
  598. package/dist/store-value.d.ts.map +1 -0
  599. package/dist/store-value.js +264 -0
  600. package/dist/store-value.js.map +1 -0
  601. package/dist/store-versioning.d.ts +70 -0
  602. package/dist/store-versioning.d.ts.map +1 -0
  603. package/dist/store-versioning.js +188 -0
  604. package/dist/store-versioning.js.map +1 -0
  605. package/dist/store.d.ts +282 -0
  606. package/dist/store.d.ts.map +1 -0
  607. package/dist/store.js +1144 -0
  608. package/dist/store.js.map +1 -0
  609. package/dist/strings.d.ts +141 -0
  610. package/dist/strings.d.ts.map +1 -0
  611. package/dist/strings.js +581 -0
  612. package/dist/strings.js.map +1 -0
  613. package/dist/telemetry.d.ts +95 -0
  614. package/dist/telemetry.d.ts.map +1 -0
  615. package/dist/telemetry.js +255 -0
  616. package/dist/telemetry.js.map +1 -0
  617. package/dist/transform-core.d.ts +228 -0
  618. package/dist/transform-core.d.ts.map +1 -0
  619. package/dist/transform-core.js +921 -0
  620. package/dist/transform-core.js.map +1 -0
  621. package/dist/transition-core.d.ts +58 -0
  622. package/dist/transition-core.d.ts.map +1 -0
  623. package/dist/transition-core.js +352 -0
  624. package/dist/transition-core.js.map +1 -0
  625. package/dist/trim-trailing.d.ts +3 -0
  626. package/dist/trim-trailing.d.ts.map +1 -0
  627. package/dist/trim-trailing.js +14 -0
  628. package/dist/trim-trailing.js.map +1 -0
  629. package/dist/upload.d.ts +51 -0
  630. package/dist/upload.d.ts.map +1 -0
  631. package/dist/upload.js +68 -0
  632. package/dist/upload.js.map +1 -0
  633. package/dist/vendor-face.d.ts +44 -0
  634. package/dist/vendor-face.d.ts.map +1 -0
  635. package/dist/vendor-face.js +80 -0
  636. package/dist/vendor-face.js.map +1 -0
  637. package/dist/vendor-session.d.ts +166 -0
  638. package/dist/vendor-session.d.ts.map +1 -0
  639. package/dist/vendor-session.js +423 -0
  640. package/dist/vendor-session.js.map +1 -0
  641. package/dist/vendor-surface.d.ts +290 -0
  642. package/dist/vendor-surface.d.ts.map +1 -0
  643. package/dist/vendor-surface.js +439 -0
  644. package/dist/vendor-surface.js.map +1 -0
  645. package/dist/version-rules.generated.d.ts +17 -0
  646. package/dist/version-rules.generated.d.ts.map +1 -0
  647. package/dist/version-rules.generated.js +99 -0
  648. package/dist/version-rules.generated.js.map +1 -0
  649. package/dist/view-transition-core.d.ts +99 -0
  650. package/dist/view-transition-core.d.ts.map +1 -0
  651. package/dist/view-transition-core.js +127 -0
  652. package/dist/view-transition-core.js.map +1 -0
  653. package/dist/view-transition-door.d.ts +26 -0
  654. package/dist/view-transition-door.d.ts.map +1 -0
  655. package/dist/view-transition-door.js +88 -0
  656. package/dist/view-transition-door.js.map +1 -0
  657. package/dist/window-identity.d.ts +3 -0
  658. package/dist/window-identity.d.ts.map +1 -0
  659. package/dist/window-identity.js +27 -0
  660. package/dist/window-identity.js.map +1 -0
  661. package/package.json +141 -2
package/dist/api.js ADDED
@@ -0,0 +1,2442 @@
1
+ //
2
+ // api.ts - the `<api>` block runtime, web half (/web/05). Declarative, auto-fetched,
3
+ // reactive data. The cross-platform LAW lives in OpenSource/Conformance/api/
4
+ // api-blocks.json — this file, ApiBlock.kt (Android) and ApiBlock.swift (iOS) all
5
+ // run the same fixtures:
6
+ //
7
+ // • reserved paths <as>.data/.loading/.refreshing/.error{status,message,body}/.fetchedAt
8
+ // • refetch when the MATERIALIZED request changes (watchKey-compared — the read set
9
+ // is tracked here via the signal graph; the native twins re-materialize per store
10
+ // publish and compare, same observable law)
11
+ // • auto defaults true for GET (a formula); debounce → abort-stale → refetch
12
+ // • network errors retry; http errors do not; stale data survives a failed refetch
13
+ // • cache: no-store (default) · max-age(d) · swr(fresh, stale) — per-surface,
14
+ // bounded, and keyed by method+url+headers+body+expect+cookie identity;
15
+ // a successful non-GET drops the entries of the readers that declared its resource
16
+ // • events: on:success / on:error / on:message / on:progress (streamed chunks
17
+ // append to data; progress entries publish <as>.progress before the settle)
18
+ // • TARGETED INVALIDATION: a successful non-GET refetches only the GET blocks that
19
+ // declared a dependency on its resource (the url's literal path prefix, or an
20
+ // explicit `depends`); a block that declares nothing keeps the broad refetch and
21
+ // is counted in apiInvalidationDiagnostics()
22
+ // • THE DEPENDENCY GRAPH (/web/11): `needs=` + expression edges make a DAG per
23
+ // component scope; a gated block publishes `<as>.status = "waiting"` +
24
+ // `<as>.blockedBy` and never fires with a hole in its inputs
25
+ // • declared transport controls (networking.md N2): stream · timeout · redirect ·
26
+ // encode (json|text|form|multipart) · via="server" (the proxy route)
27
+ //
28
+ // DOM-free by law: the same block runs in the browser, Node (SSR) and tests.
29
+ //
30
+ import { isStateIdentifier, readCookiePartition, STATE_PATH_LIMITS, } from "./store.js";
31
+ import { JSE, JSESeams } from "./jse/jse.js";
32
+ import { NSNull, isDict, number, string, truthy, safeInt, watchKey } from "./jse/values.js";
33
+ import { ReactiveRequest } from "./reactive-request.js";
34
+ import { joinApiCohort, arriveApiCohort, leaveApiCohort } from "./api-cohort.js";
35
+ import { base64Encode, base64Decode } from "./jse/core.js";
36
+ import { RunnerFetchSeam } from "./runner.js";
37
+ import { LIVE_MEDIA_TYPE, LiveStreamError, runLiveStream } from "./live-stream.js";
38
+ /** doc 05 `via="server"` / doc 13 "the embed knows its home origin": the absolute base the
39
+ * proxy route resolves against. "" = same origin (the browser default); the native hosts
40
+ * and the embed loader set their configured web origin here. */
41
+ export const ApiServerOrigin = { base: "" };
42
+ /** proposals/realtime.md R1: the reconnect ladder's one nondeterministic input. The ladder is the
43
+ * WebSocket module's, byte for byte: `min(2^attempt, 30)` seconds with FULL jitter
44
+ * (Mandatory/WebSocket web/index.js backoffDelayMs), floored by the server's declared `retry:`. A
45
+ * runner pins `random` so a reconnect waits exactly the declared floor. */
46
+ export const ApiStreamClock = { random: Math.random };
47
+ /** realtime.md R1.2: when does a LIVE stream's answer mean "come back"? A clean EOF, a drop, and a
48
+ * network failure do, a TIMEOUT included (R1.2 names the terminals, and a connect that never
49
+ * answers is the network failing: a phone in a lift gets a black hole, not a reset). HTTP 204
50
+ * (the EventSource rule), a 4xx other than 408 and 429, and any other refusal this process made
51
+ * itself (`status: -2`) do not. Twin: ApiBlock.kt `liveShouldReconnect`. */
52
+ function liveShouldReconnect(res) {
53
+ const status = number(res["status"]) ?? 0;
54
+ if (truthy(res["dropped"]))
55
+ return true;
56
+ if (status === 0)
57
+ return true;
58
+ if (status === 204)
59
+ return false;
60
+ if (status >= 400 && status < 500)
61
+ return status === 408 || status === 429;
62
+ if (status >= 500)
63
+ return true;
64
+ if (status < 0)
65
+ return string(res["error"] ?? "") === "timeout";
66
+ return truthy(res["ok"]) && Array.isArray(res["stream"]);
67
+ }
68
+ function abortableSleep(ms, signal) {
69
+ return new Promise((resolve) => {
70
+ if (signal?.aborted === true) {
71
+ resolve(false);
72
+ return;
73
+ }
74
+ const timer = setTimeout(() => { signal?.removeEventListener("abort", onAbort); resolve(true); }, ms);
75
+ const onAbort = () => { clearTimeout(timer); resolve(false); };
76
+ signal?.addEventListener("abort", onAbort, { once: true });
77
+ });
78
+ }
79
+ const API_CACHE_LIMIT = 256;
80
+ let apiCaches = new WeakMap();
81
+ export function clearApiCache() {
82
+ // WeakMap intentionally has no clear(): replace the registry. Existing blocks
83
+ // look the cache up per operation, so the reset takes effect immediately.
84
+ apiCaches = new WeakMap();
85
+ inflightReads = new WeakMap();
86
+ resetApiInvalidationDiagnostics();
87
+ }
88
+ let inflightReads = new WeakMap();
89
+ function sharesInFlight(req) {
90
+ const method = string(req["method"] ?? "GET").toUpperCase();
91
+ return (method === "GET" || method === "HEAD") && req["stream"] === undefined && req["timeout"] === undefined;
92
+ }
93
+ function sharedRead(store, key, signal, first) {
94
+ let reads = inflightReads.get(store);
95
+ if (reads === undefined) {
96
+ reads = new Map();
97
+ inflightReads.set(store, reads);
98
+ }
99
+ const table = reads;
100
+ const existing = table.get(key);
101
+ if (existing === undefined) {
102
+ // THE FIRST READER owns the request and its stream callbacks (a response the server answers
103
+ // as an event stream is delivered to it as it arrives), and awaits it with no extra hop. Its
104
+ // abort leaves the request running while anyone else has joined it.
105
+ const controller = new AbortController();
106
+ const created = { answer: first(controller.signal), controller, joiners: 1 };
107
+ table.set(key, created);
108
+ const release = () => { if (table.get(key) === created)
109
+ table.delete(key); };
110
+ created.answer.then(release, release);
111
+ const leave = () => {
112
+ created.joiners -= 1;
113
+ if (created.joiners === 0) {
114
+ release();
115
+ controller.abort();
116
+ }
117
+ };
118
+ if (signal !== null) {
119
+ if (signal.aborted)
120
+ leave();
121
+ else
122
+ signal.addEventListener("abort", leave, { once: true });
123
+ }
124
+ return created.answer;
125
+ }
126
+ const joined = existing;
127
+ joined.joiners += 1;
128
+ return new Promise((resolve) => {
129
+ let settled = false;
130
+ const leave = () => {
131
+ if (settled)
132
+ return;
133
+ settled = true;
134
+ joined.joiners -= 1;
135
+ if (joined.joiners === 0) {
136
+ if (table.get(key) === joined)
137
+ table.delete(key);
138
+ joined.controller.abort();
139
+ }
140
+ resolve({ ok: false, status: 0, data: null, aborted: true });
141
+ };
142
+ if (signal?.aborted === true) {
143
+ leave();
144
+ return;
145
+ }
146
+ signal?.addEventListener("abort", leave, { once: true });
147
+ void joined.answer.then((out) => {
148
+ if (settled)
149
+ return;
150
+ settled = true;
151
+ joined.joiners -= 1;
152
+ signal?.removeEventListener("abort", leave);
153
+ resolve({ ...out });
154
+ }, () => { if (!settled) {
155
+ settled = true;
156
+ resolve({ ok: false, status: 0, data: null });
157
+ } });
158
+ });
159
+ }
160
+ /** Every surface that holds a cache or a live reader, weakly, so `dsx.cache.invalidate` reaches
161
+ * them all at once (C4) and a surface that is gone is simply not there. */
162
+ const knownSurfaces = new Set();
163
+ const knownSurface = new WeakSet();
164
+ function noteSurface(store) {
165
+ if (!(globalThis.__DSX_OPTIONAL_API_INVALIDATION__ !== false))
166
+ return;
167
+ if (knownSurface.has(store))
168
+ return;
169
+ knownSurface.add(store);
170
+ knownSurfaces.add(new WeakRef(store));
171
+ }
172
+ function surfaceCache(store) {
173
+ let cache = apiCaches.get(store);
174
+ if (cache === undefined) {
175
+ cache = new Map();
176
+ apiCaches.set(store, cache);
177
+ noteSurface(store);
178
+ }
179
+ return cache;
180
+ }
181
+ function cacheGet(store, key) {
182
+ if (!(globalThis.__DSX_OPTIONAL_API_CACHE__ !== false))
183
+ return undefined;
184
+ const cache = surfaceCache(store);
185
+ const entry = cache.get(key);
186
+ if (entry !== undefined) {
187
+ // Map insertion order is the LRU ledger; a hit becomes newest.
188
+ cache.delete(key);
189
+ cache.set(key, entry);
190
+ }
191
+ return entry;
192
+ }
193
+ function cachePut(store, key, entry) {
194
+ if (!(globalThis.__DSX_OPTIONAL_API_CACHE__ !== false))
195
+ return;
196
+ const cache = surfaceCache(store);
197
+ cache.delete(key);
198
+ cache.set(key, entry);
199
+ while (cache.size > API_CACHE_LIMIT) {
200
+ const oldest = cache.keys().next().value;
201
+ if (oldest === undefined)
202
+ break;
203
+ cache.delete(oldest);
204
+ }
205
+ }
206
+ /** A write landed. Drop the entries whose reader declared a matching resource; an
207
+ * entry with NO declaration is dropped by every write, and a write that could not
208
+ * name what it changed drops all of them. */
209
+ function invalidateSurfaceCache(store, writeResource) {
210
+ if (!(globalThis.__DSX_OPTIONAL_API_CACHE__ !== false))
211
+ return;
212
+ if (writeResource === null) {
213
+ apiCaches.delete(store);
214
+ return;
215
+ }
216
+ const cache = apiCaches.get(store);
217
+ if (cache === undefined)
218
+ return;
219
+ for (const [key, entry] of [...cache]) {
220
+ if (entry.resource === null || apiResourceMatches(entry.resource, writeResource))
221
+ cache.delete(key);
222
+ }
223
+ }
224
+ // ── the resource declaration (the targeted-invalidation law) ──────────────────────────
225
+ //
226
+ // THE LAW: a successful non-GET refetches only the GET blocks that declare a dependency
227
+ // on its resource. A block declares what it READS, a write names what it CHANGED, and the
228
+ // invalidation is a MATCH between the two. A block that declares nothing keeps the broad
229
+ // refetch, so nothing silently stops updating, and the broad path is counted in the
230
+ // diagnostics below so an author can see what it costs.
231
+ //
232
+ // The declaration is the `depends` attribute when the author wrote one, and otherwise the
233
+ // LITERAL PATH PREFIX of the authored url: everything before the first `{{`, which is the
234
+ // part of the url the author actually fixed. `/api/orders/{{ dsx.variable.id }}` declares
235
+ // `/api/orders`; `{{ dsx.const.base }}/orders` declares NOTHING, because the author wrote
236
+ // no path at all, and that is exactly the block `depends` exists for.
237
+ /** the resource an `<api>` spec declares, or null when it declares none */
238
+ export function apiResourceKey(spec) {
239
+ const declared = (spec.depends ?? "").trim();
240
+ if (declared.length > 0)
241
+ return normalizeResource(declared, true);
242
+ return normalizeResource(spec.url ?? "", false);
243
+ }
244
+ function normalizeResource(text, explicit) {
245
+ const hole = explicit ? -1 : text.indexOf("{{");
246
+ const head = hole < 0 ? text : text.slice(0, hole);
247
+ let path = head;
248
+ const scheme = path.indexOf("://");
249
+ if (scheme >= 0) {
250
+ // the authority is not the resource: two hosts serving one path are one resource,
251
+ // and the extra refetch that costs is on the SAFE side of the law.
252
+ const slash = path.indexOf("/", scheme + 3);
253
+ path = slash < 0 ? "" : path.slice(slash);
254
+ }
255
+ const cut = path.search(/[?#]/);
256
+ if (cut >= 0)
257
+ path = path.slice(0, cut);
258
+ const segments = path.split("/").filter((s) => s.length > 0);
259
+ // a hole INSIDE the last literal segment (`/api/or{{ x }}`) leaves a partial word that
260
+ // the author never wrote as a resource, so it is not one.
261
+ if (hole >= 0 && cut < 0 && !path.endsWith("/") && segments.length > 0)
262
+ segments.pop();
263
+ if (segments.length === 0)
264
+ return explicit && head.trim().startsWith("/") ? "/" : null;
265
+ return "/" + segments.join("/");
266
+ }
267
+ /** Two declarations match when one CONTAINS the other, segment by segment. A write to
268
+ * `/api/orders` reaches a read of `/api/orders/12`, and a read of `/api/orders` is
269
+ * reached by a write to `/api/orders/12`. `/` is the whole API and matches everything. */
270
+ export function apiResourceMatches(read, write) {
271
+ if (read === write || read === "/" || write === "/")
272
+ return true;
273
+ return read.startsWith(write + "/") || write.startsWith(read + "/");
274
+ }
275
+ let apiDiagnostics = { targetedWrites: 0, broadWrites: 0, broadRefetches: 0, undeclared: new Set() };
276
+ export function apiInvalidationDiagnostics() {
277
+ return {
278
+ targetedWrites: apiDiagnostics.targetedWrites,
279
+ broadWrites: apiDiagnostics.broadWrites,
280
+ broadRefetches: apiDiagnostics.broadRefetches,
281
+ undeclaredBlocks: [...apiDiagnostics.undeclared].sort(),
282
+ };
283
+ }
284
+ export function resetApiInvalidationDiagnostics() {
285
+ apiDiagnostics = { targetedWrites: 0, broadWrites: 0, broadRefetches: 0, undeclared: new Set() };
286
+ }
287
+ /** The live readers of one surface. A GET block registers on mount and leaves on
288
+ * dispose, which is what lets a write reach exactly the blocks that declared it
289
+ * instead of poking a revision every block on the page reads. */
290
+ const apiReaders = new WeakMap();
291
+ function registerApiReader(store, block) {
292
+ if (!(globalThis.__DSX_OPTIONAL_API_INVALIDATION__ !== false))
293
+ return;
294
+ noteSurface(store);
295
+ let readers = apiReaders.get(store);
296
+ if (readers === undefined) {
297
+ readers = new Set();
298
+ apiReaders.set(store, readers);
299
+ }
300
+ readers.add(block);
301
+ }
302
+ function unregisterApiReader(store, block) {
303
+ if (!(globalThis.__DSX_OPTIONAL_API_INVALIDATION__ !== false))
304
+ return;
305
+ apiReaders.get(store)?.delete(block);
306
+ }
307
+ /** A successful non-GET landed on `writeResource` (null = it could not say). */
308
+ function notifyApiWrite(store, writeResource) {
309
+ if (!(globalThis.__DSX_OPTIONAL_API_INVALIDATION__ !== false))
310
+ return;
311
+ if (writeResource === null)
312
+ apiDiagnostics.broadWrites += 1;
313
+ else
314
+ apiDiagnostics.targetedWrites += 1;
315
+ invalidateSurfaceCache(store, writeResource);
316
+ const readers = apiReaders.get(store);
317
+ if (readers === undefined)
318
+ return;
319
+ for (const reader of [...readers]) {
320
+ const read = reader.resourceKey;
321
+ if (read === null || writeResource === null) {
322
+ apiDiagnostics.broadRefetches += 1;
323
+ reader.invalidatedByWrite();
324
+ continue;
325
+ }
326
+ if (apiResourceMatches(read, writeResource))
327
+ reader.invalidatedByWrite();
328
+ }
329
+ }
330
+ /** INVALIDATION IS AN ACTION (localization-and-caching.md C4; corpus api/api-blocks.json
331
+ * `cache-invalidate-*`): `dsx.cache.invalidate('/posts')` makes every entry tagged with that
332
+ * resource unreachable at once, in every live surface, and refetches the mounted readers that
333
+ * read it: the same match a write makes (`apiResourceMatches`), with the resource named by the
334
+ * author instead of a write's url. A reader whose url names no resource refetches, the safe side
335
+ * of the law. Not a write, so the write diagnostics are not counted. An argument that names no
336
+ * resource invalidates nothing. */
337
+ export function invalidateApiResource(resource) {
338
+ if (!(globalThis.__DSX_OPTIONAL_API_INVALIDATION__ !== false))
339
+ return;
340
+ const r = typeof resource === "string" ? normalizeResource(resource, true) : null;
341
+ if (r === null)
342
+ return;
343
+ for (const ref of [...knownSurfaces]) {
344
+ const store = ref.deref();
345
+ if (store === undefined) {
346
+ knownSurfaces.delete(ref);
347
+ continue;
348
+ }
349
+ invalidateSurfaceCache(store, r);
350
+ for (const reader of [...(apiReaders.get(store) ?? [])]) {
351
+ const read = reader.resourceKey;
352
+ if (read === null || apiResourceMatches(read, r))
353
+ reader.invalidatedByWrite();
354
+ }
355
+ }
356
+ }
357
+ if (globalThis.__DSX_OPTIONAL_API_INVALIDATION__ !== false)
358
+ JSESeams.cacheInvalidate = invalidateApiResource;
359
+ /** "60" / "60s" / "10m" / "2h" → ms */
360
+ function parseDuration(s) {
361
+ const m = /^\s*(\d+(?:\.\d+)?)\s*(?:(ms|s|m|h)\s*)?$/.exec(s);
362
+ if (m === null)
363
+ return 0;
364
+ const n = Number(m[1]);
365
+ switch (m[2] ?? "s") {
366
+ case "ms": return n;
367
+ case "m": return n * 60_000;
368
+ case "h": return n * 3_600_000;
369
+ default: return n * 1000;
370
+ }
371
+ }
372
+ /** THE CACHE GRAMMAR, exported for the one other reader that must agree with it: a route row's
373
+ * `cache` (server live.ts, proposals/localization-and-caching.md C3) takes the same words an
374
+ * `<api cache>` does, so a page and its data are declared in one vocabulary. */
375
+ export function parseCachePolicy(attr) { return parseCache(attr); }
376
+ function parseCache(attr) {
377
+ if (!(globalThis.__DSX_OPTIONAL_API_CACHE__ !== false))
378
+ return { kind: "no-store" };
379
+ if (attr === undefined || attr.trim() === "" || attr.trim() === "no-store")
380
+ return { kind: "no-store" };
381
+ const maxAge = /^max-age\(([^)]+)\)$/.exec(attr.trim());
382
+ if (maxAge !== null)
383
+ return { kind: "max-age", age: parseDuration(maxAge[1]) };
384
+ const swr = /^swr\(([^,)]+),([^)]+)\)$/.exec(attr.trim());
385
+ if (swr !== null)
386
+ return { kind: "swr", fresh: parseDuration(swr[1]), stale: parseDuration(swr[2]) };
387
+ return { kind: "no-store" };
388
+ }
389
+ /** Every `{{ … }}` hole of an interpolation template, in source order. The gate is
390
+ * per-HOLE, not per-path: `{{ filter || 'all' }}` is whole, so it never gates. */
391
+ function interpolationHoles(template) {
392
+ if (!template.includes("{{"))
393
+ return [];
394
+ const holes = [];
395
+ let idx = 0;
396
+ for (;;) {
397
+ const open = template.indexOf("{{", idx);
398
+ if (open < 0)
399
+ break;
400
+ const close = template.indexOf("}}", open + 2);
401
+ if (close < 0)
402
+ break;
403
+ holes.push(template.substring(open + 2, close));
404
+ idx = close + 2;
405
+ }
406
+ return holes;
407
+ }
408
+ const EXPR_KEYWORDS = new Set([
409
+ "true", "false", "null", "undefined", "new", "typeof", "in", "of", "return",
410
+ "if", "else", "function", "await", "void", "delete", "instanceof", "this",
411
+ ]);
412
+ /** Ambient planes are TYPED-ABSENT by law (durability P4): an absent const/env/route
413
+ * value interpolates empty and is NOT a hole waiting to be filled. Gating is for
414
+ * reactive scope — surface vars, component attributes, and other `<api>` blocks. */
415
+ const AMBIENT_ROOTS = new Set([
416
+ "global", "route", "cookie", "platform", "os", "env", "screen", "source", "app",
417
+ "query", "params", "path", "const",
418
+ ]);
419
+ // `api` joins the reactive heads with the read face (`dsx.api.<as>.data`): a hole that
420
+ // reads another block through it is the SAME graph edge the bare `<as>.data` spelling is.
421
+ const DSX_SCOPE_HEADS = new Set(["variable", "formula", "api", "item", "attribute", "element", "event", "action"]);
422
+ /** The dotted PATHS an expression reads. Conservative by construction: the result is
423
+ * only ever intersected with the sibling `as` names, or asked whether every path is
424
+ * ambient. String literals are skipped; `{ key: v }` keys are not paths. */
425
+ function expressionPaths(expr) {
426
+ const out = [];
427
+ const n = expr.length;
428
+ const isStart = (c) => (c >= "a" && c <= "z") || (c >= "A" && c <= "Z") || c === "_" || c === "$";
429
+ const isPart = (c) => isStart(c) || (c >= "0" && c <= "9");
430
+ let i = 0;
431
+ while (i < n) {
432
+ const c = expr[i];
433
+ if (c === '"' || c === "'" || c === "`") {
434
+ i += 1;
435
+ while (i < n && expr[i] !== c) {
436
+ if (expr[i] === "\\")
437
+ i += 1;
438
+ i += 1;
439
+ }
440
+ i += 1;
441
+ continue;
442
+ }
443
+ if (!isStart(c)) {
444
+ i += 1;
445
+ continue;
446
+ }
447
+ let j = i;
448
+ while (j < n && isPart(expr[j]))
449
+ j += 1;
450
+ let before = i - 1;
451
+ while (before >= 0 && (expr[before] === " " || expr[before] === "\t" || expr[before] === "\n"))
452
+ before -= 1;
453
+ let after = j;
454
+ while (after < n && (expr[after] === " " || expr[after] === "\t"))
455
+ after += 1;
456
+ const isMember = before >= 0 && expr[before] === ".";
457
+ const isObjectKey = expr[after] === ":" && expr[after + 1] !== ":";
458
+ if (isMember || isObjectKey || EXPR_KEYWORDS.has(expr.substring(i, j))) {
459
+ i = j;
460
+ continue;
461
+ }
462
+ let path = expr.substring(i, j);
463
+ let cursor = j;
464
+ for (;;) {
465
+ let dot = cursor;
466
+ while (dot < n && (expr[dot] === " " || expr[dot] === "\t"))
467
+ dot += 1;
468
+ if (expr[dot] !== "." || !isStart(expr[dot + 1] ?? ""))
469
+ break;
470
+ let end = dot + 1;
471
+ while (end < n && isPart(expr[end]))
472
+ end += 1;
473
+ path += "." + expr.substring(dot + 1, end);
474
+ cursor = end;
475
+ }
476
+ out.push(path);
477
+ i = cursor;
478
+ }
479
+ return out;
480
+ }
481
+ /** The scope name a dotted path reads — the graph-edge candidate and the `blockedBy`
482
+ * name. `dsx.variable.orders.data` → `orders`; `dsx.api.orders.data` → `orders` (the READ
483
+ * FACE, so a hole spelled through it is the same edge); `user.data.id` → `user`. */
484
+ function pathScopeName(path) {
485
+ const parts = path.split(".");
486
+ if (parts[0] !== "dsx")
487
+ return parts[0] ?? path;
488
+ if ((parts[1] === "variable" || parts[1] === "formula" || parts[1] === "api") && parts[2] !== undefined)
489
+ return parts[2];
490
+ return "";
491
+ }
492
+ function pathIsAmbient(path) {
493
+ const parts = path.split(".");
494
+ const head = parts[0] ?? "";
495
+ if (head === "dsx") {
496
+ const second = parts[1] ?? "";
497
+ return !DSX_SCOPE_HEADS.has(second);
498
+ }
499
+ return AMBIENT_ROOTS.has(head);
500
+ }
501
+ /** A hole that reads ONLY ambient planes is never a gate. */
502
+ function holeIsAmbient(hole) {
503
+ const paths = expressionPaths(hole);
504
+ if (paths.length === 0)
505
+ return true; // a literal hole cannot be waiting on anything
506
+ return paths.every(pathIsAmbient);
507
+ }
508
+ /** The name reported for a `missing_value` hole: its first non-ambient scope name. */
509
+ function holeName(hole) {
510
+ for (const path of expressionPaths(hole)) {
511
+ if (pathIsAmbient(path))
512
+ continue;
513
+ const name = pathScopeName(path);
514
+ if (name.length > 0)
515
+ return name;
516
+ }
517
+ return hole.trim();
518
+ }
519
+ /** The upstream `<api>` names one spec reads, in first-appearance order:
520
+ * `needs=` first (declared), then the expression edges the compiler can see. */
521
+ function specUpstreams(spec, siblings) {
522
+ const out = [];
523
+ const push = (name) => {
524
+ if (name !== spec.as && siblings.has(name) && !out.includes(name))
525
+ out.push(name);
526
+ };
527
+ for (const raw of (spec.needs ?? "").split(",")) {
528
+ const name = raw.trim();
529
+ if (name.length > 0 && name !== spec.as && !out.includes(name))
530
+ out.push(name);
531
+ }
532
+ for (const hole of interpolationHoles(spec.url)) {
533
+ for (const path of expressionPaths(hole))
534
+ push(pathScopeName(path));
535
+ }
536
+ for (const expr of [spec.headers, spec.body]) {
537
+ if (expr === undefined)
538
+ continue;
539
+ for (const path of expressionPaths(expr))
540
+ push(pathScopeName(path));
541
+ }
542
+ // a dynamic word that reads another block waits for it like a url hole does (ADR 0017)
543
+ for (const key of API_DYNAMIC_WORDS) {
544
+ const raw = spec[key];
545
+ if (raw === undefined || !raw.includes("{{"))
546
+ continue;
547
+ for (const hole of interpolationHoles(raw)) {
548
+ for (const path of expressionPaths(hole))
549
+ push(pathScopeName(path));
550
+ }
551
+ }
552
+ return out;
553
+ }
554
+ /** `needs=` names that are not `<api>` blocks in this scope — doc 11's lint ERROR, and
555
+ * a DECLARED runtime error here, because a silent forever-wait is the worse failure. */
556
+ function specUnknownNeeds(spec, siblings) {
557
+ const out = [];
558
+ for (const raw of (spec.needs ?? "").split(",")) {
559
+ const name = raw.trim();
560
+ if (name.length > 0 && !siblings.has(name) && !out.includes(name))
561
+ out.push(name);
562
+ }
563
+ return out;
564
+ }
565
+ /** The `<api>` dependency graph of ONE component scope (doc 11). Blocks attach to it,
566
+ * every block mounts before any fires, and a settled block re-evaluates its dependents:
567
+ * deep chains waterfall along their own edges, everything else stays concurrent. */
568
+ export class ApiGraph {
569
+ names = [];
570
+ upstream = new Map();
571
+ blocks = new Map();
572
+ /** the cycle path, when the declared graph is not a DAG (doc 11: a declared error) */
573
+ cycle;
574
+ unknown = new Map();
575
+ started = false;
576
+ constructor(specs) {
577
+ const siblings = new Set(specs.map((s) => s.as));
578
+ for (const spec of specs) {
579
+ this.names.push(spec.as);
580
+ this.upstream.set(spec.as, specUpstreams(spec, siblings));
581
+ const unknown = specUnknownNeeds(spec, siblings);
582
+ if (unknown.length > 0)
583
+ this.unknown.set(spec.as, unknown);
584
+ }
585
+ this.cycle = this.findCycle();
586
+ }
587
+ /** DFS with an explicit colour map — returns the first cycle path found, in
588
+ * declaration order so every runtime reports the same one. */
589
+ findCycle() {
590
+ const state = new Map(); // 0 unvisited · 1 on-stack · 2 done
591
+ const stack = [];
592
+ const walk = (name) => {
593
+ if (state.get(name) === 1)
594
+ return [...stack.slice(stack.indexOf(name)), name];
595
+ if (state.get(name) === 2)
596
+ return null;
597
+ state.set(name, 1);
598
+ stack.push(name);
599
+ for (const up of this.upstream.get(name) ?? []) {
600
+ if (!this.upstream.has(up))
601
+ continue;
602
+ const found = walk(up);
603
+ if (found !== null)
604
+ return found;
605
+ }
606
+ stack.pop();
607
+ state.set(name, 2);
608
+ return null;
609
+ };
610
+ for (const name of this.names) {
611
+ const found = walk(name);
612
+ if (found !== null)
613
+ return found;
614
+ }
615
+ return null;
616
+ }
617
+ upstreamsOf(name) {
618
+ return this.upstream.get(name) ?? [];
619
+ }
620
+ unknownNeedsOf(name) {
621
+ return this.unknown.get(name) ?? [];
622
+ }
623
+ attach(block, name) {
624
+ this.blocks.set(name, block);
625
+ }
626
+ detach(name) {
627
+ this.blocks.delete(name);
628
+ }
629
+ /** Mount is over — every block is registered, so the runnable ones may start. */
630
+ start() {
631
+ if (this.started)
632
+ return;
633
+ this.started = true;
634
+ for (const name of this.names)
635
+ this.blocks.get(name)?.graphStart();
636
+ }
637
+ /** An upstream settled: its dependents re-evaluate and fire the moment THEIR inputs
638
+ * are whole. Unrelated siblings are untouched (equality-checked identities). */
639
+ notifySettled(settled) {
640
+ if (!this.started)
641
+ return;
642
+ for (const name of this.names) {
643
+ if (name === settled)
644
+ continue;
645
+ this.blocks.get(name)?.graphReevaluate();
646
+ }
647
+ }
648
+ }
649
+ const MAX_API_RESPONSE_BYTES = 16 * 1024 * 1024;
650
+ const MAX_API_REQUEST_BYTES = 4 * 1024 * 1024;
651
+ const MAX_API_REQUEST_NODES = 250_000;
652
+ const MAX_API_REQUEST_DEPTH = 128;
653
+ const MAX_API_URL_BYTES = 16 * 1024;
654
+ const MAX_API_HEADER_BYTES = 64 * 1024;
655
+ const MAX_API_HEADER_COUNT = 100;
656
+ // networking.md N2: an undeclared `timeout=` is not "wait forever", it is the SAME
657
+ // bound the native lanes already carry: Android's NetworkBackend.kt DEFAULT_TIMEOUT_SECONDS
658
+ // (30.0) and iOS's equivalent default. A socket that never writes must fail closed here
659
+ // exactly as it does there, so a corpus row can pin one number across three lanes instead
660
+ // of two bounded transports and a web fetch that hangs forever.
661
+ const DEFAULT_API_TIMEOUT_MS = 30_000;
662
+ class ApiResponseError extends Error {
663
+ code;
664
+ constructor(code, message = code) {
665
+ super(message);
666
+ this.code = code;
667
+ }
668
+ }
669
+ async function readBoundedBytes(res) {
670
+ const advertised = Number(res.headers.get("content-length"));
671
+ if (Number.isFinite(advertised) && advertised > MAX_API_RESPONSE_BYTES) {
672
+ throw new ApiResponseError("response_too_large");
673
+ }
674
+ if (res.body === null)
675
+ return new Uint8Array();
676
+ const reader = res.body.getReader();
677
+ const chunks = [];
678
+ let size = 0;
679
+ for (;;) {
680
+ const { done, value } = await reader.read();
681
+ if (done)
682
+ break;
683
+ size += value.byteLength;
684
+ if (size > MAX_API_RESPONSE_BYTES) {
685
+ try {
686
+ await reader.cancel("response_too_large");
687
+ }
688
+ catch { /* already closed */ }
689
+ throw new ApiResponseError("response_too_large");
690
+ }
691
+ chunks.push(value);
692
+ }
693
+ const body = new Uint8Array(size);
694
+ let offset = 0;
695
+ for (const chunk of chunks) {
696
+ body.set(chunk, offset);
697
+ offset += chunk.byteLength;
698
+ }
699
+ return body;
700
+ }
701
+ function decodeSseData(data) {
702
+ try {
703
+ return JSON.parse(data);
704
+ }
705
+ catch {
706
+ return data;
707
+ }
708
+ }
709
+ function escapedJsonStringBytes(value, remaining) {
710
+ let bytes = 2; // quotes
711
+ for (let index = 0; index < value.length; index += 1) {
712
+ const code = value.charCodeAt(index);
713
+ if (code === 0x22 || code === 0x5c)
714
+ bytes += 2;
715
+ else if (code <= 0x1f)
716
+ bytes += 6;
717
+ else if (code <= 0x7f)
718
+ bytes += 1;
719
+ else if (code <= 0x7ff)
720
+ bytes += 2;
721
+ else if (code >= 0xd800 && code <= 0xdbff) {
722
+ const low = value.charCodeAt(index + 1);
723
+ if (low >= 0xdc00 && low <= 0xdfff) {
724
+ bytes += 4;
725
+ index += 1;
726
+ }
727
+ else {
728
+ bytes += 6; // JSON.stringify escapes an unpaired surrogate
729
+ }
730
+ }
731
+ else if (code >= 0xdc00 && code <= 0xdfff)
732
+ bytes += 6;
733
+ else
734
+ bytes += 3;
735
+ if (bytes > remaining)
736
+ return bytes;
737
+ }
738
+ return bytes;
739
+ }
740
+ /** Reject hostile/deep request graphs before JSON.stringify can monopolize the UI
741
+ * thread or allocate an unbounded intermediate string. */
742
+ function preflightJsonBody(value) {
743
+ const stack = [{ value, depth: 0 }];
744
+ const ancestors = new Set();
745
+ let nodes = 0;
746
+ let bytes = 0;
747
+ const add = (count) => {
748
+ bytes += count;
749
+ if (bytes > MAX_API_REQUEST_BYTES) {
750
+ throw new ApiResponseError("request_too_large");
751
+ }
752
+ };
753
+ while (stack.length > 0) {
754
+ const frame = stack.pop();
755
+ if (frame.exit !== undefined) {
756
+ ancestors.delete(frame.exit);
757
+ continue;
758
+ }
759
+ nodes += 1;
760
+ if (nodes > MAX_API_REQUEST_NODES || frame.depth > MAX_API_REQUEST_DEPTH) {
761
+ throw new ApiResponseError("request_too_complex");
762
+ }
763
+ const next = frame.value;
764
+ if (next === null || next === undefined || next === NSNull) {
765
+ add(4);
766
+ }
767
+ else if (typeof next === "string") {
768
+ add(escapedJsonStringBytes(next, MAX_API_REQUEST_BYTES - bytes));
769
+ }
770
+ else if (typeof next === "number") {
771
+ add(Number.isFinite(next) ? String(next).length : 4);
772
+ }
773
+ else if (typeof next === "boolean") {
774
+ add(next ? 4 : 5);
775
+ }
776
+ else if (Array.isArray(next)) {
777
+ if (ancestors.has(next))
778
+ throw new ApiResponseError("invalid_request");
779
+ ancestors.add(next);
780
+ add(2 + Math.max(0, next.length - 1));
781
+ stack.push({ depth: frame.depth, exit: next });
782
+ for (let index = next.length - 1; index >= 0; index -= 1) {
783
+ stack.push({ value: next[index], depth: frame.depth + 1 });
784
+ }
785
+ }
786
+ else if (isDict(next)) {
787
+ if (ancestors.has(next))
788
+ throw new ApiResponseError("invalid_request");
789
+ ancestors.add(next);
790
+ const entries = Object.entries(next);
791
+ add(2 + Math.max(0, entries.length - 1));
792
+ stack.push({ depth: frame.depth, exit: next });
793
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
794
+ const [key, entryValue] = entries[index];
795
+ add(escapedJsonStringBytes(key, MAX_API_REQUEST_BYTES - bytes) + 1);
796
+ stack.push({ value: entryValue, depth: frame.depth + 1 });
797
+ }
798
+ }
799
+ else {
800
+ throw new ApiResponseError("invalid_request");
801
+ }
802
+ }
803
+ }
804
+ function compactBodyHash(value) {
805
+ // Four independent 32-bit lanes keep cache keys compact (request bodies are
806
+ // capped at 4 MiB) while making accidental collisions vanishingly small.
807
+ const lanes = [0x811c9dc5, 0x9e3779b9, 0x85ebca6b, 0xc2b2ae35];
808
+ for (let index = 0; index < value.length; index += 1) {
809
+ const code = value.charCodeAt(index);
810
+ for (let lane = 0; lane < lanes.length; lane += 1) {
811
+ lanes[lane] = Math.imul((lanes[lane] ^ code) >>> 0, 0x01000193 + lane * 2) >>> 0;
812
+ }
813
+ }
814
+ return `${value.length}:` + lanes.map((lane) => lane.toString(16).padStart(8, "0")).join("");
815
+ }
816
+ /** THE REQUEST BODY FOLD (proposals/web-components.md, the Paywall size work): only a slice that
817
+ * declares an `<api body=…>` or `encode=`, or calls a block with arguments (`dsx.api.save({…})`),
818
+ * can put a body on the wire, so an embed whose slice does neither drops the body family: the
819
+ * JSON preflight, the body hash and the form and multipart encoders
820
+ * (`__DSX_OPTIONAL_API_BODIES__`, set per slice by the embed emitter, cli embed/entry.ts). */
821
+ // Spelled inline at each use, like the streams fold: esbuild folds the defined expression in
822
+ // place and drops the dead branch, where a const holding it keeps both arms.
823
+ function prepareRequestBody(rawBody) {
824
+ if (!(globalThis.__DSX_OPTIONAL_API_BODIES__ !== false))
825
+ return { key: "∅" };
826
+ if (rawBody === undefined || rawBody === null || rawBody === NSNull)
827
+ return { key: "∅" };
828
+ if (typeof rawBody === "string") {
829
+ if (rawBody.length > MAX_API_REQUEST_BYTES) {
830
+ throw new ApiResponseError("request_too_large");
831
+ }
832
+ if (new TextEncoder().encode(rawBody).byteLength > MAX_API_REQUEST_BYTES) {
833
+ throw new ApiResponseError("request_too_large");
834
+ }
835
+ return { wire: rawBody, key: `text:${compactBodyHash(rawBody)}` };
836
+ }
837
+ preflightJsonBody(rawBody);
838
+ const encoded = JSON.stringify(rawBody, (_k, v) => (v === NSNull ? null : v));
839
+ if (encoded === undefined)
840
+ throw new ApiResponseError("invalid_request");
841
+ if (new TextEncoder().encode(encoded).byteLength > MAX_API_REQUEST_BYTES) {
842
+ throw new ApiResponseError("request_too_large");
843
+ }
844
+ return { wire: encoded, key: `json:${compactBodyHash(encoded)}` };
845
+ }
846
+ /** networking.md N2 — the declared REQUEST encodings the kernel materializes itself, so
847
+ * all three runtimes put the same bytes (or the same `parts`) on the wire. */
848
+ function encodeFormBody(body) {
849
+ if (!isDict(body))
850
+ return string(body);
851
+ const dict = body;
852
+ return Object.keys(dict).sort()
853
+ .map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(string(dict[k]))}`)
854
+ .join("&");
855
+ }
856
+ /** multipart/form-data parts, SORTED BY FIELD NAME so the corpus is order-deterministic
857
+ * on runtimes whose native dictionaries are unordered. A `{ __blob, type, name }` value
858
+ * (the JSE Blob/File shape) becomes a file part; everything else a value part. */
859
+ function multipartParts(body) {
860
+ if (!isDict(body))
861
+ return [];
862
+ const dict = body;
863
+ const out = [];
864
+ for (const key of Object.keys(dict).sort()) {
865
+ const value = dict[key];
866
+ if (isDict(value) && typeof value["__blob"] === "string") {
867
+ const blob = value;
868
+ const part = { name: key, blob: blob["__blob"] };
869
+ if (typeof blob["name"] === "string")
870
+ part["filename"] = blob["name"];
871
+ if (typeof blob["type"] === "string")
872
+ part["contentType"] = blob["type"];
873
+ out.push(part);
874
+ }
875
+ else {
876
+ out.push({ name: key, value: string(value) });
877
+ }
878
+ }
879
+ return out;
880
+ }
881
+ function validateRequestMetadata(req) {
882
+ if (new TextEncoder().encode(string(req["url"])).byteLength > MAX_API_URL_BYTES) {
883
+ throw new ApiResponseError("request_too_large");
884
+ }
885
+ const entries = isDict(req["headers"]) ? Object.entries(req["headers"]) : [];
886
+ if (entries.length > MAX_API_HEADER_COUNT) {
887
+ throw new ApiResponseError("request_too_large");
888
+ }
889
+ let bytes = 0;
890
+ for (const [name, value] of entries) {
891
+ bytes += new TextEncoder().encode(name).byteLength + new TextEncoder().encode(string(value)).byteLength + 4;
892
+ if (bytes > MAX_API_HEADER_BYTES) {
893
+ throw new ApiResponseError("request_too_large");
894
+ }
895
+ }
896
+ }
897
+ /** THE LOCALE IS IN EVERY API REQUEST (localization-and-caching.md C7; corpus api/api-blocks.json
898
+ * `accept-language-*`): the language the app speaks rides every request as `accept-language`,
899
+ * a materialized header, so it enters the cache key and a locale switch re-materializes and
900
+ * refetches localized data with no author code (L11). Read through `dsx.app.locale`, the app
901
+ * plane every lane publishes and the server render sets, and read TRACKED, so the block's own
902
+ * reactive request law does the rest. An author's own `accept-language` wins; an app plane with
903
+ * no locale adds nothing. */
904
+ function withAppLocale(headers, store, item) {
905
+ if (headers !== null && "accept-language" in headers)
906
+ return headers;
907
+ const locale = JSE.eval("dsx.app.locale", store.jse, item);
908
+ if (typeof locale !== "string" || locale.length === 0 || !/^[A-Za-z0-9-]{1,35}$/.test(locale))
909
+ return headers;
910
+ return { ...(headers ?? {}), "accept-language": locale };
911
+ }
912
+ export function normalizeRequestHeaders(value) {
913
+ if (!isDict(value))
914
+ return null;
915
+ const headers = {};
916
+ for (const [rawName, rawValue] of Object.entries(value)) {
917
+ if (rawName.startsWith("__"))
918
+ continue; // portable `new Headers()` marker
919
+ const name = rawName.trim().toLowerCase();
920
+ if (name.length > 0)
921
+ headers[name] = string(rawValue);
922
+ }
923
+ return headers;
924
+ }
925
+ function isHttpsDowngrade(requestUrl, responseUrl) {
926
+ if (responseUrl.length === 0)
927
+ return false; // injected/test Responses have no URL
928
+ try {
929
+ const base = typeof location !== "undefined" ? location.href : undefined;
930
+ const initial = new URL(requestUrl, base);
931
+ const final = new URL(responseUrl);
932
+ return initial.protocol === "https:" && final.protocol === "http:";
933
+ }
934
+ catch {
935
+ return false;
936
+ }
937
+ }
938
+ /** Node 22 and every current browser expose `AbortSignal.any`; the fallback keeps the
939
+ * author's own cancellation authoritative when a runtime predates it. */
940
+ function combineSignals(a, b) {
941
+ if (a === null)
942
+ return b;
943
+ if (b === null)
944
+ return a;
945
+ const any = AbortSignal.any;
946
+ return typeof any === "function" ? any([a, b]) : a;
947
+ }
948
+ /** networking.md N2 "multipart/file": the materialized `parts` (already sorted by field
949
+ * name) become a real multipart body. `FormData`/`Blob` are fetch globals, not DOM —
950
+ * the block stays DOM-free and runs identically in the browser, Node and tests. */
951
+ function multipartFormData(parts) {
952
+ const form = new FormData();
953
+ for (const part of parts) {
954
+ const name = string(part["name"]);
955
+ if (name.length === 0)
956
+ continue;
957
+ const blob = part["blob"];
958
+ if (typeof blob === "string") {
959
+ const bytes = base64Decode(blob) ?? new Uint8Array();
960
+ const type = string(part["contentType"] ?? "application/octet-stream");
961
+ const filename = string(part["filename"] ?? name);
962
+ form.append(name, new Blob([bytes], { type }), filename);
963
+ }
964
+ else {
965
+ form.append(name, string(part["value"]));
966
+ }
967
+ }
968
+ return form;
969
+ }
970
+ async function doFetch(url, init, signal, onStreamMessage, onLiveReady, onStreamRetry) {
971
+ if (RunnerFetchSeam.impl)
972
+ return RunnerFetchSeam.impl(url, { ...init, signal });
973
+ const method = string(init["method"] ?? "GET") || "GET";
974
+ // proposals/realtime.md R1.1: a LIVE stream reconnects by re-issuing the request, so it may
975
+ // only be a read. Refused before a byte leaves, the same answer the persistent path gives.
976
+ if (init["stream"] === "live" && method.toUpperCase() !== "GET") {
977
+ return { ok: false, status: -2, data: null, error: "invalid_request" };
978
+ }
979
+ const headers = {};
980
+ if (isDict(init["headers"])) {
981
+ for (const [k, v] of Object.entries(init["headers"]))
982
+ headers[k] = string(v);
983
+ }
984
+ let automaticCsrf = false;
985
+ // Host-only CSRF cookies are readable through the existing cookie seam. Only
986
+ // the document's own origin may receive this token; GET feeds stay eligible
987
+ // for browser WebSocket negotiation without synthetic request headers.
988
+ if (!["GET", "HEAD"].includes(method.toUpperCase())
989
+ && !Object.keys(headers).some(name => name.toLowerCase() === "x-despia-csrf")
990
+ && typeof location !== "undefined") {
991
+ try {
992
+ const target = new URL(url, location.href);
993
+ const current = new URL(location.href);
994
+ const jar = readCookiePartition()["jar"];
995
+ const token = isDict(jar) ? jar["__Host-despia_csrf"] : undefined;
996
+ if (target.origin === current.origin && target.protocol === "https:"
997
+ && typeof token === "string" && /^[A-Za-z0-9_-]{1,256}$/.test(token)) {
998
+ headers["x-despia-csrf"] = token;
999
+ automaticCsrf = true;
1000
+ }
1001
+ }
1002
+ catch { /* An invalid URL follows the normal fetch refusal. */ }
1003
+ }
1004
+ let body;
1005
+ const rawBody = init["body"];
1006
+ try {
1007
+ validateRequestMetadata(init);
1008
+ // networking.md N2: a DECLARED encoding (text/form/multipart) already materialized
1009
+ // its wire form (or its `parts`); only the default json path prepares here.
1010
+ if ((globalThis.__DSX_OPTIONAL_API_BODIES__ !== false) && Array.isArray(init["parts"])) {
1011
+ body = multipartFormData(init["parts"]);
1012
+ }
1013
+ else if (typeof init["wire"] === "string") {
1014
+ body = init["wire"];
1015
+ }
1016
+ else {
1017
+ const prepared = typeof init["__dsxBodyKey"] === "string"
1018
+ ? { wire: typeof init["__dsxBodyWire"] === "string" ? init["__dsxBodyWire"] : undefined }
1019
+ : prepareRequestBody(rawBody);
1020
+ body = prepared.wire;
1021
+ if (body !== undefined && typeof rawBody !== "string"
1022
+ && !Object.keys(headers).some((k) => k.toLowerCase() === "content-type")) {
1023
+ headers["Content-Type"] = "application/json";
1024
+ }
1025
+ }
1026
+ }
1027
+ catch (error) {
1028
+ const failure = error;
1029
+ return {
1030
+ ok: false,
1031
+ status: -2,
1032
+ data: null,
1033
+ error: failure.code ?? "invalid_request",
1034
+ };
1035
+ }
1036
+ // networking.md N2 "Control": a declared per-request timeout is an abort with its own
1037
+ // reason, so it is distinguishable from an author cancel; a declared redirect policy
1038
+ // rides straight through to the transport. An UNDECLARED timeout is not "wait forever":
1039
+ // applyTransportControls only ever sets `init["timeout"]` when the author declared a
1040
+ // positive value, so its absence here is the undeclared case, and it falls back to the
1041
+ // same DEFAULT_API_TIMEOUT_MS the native lanes bound a socket to.
1042
+ const declaredTimeout = init["timeout"];
1043
+ const timeoutMs = declaredTimeout === undefined
1044
+ ? DEFAULT_API_TIMEOUT_MS
1045
+ : safeInt(number(declaredTimeout) ?? 0);
1046
+ const timeoutController = timeoutMs > 0 && typeof AbortController !== "undefined" ? new AbortController() : null;
1047
+ let timeoutTimer = null;
1048
+ let timedOut = false;
1049
+ if (timeoutController !== null) {
1050
+ timeoutTimer = setTimeout(() => { timedOut = true; timeoutController.abort(); }, timeoutMs);
1051
+ }
1052
+ const effectiveSignal = combineSignals(signal, timeoutController?.signal ?? null);
1053
+ const redirect = automaticCsrf ? "error" : string(init["redirect"] ?? "");
1054
+ let res;
1055
+ try {
1056
+ res = await fetch(url, {
1057
+ method,
1058
+ headers,
1059
+ body,
1060
+ ...(redirect === "error" || redirect === "follow" ? { redirect: redirect } : {}),
1061
+ ...(effectiveSignal ? { signal: effectiveSignal } : {}),
1062
+ });
1063
+ }
1064
+ catch (e) {
1065
+ if (timeoutTimer !== null)
1066
+ clearTimeout(timeoutTimer);
1067
+ if (timedOut)
1068
+ return { ok: false, status: -2, data: null, error: "timeout" };
1069
+ if (e.name === "AbortError")
1070
+ return { ok: false, status: -1, aborted: true, data: null };
1071
+ if (e.name === "TypeError" && redirect === "error") {
1072
+ return { ok: false, status: -2, data: null, error: "redirect" };
1073
+ }
1074
+ return { ok: false, status: 0, data: null, error: "network" };
1075
+ }
1076
+ if (timeoutTimer !== null)
1077
+ clearTimeout(timeoutTimer);
1078
+ const contentType = res.headers.get("content-type") ?? "";
1079
+ const outHeaders = {};
1080
+ res.headers.forEach((v, k) => { outHeaders[k] = v; });
1081
+ if (isHttpsDowngrade(url, res.url)) {
1082
+ try {
1083
+ await res.body?.cancel("insecure_redirect");
1084
+ }
1085
+ catch { /* already closed */ }
1086
+ return {
1087
+ ok: false,
1088
+ status: -2,
1089
+ data: null,
1090
+ headers: outHeaders,
1091
+ error: "insecure_redirect",
1092
+ };
1093
+ }
1094
+ try {
1095
+ // Server-Sent Events are delivered while the connection is still open. A
1096
+ // line parser (rather than split("\n\n")) preserves CRLF and chunk-boundary
1097
+ // correctness and joins multi-line data fields per the SSE wire format.
1098
+ // networking.md N2: streaming is DECLARED, not sniffed. `stream="false"` reads an
1099
+ // event-stream as an ordinary body; `stream="true"` streams a non-SSE body as
1100
+ // newline-delimited chunks. Absent, the historical content-type sniff still applies.
1101
+ const declaredStream = init["stream"];
1102
+ // THE LIVE STREAM FOLD (proposals/realtime.md; proposals/web-components.md, the Paywall size
1103
+ // work): only a block that declares `stream=` can reach the live reader, so an embed whose
1104
+ // slice declares none drops live-stream.ts (`__DSX_OPTIONAL_API_STREAMS__`, set per slice).
1105
+ if (globalThis.__DSX_OPTIONAL_API_STREAMS__ !== false
1106
+ && (declaredStream === true || declaredStream === "live") && res.ok && contentType.split(";")[0]?.trim() === LIVE_MEDIA_TYPE) {
1107
+ if (method !== "GET")
1108
+ throw new ApiResponseError("invalid_request");
1109
+ try {
1110
+ await runLiveStream({
1111
+ url, initial: res, headers, signal,
1112
+ onMessage: (chunk) => {
1113
+ const record = isDict(chunk) ? chunk : {};
1114
+ onStreamMessage?.(chunk, true, {
1115
+ event: typeof record["event"] === "string" ? record["event"] : "message",
1116
+ id: typeof record["cursor"] === "string" ? record["cursor"] : null,
1117
+ });
1118
+ },
1119
+ onReady: onLiveReady,
1120
+ });
1121
+ return { ok: false, status: -1, aborted: true, data: null };
1122
+ }
1123
+ catch (error) {
1124
+ if (error instanceof LiveStreamError) {
1125
+ return { ok: false, status: error.status, data: null, error: error.code };
1126
+ }
1127
+ throw error;
1128
+ }
1129
+ }
1130
+ const sse = contentType.includes("text/event-stream");
1131
+ const streaming = declaredStream === false ? false : (sse || declaredStream === true || declaredStream === "live");
1132
+ if (streaming && res.body !== null) {
1133
+ const advertised = Number(res.headers.get("content-length"));
1134
+ if (Number.isFinite(advertised) && advertised > MAX_API_RESPONSE_BYTES) {
1135
+ throw new ApiResponseError("response_too_large");
1136
+ }
1137
+ const chunks = [];
1138
+ const reader = res.body.getReader();
1139
+ const decoder = new TextDecoder();
1140
+ const dataLines = [];
1141
+ // proposals/realtime.md R1.4: the EventSource fields are KEPT. `eventType` is the frame's
1142
+ // own and resets at every dispatch; `lastId` is the stream's buffer and persists.
1143
+ let eventType = "";
1144
+ let lastId = null;
1145
+ let line = "";
1146
+ let skipLineFeed = false;
1147
+ let totalBytes = 0;
1148
+ let firstLine = true;
1149
+ const dispatch = () => {
1150
+ const event = eventType === "" ? "message" : eventType;
1151
+ eventType = "";
1152
+ if (dataLines.length === 0)
1153
+ return;
1154
+ const chunk = decodeSseData(dataLines.join("\n"));
1155
+ dataLines.length = 0;
1156
+ // an `event: error` frame is the server saying the stream failed: it is the envelope's
1157
+ // error, never a message (realtime.ts sends exactly this on a failed subscription)
1158
+ if (event !== "error")
1159
+ chunks.push(chunk);
1160
+ if (res.ok)
1161
+ onStreamMessage?.(chunk, false, { event, id: lastId });
1162
+ };
1163
+ const acceptLine = (rawLine) => {
1164
+ let nextLine = rawLine;
1165
+ if (firstLine) {
1166
+ firstLine = false;
1167
+ if (nextLine.startsWith("\uFEFF"))
1168
+ nextLine = nextLine.substring(1);
1169
+ }
1170
+ if (!sse) {
1171
+ // a declared non-SSE stream is newline-delimited: one whole line, one chunk
1172
+ if (nextLine.length === 0)
1173
+ return;
1174
+ dataLines.push(nextLine);
1175
+ dispatch();
1176
+ return;
1177
+ }
1178
+ if (nextLine === "") {
1179
+ dispatch();
1180
+ return;
1181
+ }
1182
+ if (nextLine.startsWith(":"))
1183
+ return;
1184
+ const colon = nextLine.indexOf(":");
1185
+ const field = colon < 0 ? nextLine : nextLine.substring(0, colon);
1186
+ let value = colon < 0 ? "" : nextLine.substring(colon + 1);
1187
+ if (value.startsWith(" "))
1188
+ value = value.substring(1);
1189
+ if (field === "data")
1190
+ dataLines.push(value);
1191
+ else if (field === "event")
1192
+ eventType = value;
1193
+ // the spec ignores an id carrying NULL; any other value (the empty one included) sets it
1194
+ else if (field === "id") {
1195
+ if (!value.includes("\u0000"))
1196
+ lastId = value;
1197
+ }
1198
+ else if (field === "retry") {
1199
+ if (/^\d+$/.test(value))
1200
+ onStreamRetry?.(Number(value));
1201
+ }
1202
+ };
1203
+ const consume = (text) => {
1204
+ for (const character of text) {
1205
+ if (skipLineFeed) {
1206
+ skipLineFeed = false;
1207
+ if (character === "\n")
1208
+ continue;
1209
+ }
1210
+ if (character === "\r") {
1211
+ acceptLine(line);
1212
+ line = "";
1213
+ skipLineFeed = true;
1214
+ }
1215
+ else if (character === "\n") {
1216
+ acceptLine(line);
1217
+ line = "";
1218
+ }
1219
+ else {
1220
+ line += character;
1221
+ }
1222
+ }
1223
+ };
1224
+ let dropped = false;
1225
+ for (;;) {
1226
+ let step;
1227
+ try {
1228
+ step = await reader.read();
1229
+ }
1230
+ catch (error) {
1231
+ // realtime.md R1.2: a LIVE stream whose connection died mid read was DROPPED, which is
1232
+ // the reconnect case, not a malformed answer; a finite stream keeps its old verdict
1233
+ if (declaredStream !== "live" || error.name === "AbortError")
1234
+ throw error;
1235
+ dropped = true;
1236
+ break;
1237
+ }
1238
+ const { done, value } = step;
1239
+ if (done)
1240
+ break;
1241
+ totalBytes += value.byteLength;
1242
+ if (totalBytes > MAX_API_RESPONSE_BYTES) {
1243
+ try {
1244
+ await reader.cancel("response_too_large");
1245
+ }
1246
+ catch { /* already closed */ }
1247
+ throw new ApiResponseError("response_too_large");
1248
+ }
1249
+ consume(decoder.decode(value, { stream: true }));
1250
+ }
1251
+ consume(decoder.decode());
1252
+ if (line.length > 0)
1253
+ acceptLine(line);
1254
+ dispatch();
1255
+ return {
1256
+ ok: res.ok,
1257
+ status: res.status,
1258
+ data: chunks,
1259
+ headers: outHeaders,
1260
+ stream: chunks,
1261
+ streamDelivered: res.ok,
1262
+ lastEventId: lastId,
1263
+ ...(dropped ? { dropped: true } : {}),
1264
+ };
1265
+ }
1266
+ const bytes = await readBoundedBytes(res);
1267
+ const expected = string(init["expect"]) || "json";
1268
+ const text = expected === "blob" ? "" : new TextDecoder().decode(bytes);
1269
+ let data;
1270
+ if (expected === "blob") {
1271
+ data = {
1272
+ __blob: base64Encode(bytes),
1273
+ type: contentType.split(";", 1)[0].trim(),
1274
+ size: bytes.byteLength,
1275
+ };
1276
+ }
1277
+ else if (expected === "text")
1278
+ data = text;
1279
+ else if (contentType.includes("json"))
1280
+ data = text.length > 0 ? JSON.parse(text) : null;
1281
+ else
1282
+ data = text;
1283
+ return { ok: res.ok, status: res.status, data, headers: outHeaders };
1284
+ }
1285
+ catch (e) {
1286
+ if (e.name === "AbortError")
1287
+ return { ok: false, status: -1, aborted: true, data: null };
1288
+ const failure = e;
1289
+ return {
1290
+ ok: false,
1291
+ // Parsing/size failures are terminal response failures, not transport
1292
+ // failures: status -2 prevents the network-retry loop from amplifying them.
1293
+ status: -2,
1294
+ data: null,
1295
+ error: failure.code ?? "invalid_response",
1296
+ };
1297
+ }
1298
+ }
1299
+ // ── materialization + SSR prefetch (shared with @despia-native/server render) ──────────────────
1300
+ /** Evaluate url/headers/body/auto in `store`'s scope — the ONE place the request is
1301
+ * materialized (the block's dependency effect and the SSR prefetch below both use it,
1302
+ * so the request an SSR run executes is byte-for-byte the one the client would). */
1303
+ export function materializeApiRequest(declared, store, item) {
1304
+ const spec = liveApiSpec(declared, store, item);
1305
+ const method = (spec.method ?? "GET").trim().toUpperCase();
1306
+ const expectWord = (spec.expect ?? "json").trim().toLowerCase();
1307
+ const expect = expectWord === "text" || expectWord === "blob" ? expectWord : "json";
1308
+ const autoExpr = spec.auto;
1309
+ const auto = autoExpr !== undefined
1310
+ ? truthy(JSE.eval(autoExpr, store.jse, item))
1311
+ : method === "GET"; // auto defaults true for GET (doc 05)
1312
+ // doc 11 value-presence gating is derived from the SAME pass that interpolates, so a
1313
+ // gated block costs no extra evaluation: each `{{ … }}` hole that lands in the url is
1314
+ // checked as it is written. Ambient planes are typed-absent, never holes.
1315
+ const missing = [];
1316
+ const url = interpolateGated(spec.url, store, item, missing);
1317
+ const rawHeaders = spec.headers !== undefined ? JSE.eval(spec.headers, store.jse, item) : null;
1318
+ if (isDict(rawHeaders)) {
1319
+ const dict = rawHeaders;
1320
+ for (const key of Object.keys(dict).sort()) {
1321
+ const value = dict[key];
1322
+ if ((value === null || value === undefined || value === NSNull) && !missing.includes(key)) {
1323
+ missing.push(key);
1324
+ }
1325
+ }
1326
+ }
1327
+ const headers = withAppLocale(normalizeRequestHeaders(rawHeaders), store, item);
1328
+ const body = spec.body !== undefined ? JSE.eval(spec.body, store.jse, item) : null;
1329
+ if (spec.body !== undefined && (body === null || body === undefined || body === NSNull)) {
1330
+ for (const path of expressionPaths(spec.body)) {
1331
+ if (pathIsAmbient(path))
1332
+ continue;
1333
+ const name = pathScopeName(path);
1334
+ if (name.length > 0 && !missing.includes(name))
1335
+ missing.push(name);
1336
+ break;
1337
+ }
1338
+ }
1339
+ const req = {
1340
+ url,
1341
+ method,
1342
+ headers,
1343
+ body,
1344
+ expect,
1345
+ // GET/HEAD responses are identity-sensitive even when auth rides an implicit cookie.
1346
+ cookiePartition: method === "GET" || method === "HEAD" ? readCookiePartition() : null,
1347
+ auto,
1348
+ _missing: missing,
1349
+ };
1350
+ applyTransportControls(spec, req);
1351
+ return req;
1352
+ }
1353
+ /** `JSE.interpolate`, with the doc-11 hole ledger: a `{{ … }}` that evaluates to
1354
+ * null/undefined and reads at least one non-ambient path records its scope name. */
1355
+ export function interpolateGated(template, store, item, missing) {
1356
+ if (!template.includes("{{"))
1357
+ return template;
1358
+ let out = "";
1359
+ let idx = 0;
1360
+ for (;;) {
1361
+ const open = template.indexOf("{{", idx);
1362
+ if (open < 0)
1363
+ break;
1364
+ out += template.substring(idx, open);
1365
+ const close = template.indexOf("}}", open + 2);
1366
+ if (close < 0) {
1367
+ out += template.substring(open);
1368
+ return out;
1369
+ }
1370
+ const hole = template.substring(open + 2, close);
1371
+ const value = JSE.eval(hole, store.jse, item);
1372
+ if ((value === null || value === undefined || value === NSNull) && !holeIsAmbient(hole)) {
1373
+ const name = holeName(hole);
1374
+ if (!missing.includes(name))
1375
+ missing.push(name);
1376
+ }
1377
+ out += string(value);
1378
+ idx = close + 2;
1379
+ }
1380
+ out += template.substring(idx);
1381
+ return out;
1382
+ }
1383
+ /** THE DECLARED WORDS OF AN `<api>` TAKE `{{ }}`. `method`,
1384
+ * `expect`, `timeout`, `retry`, `cache`, `debounce`, `redirect`, `encode` and `keep` are read
1385
+ * through the interpolation law every attribute obeys, against the block's own scope, WHEN THE
1386
+ * NEXT REQUEST STARTS: `method` and `expect` are part of the materialized request (a change is a
1387
+ * new request, like a url change), the rest are transport policy the next request reads. A word
1388
+ * with no hole is the word, at no cost. `as`, `needs`, `depends`, `ssr`, `via` and `stream` are
1389
+ * DECLARATION facts the build and the graph read before any state exists, and the linter
1390
+ * refuses a hole in them by name. Twins: ApiBlock.kt `word`, ApiBlock.swift `word`. */
1391
+ export function apiWord(raw, store, item) {
1392
+ if (raw === undefined || !raw.includes("{{"))
1393
+ return raw;
1394
+ return JSE.interpolate(raw, store.jse, item);
1395
+ }
1396
+ /** The spec with its dynamic words read now (see `apiWord`). The same object when nothing in it
1397
+ * carries a hole, so a static block allocates nothing. */
1398
+ export function liveApiSpec(spec, store, item) {
1399
+ let out = null;
1400
+ for (const key of API_DYNAMIC_WORDS) {
1401
+ const raw = spec[key];
1402
+ if (raw === undefined || !raw.includes("{{"))
1403
+ continue;
1404
+ if (out === null)
1405
+ out = { ...spec };
1406
+ out[key] = JSE.interpolate(raw, store.jse, item);
1407
+ }
1408
+ return out ?? spec;
1409
+ }
1410
+ /** `error-if`: is this ANSWERED response an error? `undefined` when the block declares no test
1411
+ * (the status decides) or the response never got an answer (a network failure is always an
1412
+ * error). Twins: ApiBlock.kt / ApiBlock.swift `judgedError`. */
1413
+ export function apiErrorIf(expr, res, store, item) {
1414
+ if (expr === undefined || expr.trim() === "")
1415
+ return undefined;
1416
+ const status = number(res["status"]) ?? 0;
1417
+ if (status <= 0)
1418
+ return undefined;
1419
+ const scope = { ...(isDict(item) ? item : {}), status, headers: isDict(res["headers"]) ? res["headers"] : {}, data: res["data"] ?? null };
1420
+ return truthy(JSE.eval(expr, store.jse, scope));
1421
+ }
1422
+ export const API_DYNAMIC_WORDS = ["method", "expect", "timeout", "retry", "cache", "debounce", "redirect", "encode", "keep", "strings"];
1423
+ /** networking.md N2 + doc 05's secrets story: fold the DECLARED transport controls into
1424
+ * the materialized request. Nothing here is sniffed — every one is authored. */
1425
+ function applyTransportControls(spec, req) {
1426
+ const flag = (raw) => {
1427
+ if (raw === undefined)
1428
+ return null;
1429
+ const v = raw.trim().toLowerCase();
1430
+ if (v === "" || v === "true" || v === "1")
1431
+ return true;
1432
+ if (v === "false" || v === "0")
1433
+ return false;
1434
+ return null;
1435
+ };
1436
+ // proposals/realtime.md R1.1: `live` is the third word, a stream meant to stay open
1437
+ const stream = (spec.stream ?? "").trim().toLowerCase() === "live" ? "live" : flag(spec.stream);
1438
+ if (stream !== null)
1439
+ req["stream"] = stream;
1440
+ const timeout = safeInt(number((spec.timeout ?? "").trim()) ?? 0);
1441
+ if (timeout > 0)
1442
+ req["timeout"] = timeout;
1443
+ const redirect = (spec.redirect ?? "").trim().toLowerCase();
1444
+ if (redirect === "error" || redirect === "follow")
1445
+ req["redirect"] = redirect;
1446
+ const encodeWord = (spec.encode ?? "json").trim().toLowerCase();
1447
+ if ((globalThis.__DSX_OPTIONAL_API_BODIES__ !== false) && (encodeWord === "text" || encodeWord === "form" || encodeWord === "multipart")) {
1448
+ req["encode"] = encodeWord;
1449
+ const headers = isDict(req["headers"]) ? req["headers"] : {};
1450
+ if (encodeWord === "multipart") {
1451
+ req["parts"] = multipartParts(req["body"]);
1452
+ }
1453
+ else {
1454
+ req["wire"] = encodeWord === "form" ? encodeFormBody(req["body"]) : string(req["body"]);
1455
+ if (headers["content-type"] === undefined) {
1456
+ headers["content-type"] = encodeWord === "form"
1457
+ ? "application/x-www-form-urlencoded;charset=UTF-8"
1458
+ : "text/plain;charset=UTF-8";
1459
+ }
1460
+ }
1461
+ req["headers"] = headers;
1462
+ }
1463
+ if ((spec.via ?? "").trim().toLowerCase() === "server") {
1464
+ // The CLIENT half calls the generated internal route; the SERVER half performs the
1465
+ // real request with server-held headers. The target rides as one encoded parameter
1466
+ // so the proxy needs no per-block code — and no secret is ever in the bundle.
1467
+ const target = string(req["url"]);
1468
+ req["via"] = "server";
1469
+ req["target"] = target;
1470
+ req["url"] = `${ApiServerOrigin.base}/dsx/api/${spec.as}?u=${encodeURIComponent(target)}`;
1471
+ }
1472
+ }
1473
+ /** doc 05/02: `ssr` defaults true for GET, false otherwise; an explicit boolean-literal
1474
+ * attribute overrides. A non-GET is NEVER eligible (a mutation must never run during
1475
+ * render), regardless of the flag. A `defer`red block is also ineligible — the shell
1476
+ * flushes without it and it fetches on the client (the streaming flush is the open seam). */
1477
+ export function apiSsrEnabled(spec) {
1478
+ const method = (spec.method ?? "GET").trim().toUpperCase();
1479
+ if (method !== "GET")
1480
+ return false;
1481
+ if (apiDeferred(spec))
1482
+ return false;
1483
+ // realtime.md R1: a LIVE stream never ends, so a render cannot wait for it; it opens on the client
1484
+ if ((spec.stream ?? "").trim().toLowerCase() === "live")
1485
+ return false;
1486
+ const raw = spec.ssr;
1487
+ if (raw === undefined)
1488
+ return true; // default true on GET
1489
+ const v = raw.trim().toLowerCase();
1490
+ // proposals/static-data.md S1: a BUILD block is server-resolved too, one rung earlier (a live
1491
+ // server that renders it anyway answers fresher, which is never wrong)
1492
+ return v === "" || v === "true" || v === "1" || v === "build";
1493
+ }
1494
+ /** proposals/static-data.md S1: `ssr="build"` - the block is resolved by `despia build` and
1495
+ * baked into the route's HTML and hydration payload. Fail CLOSED: the build refuses when it
1496
+ * cannot resolve one. A GET only, like every server-resolved block. */
1497
+ export function apiBuildTime(spec) {
1498
+ const method = (spec.method ?? "GET").trim().toUpperCase();
1499
+ return method === "GET" && (spec.ssr ?? "").trim().toLowerCase() === "build";
1500
+ }
1501
+ /** doc 02 "Streaming": a boolean-literal `defer` marks a block for out-of-order streaming.
1502
+ * The initial render never awaits a deferred block — the shell flushes with its loading
1503
+ * branch; a STREAMING adapter (server stream.ts renderPageStream) then runs it and
1504
+ * flushes its seed as a late chunk, and a non-streaming render leaves it on the
1505
+ * client-fetch path (fail-open either way). */
1506
+ export function apiDeferred(spec) {
1507
+ const raw = spec.defer;
1508
+ if (raw === undefined)
1509
+ return false;
1510
+ const v = raw.trim().toLowerCase();
1511
+ return v === "" || v === "true" || v === "1";
1512
+ }
1513
+ /** Is this block ALREADY IN FLIGHT the first time a render reads its envelope?
1514
+ *
1515
+ * An `auto` block fires from its dependency effect the moment the head scope is built, and
1516
+ * the effect body publishes `loading: true` (network) or `loading: true, status: "waiting"`
1517
+ * (publishGate, when doc 11 gating holds it) BEFORE the tree is walked. So on the client the
1518
+ * answer at first paint is yes for every auto block, gated or not, and no for a block that
1519
+ * will never fire on its own.
1520
+ *
1521
+ * The SSR renderer runs no effects, so it has to ask this question rather than observe it.
1522
+ * Without it the server published `loading: false, status: "ready"` for a block it never ran,
1523
+ * which is not merely a different value, it is untrue: `data` is null because nothing has
1524
+ * been fetched yet, not because the answer is empty. That untruth is what a `loading` branch
1525
+ * and its `!loading && rows.length == 0` sibling BOTH read, so the server rendered the empty
1526
+ * state where the client renders the loading one, and every such pair was a hydration
1527
+ * mismatch (the Studio's navigator: "This project has no screens yet" server-side against
1528
+ * "Reading the project…" on the client). One law, asked on both planes. */
1529
+ export function apiPendingAtFirstRender(spec, store, item) {
1530
+ return truthy(materializeApiRequest(spec, store, item)["auto"]);
1531
+ }
1532
+ /** doc 02 out-of-order streaming: is this block one the STREAM runs after the initial
1533
+ * flush? Exactly the ssr-eligibility ladder with the defer arm inverted — a deferred
1534
+ * GET whose `ssr` flag is not explicitly false. Web-SSR infrastructure, like `ssr=`
1535
+ * itself: no native twin owed (the unified-codebase law's infrastructure exemption). */
1536
+ export function apiStreamEligible(spec) {
1537
+ const method = (spec.method ?? "GET").trim().toUpperCase();
1538
+ if (method !== "GET" || !apiDeferred(spec))
1539
+ return false;
1540
+ const raw = spec.ssr;
1541
+ if (raw === undefined)
1542
+ return true;
1543
+ const v = raw.trim().toLowerCase();
1544
+ return v === "" || v === "true" || v === "1";
1545
+ }
1546
+ const DEFAULT_SSR_TIMEOUT_MS = 5000;
1547
+ /** The key the server data cache files a materialized request under: the client's own parts. */
1548
+ export function ssrDataCacheKey(req) {
1549
+ return `${string(req["method"])}\u0001${string(req["url"])}\u0001${watchKey(req["headers"] ?? null)}\u0001${string(req["expect"] ?? "json")}`;
1550
+ }
1551
+ /** A request is PUBLIC (C2) when it names no identity: no authorization or cookie header, and no
1552
+ * `dsx.cookie` read while it materialized. The host adds the third condition, an anonymous
1553
+ * render, by handing a cache at all. */
1554
+ function publicRequest(req, readCookie) {
1555
+ if (readCookie)
1556
+ return false;
1557
+ const headers = isDict(req["headers"]) ? Object.keys(req["headers"]).map((h) => h.toLowerCase()) : [];
1558
+ return !headers.includes("authorization") && !headers.includes("cookie");
1559
+ }
1560
+ export async function executeApiForSSR(spec, store, item, opts = {}) {
1561
+ // `allowDeferred` is the STREAM pass (renderPageStream): the same execution, gated by
1562
+ // apiStreamEligible instead — a deferred block runs AFTER the initial flush there.
1563
+ if (!apiSsrEnabled(spec) &&
1564
+ !(opts.allowDeferred === true && apiStreamEligible(spec)))
1565
+ return { status: "skip" };
1566
+ let readCookie = false;
1567
+ const priorCookieRead = JSESeams.onCookieRead;
1568
+ JSESeams.onCookieRead = () => { readCookie = true; priorCookieRead?.(); };
1569
+ let req;
1570
+ try {
1571
+ req = materializeApiRequest(spec, store, item);
1572
+ }
1573
+ finally {
1574
+ JSESeams.onCookieRead = priorCookieRead;
1575
+ }
1576
+ if (string(req["method"]).toUpperCase() !== "GET")
1577
+ return { status: "skip" };
1578
+ if (!truthy(req["auto"]))
1579
+ return { status: "skip" }; // auto="false" is imperative-only
1580
+ // C1: THE SERVER HONOURS `<api cache>`. A public block with a max-age or swr policy is answered
1581
+ // from the server data cache while fresh (swr: within fresh + stale), and filled after a fetch.
1582
+ // A private one is never looked up and never stored (C2); `no-store` is neither.
1583
+ const policy = parseCache(apiWord(spec.cache, store, item));
1584
+ const cacheable = opts.dataCache !== undefined && policy.kind !== "no-store" && publicRequest(req, readCookie);
1585
+ const dataKey = cacheable ? ssrDataCacheKey(req) : "";
1586
+ if (cacheable) {
1587
+ let hit;
1588
+ try {
1589
+ hit = await opts.dataCache.get(dataKey);
1590
+ }
1591
+ catch {
1592
+ hit = undefined;
1593
+ } // a cache that cannot answer is a miss
1594
+ const nowAt = (opts.now ?? (() => Date.now()))();
1595
+ const window = policy.kind === "max-age" ? policy.age : policy.kind === "swr" ? policy.fresh + policy.stale : 0;
1596
+ if (hit !== undefined && nowAt - hit.at < window) {
1597
+ // swr past its fresh window: the stale answer is served now and ONE refetch refills the
1598
+ // entry behind it, which is what stale-while-revalidate means (the next render reads it).
1599
+ if (policy.kind === "swr" && nowAt - hit.at >= policy.fresh) {
1600
+ let target = string(req["url"]);
1601
+ if (opts.origin !== undefined && target.startsWith("/")) {
1602
+ try {
1603
+ target = new URL(target, opts.origin).href;
1604
+ }
1605
+ catch { /* doFetch reports */ }
1606
+ }
1607
+ const cache = opts.dataCache;
1608
+ void doFetch(target, req, null).then((fresh) => {
1609
+ if (truthy(fresh["ok"]) && !Array.isArray(fresh.stream)) {
1610
+ void Promise.resolve(cache.put(dataKey, { data: fresh["data"] ?? null, at: (opts.now ?? (() => Date.now()))(), resource: apiResourceKey(spec) })).catch(() => { });
1611
+ }
1612
+ }, () => { });
1613
+ }
1614
+ return { status: "seed", envelope: { data: hit.data, error: null, fetchedAt: hit.at } };
1615
+ }
1616
+ }
1617
+ const now = opts.now ?? (() => Date.now());
1618
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_SSR_TIMEOUT_MS;
1619
+ const controller = typeof AbortController !== "undefined" ? new AbortController() : null;
1620
+ let timer = null;
1621
+ const TIMEOUT = Symbol("ssr-timeout");
1622
+ const timeout = new Promise((resolve) => {
1623
+ timer = setTimeout(() => resolve(TIMEOUT), timeoutMs);
1624
+ });
1625
+ let res;
1626
+ try {
1627
+ // Prepare the request under the same guards as a live fire (body/header/url bounds).
1628
+ try {
1629
+ validateRequestMetadata(req);
1630
+ prepareRequestBody(req["body"]);
1631
+ }
1632
+ catch (error) {
1633
+ const failure = error;
1634
+ return { status: "client", code: failure.code ?? "invalid_request" };
1635
+ }
1636
+ // A SAME-ORIGIN URL IS THE DOCUMENTED SPELLING, and it is the one SSR could not run.
1637
+ // `<api url="/catalog/home">` is exactly what the reference shows, but server-side
1638
+ // `fetch` has no document to resolve a relative path against, so every such block
1639
+ // threw and fell open to the client — which meant a data-driven route's first paint
1640
+ // was ALWAYS its loading branch, however complete its SSR pass was. The render pass
1641
+ // knows the origin it is answering for; resolving against it here is what makes
1642
+ // seeding work for the common case. Absolute URLs are untouched, and an unparseable
1643
+ // pair falls through to the same fail-open path as before.
1644
+ let target = string(req["url"]);
1645
+ if (opts.origin !== undefined && target.startsWith("/")) {
1646
+ try {
1647
+ target = new URL(target, opts.origin).href;
1648
+ }
1649
+ catch { /* leave it; doFetch reports */ }
1650
+ }
1651
+ res = await Promise.race([doFetch(target, req, controller?.signal ?? null), timeout]);
1652
+ }
1653
+ catch {
1654
+ return { status: "client", code: "ssr_fetch_threw" };
1655
+ }
1656
+ finally {
1657
+ if (timer !== null)
1658
+ clearTimeout(timer);
1659
+ }
1660
+ if (res === TIMEOUT) {
1661
+ controller?.abort(); // bound even a seam/host that ignores the signal
1662
+ return { status: "client", code: "ssr_timeout" };
1663
+ }
1664
+ if (truthy(res["aborted"]))
1665
+ return { status: "client", code: "ssr_aborted" };
1666
+ // error-if judges a server-rendered answer exactly as the client would: an
1667
+ // error it names is never seeded, and an answer it accepts is, whatever its status
1668
+ const judged = Array.isArray(res.stream) ? undefined : apiErrorIf(spec["error-if"], res, store, item);
1669
+ if (judged === true)
1670
+ return { status: "client", code: "error_if" };
1671
+ if (!truthy(res["ok"]) && judged !== false) {
1672
+ return { status: "client", code: string(res["error"] ?? `http_${string(res["status"])}`) };
1673
+ }
1674
+ // A streamed SSR response collapses to its accumulated chunk array (doc 02 defers
1675
+ // true streaming — that seam stays client-side for now).
1676
+ const data = Array.isArray(res.stream) ? res.stream : (res["data"] ?? null);
1677
+ const at = now();
1678
+ if (cacheable) {
1679
+ try {
1680
+ await opts.dataCache.put(dataKey, { data, at, resource: apiResourceKey(spec) });
1681
+ }
1682
+ catch { /* a failed fill is a later miss */ }
1683
+ }
1684
+ return { status: "seed", envelope: { data, error: null, fetchedAt: at } };
1685
+ }
1686
+ // ── the block ────────────────────────────────────────────────────────────────────────
1687
+ export class ApiBlock {
1688
+ spec;
1689
+ store;
1690
+ item;
1691
+ onEvent;
1692
+ now;
1693
+ /** The declared cache policy, parsed once; null when `cache=` carries a hole and is read at
1694
+ * each use instead (`policy`). */
1695
+ staticPolicy;
1696
+ get policy() {
1697
+ return this.staticPolicy ?? parseCache(apiWord(this.spec.cache, this.store, this.item));
1698
+ }
1699
+ seed;
1700
+ builtAt;
1701
+ graph;
1702
+ egress;
1703
+ /** proposals/realtime.md R0: WHEN this block (re)connects is the shared reactive law,
1704
+ * reactive-request.ts; this class owns HOW (transport, cache, seed, envelope). */
1705
+ rr;
1706
+ /** stable UI Law 6: the cohort the read in flight belongs to (api-cohort.ts). */
1707
+ cohort = null;
1708
+ declaredError = null;
1709
+ /** what this block declares it reads (GET/HEAD) or changes (everything else) */
1710
+ resourceKey;
1711
+ isReader;
1712
+ constructor(spec, store, item, opts = {}) {
1713
+ if (!isStateIdentifier(spec.as)) {
1714
+ throw new TypeError("<api as> must be an ASCII identifier of at most 128 characters");
1715
+ }
1716
+ if (!store.vars.has(spec.as) && store.vars.size >= STATE_PATH_LIMITS.maxContainerEntries) {
1717
+ throw new RangeError("<api as> exceeds the store container-entry budget");
1718
+ }
1719
+ store.jse.apiNames.add(spec.as);
1720
+ this.spec = spec;
1721
+ this.store = store;
1722
+ this.item = item;
1723
+ this.onEvent = opts.onEvent ?? (() => { });
1724
+ this.now = opts.now ?? (() => Date.now());
1725
+ this.staticPolicy = spec.cache !== undefined && spec.cache.includes("{{") ? null : parseCache(spec.cache);
1726
+ this.seed = opts.seed;
1727
+ this.builtAt = opts.builtAt;
1728
+ this.graph = opts.graph ?? null;
1729
+ this.egress = opts.egress ?? null;
1730
+ this.resourceKey = apiResourceKey(spec);
1731
+ if (spec.strings !== undefined) {
1732
+ // THROUGH THE SEAM, not an import: the string tables bind it (strings.ts), so an embed
1733
+ // whose <api> never spells `strings=` ships no localization plane for it.
1734
+ JSESeams.remoteTableBlocks(1);
1735
+ // a server-seeded table is a table (L11): installed at mount, so hydration draws in it
1736
+ const seeded = opts.seed?.data;
1737
+ const tag = apiWord(spec.strings, store, item);
1738
+ if (seeded !== undefined && seeded !== null && tag !== undefined)
1739
+ JSESeams.remoteTableInstall(tag, seeded);
1740
+ }
1741
+ this.rr = new ReactiveRequest({
1742
+ as: spec.as,
1743
+ store,
1744
+ graph: this.graph,
1745
+ materialize: () => this.materialize(),
1746
+ identity: (req) => this.requestIdentity(req),
1747
+ hasData: () => this.hasData(),
1748
+ debounceMs: () => safeInt(number(apiWord(this.spec.debounce, this.store, this.item)) ?? 0),
1749
+ adoptFirst: (req) => {
1750
+ if (this.seed === undefined)
1751
+ return false;
1752
+ // SSR-seeded (doc 02): adopt the server-resolved data instead of issuing the
1753
+ // initial fetch. A later dep change / refresh() fetches normally.
1754
+ this.primeSeedCache(req);
1755
+ // proposals/static-data.md S4: the seed is drawn either way (the envelope was seeded
1756
+ // at construction); a cacheable policy is CONSULTED at the seed's age. Past max-age,
1757
+ // or in swr's stale window, the first run fires through the primed cache, so the
1758
+ // answer is revalidated with `refreshing` true and the baked data still drawn.
1759
+ return this.seedFresh();
1760
+ },
1761
+ fire: (req) => { void this.fire(req, { allowCache: true }); },
1762
+ });
1763
+ const declaredMethod = (apiWord(spec.method, store, item) ?? "GET").trim().toUpperCase();
1764
+ this.isReader = declaredMethod === "GET" || declaredMethod === "HEAD";
1765
+ if (this.isReader) {
1766
+ registerApiReader(store, this);
1767
+ // An author sees the cost of a url that names nothing WITHOUT waiting for a write.
1768
+ if (this.resourceKey === null)
1769
+ apiDiagnostics.undeclared.add(spec.url);
1770
+ }
1771
+ // seed the reserved paths — data null until first resolve (doc 05), OR the
1772
+ // SSR-resolved envelope when a hydration seed is supplied (doc 02). `status` +
1773
+ // `blockedBy` are doc 11's additions to the same reserved envelope.
1774
+ if (store.vars.get(spec.as) === undefined) {
1775
+ const seed = this.seed;
1776
+ store.set(spec.as, seed !== undefined
1777
+ ? { data: seed.data ?? null, loading: false, refreshing: false, error: seed.error ?? null, fetchedAt: this.seedAt(), status: seed.error != null ? "error" : "ready", blockedBy: [], progress: null }
1778
+ : { data: null, loading: false, refreshing: false, error: null, fetchedAt: null, status: "ready", blockedBy: [], progress: null });
1779
+ }
1780
+ // doc 11: a cycle / an unknown `needs=` is a DECLARED error — the block publishes it
1781
+ // and issues no request, because a silent forever-wait is the worse failure mode.
1782
+ if (this.graph !== null) {
1783
+ const cycle = this.graph.cycle;
1784
+ if (cycle !== null && cycle.includes(spec.as))
1785
+ this.declaredError = "cycle";
1786
+ else if (this.graph.unknownNeedsOf(spec.as).length > 0)
1787
+ this.declaredError = "unknown_needs";
1788
+ this.graph.attach(this, spec.as);
1789
+ }
1790
+ if (this.graph === null && opts.deferStart !== true)
1791
+ this.startEffect();
1792
+ }
1793
+ /** doc 11: the graph starts its blocks only once EVERY sibling has mounted, so the
1794
+ * runnable set is computed against the whole scope, not against mount order. */
1795
+ graphStart() {
1796
+ if (!this.rr.running)
1797
+ this.startEffect();
1798
+ }
1799
+ /** doc 02 out-of-order streaming: adopt a SERVER-resolved envelope that arrived over
1800
+ * the response stream AFTER this block mounted (web-SSR infrastructure, like `ssr=`).
1801
+ * Applied only while the block has not itself SETTLED (no fetchedAt, no error) — the
1802
+ * client's own resolved envelope always wins, never a backwards flash. An in-flight
1803
+ * initial fetch is superseded exactly like a stale response (generation bump + abort).
1804
+ * Fires `success` like any resolved-ok request (corpus law 7). Returns whether the
1805
+ * seed took. */
1806
+ seedLate(seed) {
1807
+ const as = this.spec.as;
1808
+ const current = this.store.vars.get(as);
1809
+ if (isDict(current)) {
1810
+ const cur = current;
1811
+ if (cur["fetchedAt"] != null || cur["error"] != null)
1812
+ return false;
1813
+ }
1814
+ this.rr.supersede();
1815
+ this.store.set(as, {
1816
+ data: seed.data ?? null, loading: false, refreshing: false,
1817
+ error: seed.error ?? null, fetchedAt: seed.fetchedAt ?? this.now(),
1818
+ status: seed.error != null ? "error" : "ready", blockedBy: [], progress: null,
1819
+ });
1820
+ this.emitEvent("success", { data: seed.data ?? null, status: 200, streamed: true });
1821
+ this.graph?.notifySettled(as);
1822
+ return true;
1823
+ }
1824
+ /** An upstream settled. Re-materialize + re-gate; the identity guard means an
1825
+ * unrelated settle, or a refetch that produced identical data, is a no-op. */
1826
+ graphReevaluate() {
1827
+ this.rr.reevaluate();
1828
+ }
1829
+ startEffect() {
1830
+ if (this.declaredError !== null) {
1831
+ this.publishDeclaredError(this.declaredError);
1832
+ return;
1833
+ }
1834
+ // the dependency effect: evaluating the request INSIDE the tracker makes its read
1835
+ // set the trigger; watchKey dedup means we refire only when the MATERIALIZED
1836
+ // request (or its doc-11 gate) changes — the cross-platform law the native twins
1837
+ // match by comparison
1838
+ this.rr.start();
1839
+ }
1840
+ /** evaluate url/headers/body/auto in the current scope (tracked) */
1841
+ materialize() {
1842
+ return materializeApiRequest(this.spec, this.store, this.item);
1843
+ }
1844
+ /** The identity the reactive law compares (reactive-request.ts). The ReactiveStore's generic
1845
+ * effect key must never recursively walk an unbounded authored body: validate/encode first,
1846
+ * then key on the bounded wire string. */
1847
+ requestIdentity(req) {
1848
+ try {
1849
+ this.prepareRequest(req);
1850
+ return `${string(req["method"])}${string(req["url"])}${watchKey(req["headers"] ?? null)}${string(req["__dsxBodyWire"] ?? "")}${string(req["expect"])}${watchKey(req["cookiePartition"] ?? null)}${truthy(req["auto"]) ? "1" : "0"}`;
1851
+ }
1852
+ catch (error) {
1853
+ const failure = error;
1854
+ req["__dsxRequestError"] = failure.code ?? "invalid_request";
1855
+ const rawBody = req["body"];
1856
+ const bodyShape = typeof rawBody === "string" ? `string:${rawBody.length}` : typeof rawBody;
1857
+ return `error${string(req["method"])}${string(req["url"]).slice(0, MAX_API_URL_BYTES)}${string(req["__dsxRequestError"])}${bodyShape}${truthy(req["auto"]) ? "1" : "0"}`;
1858
+ }
1859
+ }
1860
+ /** THE MATERIALIZED REQUEST, READ FROM OUTSIDE. The devtools state door's api plane shows a
1861
+ * person the url their expression actually PRODUCED, which is the one line on a response
1862
+ * panel no other surface can answer — `url=` is a template and `{{ … }}` is what a reader
1863
+ * cannot evaluate in their head.
1864
+ *
1865
+ * It is `materializeApiRequest`'s answer and nothing else, which is the whole reason this
1866
+ * method exists rather than a second pass at the door: the tracked request when the effect
1867
+ * holds one (the request this block last materialized, prepared exactly as it would be
1868
+ * sent), and a fresh materialization when it does not (the request it WOULD send). A reader
1869
+ * that re-evaluated `url`/`headers` itself would be a second opinion about what the block
1870
+ * requests, and doc 05 keeps that to one function on purpose — the SSR prefetch is the other
1871
+ * caller, and it exists so an SSR run issues byte-for-byte the request the client would.
1872
+ *
1873
+ * A COPY, because `fire` MUTATES the request it is handed (a body override, the encoded wire
1874
+ * body and its content-type) and a reader must not be able to reach into the block's own. */
1875
+ request() {
1876
+ return { ...(this.rr.trackedRequest ?? this.materialize()) };
1877
+ }
1878
+ /** SSR-seeded blocks skip the first fetch; on a cacheable policy, prime the cache
1879
+ * with the seed so a same-request revisit inside the fresh window is a hit, not a
1880
+ * network call (doc 02: "the client marks them fresh per cache"). */
1881
+ primeSeedCache(req) {
1882
+ if (!(globalThis.__DSX_OPTIONAL_API_CACHE__ !== false))
1883
+ return;
1884
+ if (this.seed === undefined || this.policy.kind === "no-store")
1885
+ return;
1886
+ try {
1887
+ this.prepareRequest(req);
1888
+ cachePut(this.store, this.cacheKey(req), { data: this.seed.data ?? null, at: this.seedAt() ?? this.now(), resource: this.resourceKey });
1889
+ }
1890
+ catch { /* a bad request just means no cache prime — the seed still stands */ }
1891
+ }
1892
+ /** When the seed's answer was made: its own `fetchedAt`, else the build's `builtAt`, else
1893
+ * unknown (null). */
1894
+ seedAt() {
1895
+ const at = this.seed?.fetchedAt;
1896
+ if (typeof at === "number" && Number.isFinite(at))
1897
+ return at;
1898
+ return typeof this.builtAt === "number" && Number.isFinite(this.builtAt) ? this.builtAt : null;
1899
+ }
1900
+ /** proposals/static-data.md S4: does the seed stand on mount? no-store: always (a static
1901
+ * answer is the answer). max-age(d): while younger than d. swr(f, s): while younger than f.
1902
+ * A seed of unknown age stands (the pre-S4 behaviour). */
1903
+ seedFresh() {
1904
+ if (!(globalThis.__DSX_OPTIONAL_API_CACHE__ !== false))
1905
+ return true;
1906
+ const policy = this.policy;
1907
+ if (policy.kind === "no-store")
1908
+ return true;
1909
+ const at = this.seedAt();
1910
+ if (at === null)
1911
+ return true;
1912
+ const age = this.now() - at;
1913
+ return policy.kind === "max-age" ? age < policy.age : age < policy.fresh;
1914
+ }
1915
+ prepareRequest(req) {
1916
+ validateRequestMetadata(req);
1917
+ const prepared = prepareRequestBody(req["body"]);
1918
+ req["__dsxBodyWire"] = prepared.wire;
1919
+ req["__dsxBodyKey"] = prepared.key;
1920
+ }
1921
+ /** doc 11: a cycle, or a `needs=` naming a block that is not in this scope. */
1922
+ publishDeclaredError(message) {
1923
+ const as = this.spec.as;
1924
+ const error = { status: -3, message, body: null };
1925
+ this.store.batch(() => {
1926
+ this.store.setPath(`${as}.loading`, false);
1927
+ this.store.setPath(`${as}.refreshing`, false);
1928
+ this.store.setPath(`${as}.status`, "error");
1929
+ this.store.setPath(`${as}.blockedBy`, []);
1930
+ this.store.setPath(`${as}.error`, error);
1931
+ });
1932
+ this.emitEvent("error", { error });
1933
+ }
1934
+ /** networking.md N2 "Progress": each entry publishes `<as>.progress` and fires
1935
+ * `on:progress` BEFORE the terminal settle. Real transports deliver them one at a
1936
+ * time; the seamed corpus carries them on the response envelope. */
1937
+ publishProgress(entries) {
1938
+ if (!Array.isArray(entries))
1939
+ return;
1940
+ for (const raw of entries) {
1941
+ if (!isDict(raw))
1942
+ continue;
1943
+ const entry = raw;
1944
+ const loaded = number(entry["loaded"]) ?? 0;
1945
+ const total = number(entry["total"]) ?? 0;
1946
+ const progress = {
1947
+ direction: string(entry["direction"] ?? "down"),
1948
+ loaded,
1949
+ total,
1950
+ fraction: total > 0 ? loaded / total : 0,
1951
+ };
1952
+ this.store.setPath(`${this.spec.as}.progress`, progress);
1953
+ this.emitEvent("progress", { progress });
1954
+ }
1955
+ }
1956
+ cacheKey(req) {
1957
+ // \u0001-delimited (the ApiBlock.kt / ApiBlock.swift twins), so
1958
+ // `PU`+`T/x` and `PUT`+`/x` cannot collide. Headers are part of the
1959
+ // materialized request: an Authorization/user switch must never receive a
1960
+ // prior identity's cached response. The cache itself is scoped to this
1961
+ // ReactiveStore and bounded, so route/session teardown releases it.
1962
+ return `${string(req["method"])}${string(req["url"])}${watchKey(req["headers"] ?? null)}${string(req["__dsxBodyKey"] ?? "∅")}${string(req["expect"] ?? "json")}${watchKey(req["cookiePartition"] ?? null)}`;
1963
+ }
1964
+ emitEvent(name, payload) {
1965
+ try {
1966
+ this.onEvent(name, payload);
1967
+ }
1968
+ catch (error) {
1969
+ // Author event logic is downstream of the transport. It must not abort an
1970
+ // otherwise valid response or starve later stream messages.
1971
+ console.warn("[dsx api]", name, error);
1972
+ }
1973
+ // the call's own handler, additive to the tag's (reference/jse.md)
1974
+ try {
1975
+ const binding = this.listener;
1976
+ if (binding !== null)
1977
+ binding.done = binding.fn(name, payload);
1978
+ }
1979
+ catch (error) {
1980
+ console.warn("[dsx api]", name, error);
1981
+ }
1982
+ }
1983
+ serveCached(entry) {
1984
+ if (!(globalThis.__DSX_OPTIONAL_API_CACHE__ !== false))
1985
+ return;
1986
+ const as = this.spec.as;
1987
+ this.store.batch(() => {
1988
+ this.store.setPath(`${as}.loading`, false);
1989
+ this.store.setPath(`${as}.refreshing`, false);
1990
+ this.store.setPath(`${as}.data`, entry.data);
1991
+ this.store.setPath(`${as}.error`, null);
1992
+ this.store.setPath(`${as}.fetchedAt`, entry.at);
1993
+ this.store.setPath(`${as}.status`, "ready");
1994
+ });
1995
+ this.emitEvent("success", { data: entry.data, status: 200, cached: true });
1996
+ this.graph?.notifySettled(as);
1997
+ }
1998
+ disposedTable = false;
1999
+ /** L11: a `strings` block's answer is a table. After every fire, a ready answer installs it for
2000
+ * the tag the block names now, and an error releases that tag's hold. */
2001
+ async fire(req, opts) {
2002
+ if (!this.isReader)
2003
+ return this.fireStrings(req, opts);
2004
+ // COALESCE: the reader's
2005
+ // request in flight is remembered by its identity, so an explicit call with the same identity
2006
+ // joins it instead of sending a second identical request. Twins: ApiBlock.kt/.swift, whose
2007
+ // post-render publish never refires a request a manual call already holds.
2008
+ const id = this.requestIdentity(req);
2009
+ if (this.inflightRead !== null && this.inflightRead.id === id)
2010
+ return this.inflightRead.promise;
2011
+ const entry = { id, promise: undefined };
2012
+ entry.promise = this.fireStrings(req, opts);
2013
+ this.inflightRead = entry;
2014
+ try {
2015
+ return await entry.promise;
2016
+ }
2017
+ finally {
2018
+ if (this.inflightRead === entry)
2019
+ this.inflightRead = null;
2020
+ }
2021
+ }
2022
+ inflightRead = null;
2023
+ async fireStrings(req, opts) {
2024
+ if (this.spec.strings === undefined)
2025
+ return this.fireIn(req, opts);
2026
+ const out = await this.fireIn(req, opts);
2027
+ const tag = apiWord(this.spec.strings, this.store, this.item);
2028
+ if (tag !== undefined && tag.trim().length > 0 && out !== null && out !== undefined) {
2029
+ const status = this.store.getPath(`${this.spec.as}.status`);
2030
+ if (status === "ready")
2031
+ JSESeams.remoteTableInstall(tag, this.store.getPath(`${this.spec.as}.data`));
2032
+ else if (status === "error")
2033
+ JSESeams.remoteTableFailed(tag);
2034
+ }
2035
+ return out;
2036
+ }
2037
+ async fireIn(req, opts) {
2038
+ // a fire adopts the handlers of the call that started it, and nothing else inherits them
2039
+ this.listener = this.pendingListener;
2040
+ this.pendingListener = null;
2041
+ try {
2042
+ // send(bodyOverride) changes the body after materialization; always prepare
2043
+ // at the fire boundary so the override receives the same guards.
2044
+ this.prepareRequest(req);
2045
+ delete req["__dsxRequestError"];
2046
+ }
2047
+ catch (error) {
2048
+ const failure = error;
2049
+ return this.failRequest(failure.code ?? "invalid_request");
2050
+ }
2051
+ // Capture identity before starting I/O. A Set-Cookie/login transition while
2052
+ // the request is in flight must not seed the response under the new session.
2053
+ const key = this.cacheKey(req);
2054
+ // the cache gate (auto fires only — send/refresh force the network)
2055
+ if ((globalThis.__DSX_OPTIONAL_API_CACHE__ !== false) && opts.allowCache === true && opts.forceNetwork !== true && this.policy.kind !== "no-store") {
2056
+ const entry = cacheGet(this.store, key);
2057
+ if (entry !== undefined) {
2058
+ const age = this.now() - entry.at;
2059
+ if (this.policy.kind === "max-age" && age < this.policy.age) {
2060
+ // A cache hit is still a winning request generation. Without this,
2061
+ // an older network response can arrive later and overwrite it.
2062
+ this.rr.supersede();
2063
+ this.serveCached(entry);
2064
+ return { ok: true, status: 200, data: entry.data, cached: true };
2065
+ }
2066
+ if (this.policy.kind === "swr") {
2067
+ if (age < this.policy.fresh) {
2068
+ this.rr.supersede();
2069
+ this.serveCached(entry);
2070
+ return { ok: true, status: 200, data: entry.data, cached: true };
2071
+ }
2072
+ if (age < this.policy.fresh + this.policy.stale) {
2073
+ this.serveCached(entry); // serve stale NOW …
2074
+ return this.network(req, { refreshing: true }, key); // … revalidate in the background
2075
+ }
2076
+ }
2077
+ }
2078
+ }
2079
+ // stable-ui Law 2: `.loading` means NOTHING TO SHOW YET. A fetch that starts while
2080
+ // `.data` is present is a refresh on every path (auto, dependency change, manual), so a
2081
+ // loading face never appears over content that is still drawn; and a fetch that starts
2082
+ // with nothing to draw is a load on every path, the manual GET call included. A submit
2083
+ // (non-GET) keeps `.loading` for every send: that flag is its pending action. Twins: ApiBlock.kt and
2084
+ // ApiBlock.swift `fire`; corpus row `a-refetch-with-data-is-a-refresh`.
2085
+ return this.network(req, { refreshing: this.isReader ? this.hasData() : opts.refreshing === true }, key);
2086
+ }
2087
+ /** stable-ui Law 2: the envelope holds something a surface can draw. A reader's `.data` is
2088
+ * content; a submit's is the last response, and its `.loading` stays the pending action. */
2089
+ hasData() {
2090
+ if (!this.isReader)
2091
+ return false;
2092
+ const data = this.store.getPath(`${this.spec.as}.data`);
2093
+ return data !== null && data !== undefined && data !== NSNull;
2094
+ }
2095
+ failRequest(code) {
2096
+ this.rr.supersede();
2097
+ const error = { status: -2, message: code, body: null };
2098
+ this.store.batch(() => {
2099
+ this.store.setPath(`${this.spec.as}.loading`, false);
2100
+ this.store.setPath(`${this.spec.as}.refreshing`, false);
2101
+ this.store.setPath(`${this.spec.as}.error`, error);
2102
+ this.store.setPath(`${this.spec.as}.fetchedAt`, this.now());
2103
+ this.store.setPath(`${this.spec.as}.status`, "error");
2104
+ });
2105
+ this.emitEvent("error", { error });
2106
+ this.graph?.notifySettled(this.spec.as);
2107
+ return { ok: false, status: -2, data: null, error: code };
2108
+ }
2109
+ async network(req, opts, cacheKey) {
2110
+ // stable UI Law 6 (api-cohort.ts): this read joins the cohort of the stretch it starts in,
2111
+ // and its answer commits with the others that started there.
2112
+ leaveApiCohort(this.cohort);
2113
+ const member = joinApiCohort();
2114
+ this.cohort = member;
2115
+ try {
2116
+ return await this.networkIn(member, req, opts, cacheKey);
2117
+ }
2118
+ finally {
2119
+ leaveApiCohort(member);
2120
+ if (this.cohort === member)
2121
+ this.cohort = null;
2122
+ }
2123
+ }
2124
+ async networkIn(member, req, opts, cacheKey) {
2125
+ const { gen, signal } = this.rr.begin(); // abort-stale — the newest request wins
2126
+ const as = this.spec.as;
2127
+ this.store.batch(() => {
2128
+ this.store.setPath(`${as}.${opts.refreshing ? "refreshing" : "loading"}`, true);
2129
+ this.store.setPath(`${as}.status`, opts.refreshing ? "refreshing" : "loading");
2130
+ });
2131
+ // strict base-10 integer, exactly like the natives (Kotlin toIntOrNull / Swift Int()):
2132
+ // `retry="2.5"` or `"2e1"` is NOT a count (→ 0 retries), never 3 or 21 attempts.
2133
+ const retryAttr = (apiWord(this.spec.retry, this.store, this.item) ?? "").trim();
2134
+ const retries = /^-?\d+$/.test(retryAttr) ? Math.max(0, parseInt(retryAttr, 10)) : 0;
2135
+ let res = { ok: false, status: 0, data: null };
2136
+ const streamedChunks = [];
2137
+ // proposals/realtime.md R1: a LIVE stream stays open. EOF and a drop both reconnect, with the
2138
+ // stream's own `Last-Event-ID`; the resume state lives in THIS call, so it belongs to this
2139
+ // materialized request and is never carried to a different one (R0 step 4).
2140
+ const live = (globalThis.__DSX_OPTIONAL_API_STREAMS__ !== false) && req["stream"] === "live";
2141
+ let lastEventId = null;
2142
+ let serverRetryMs = null;
2143
+ let deliveredThisConnection = false;
2144
+ let streamError = null;
2145
+ const keepLimit = () => {
2146
+ const raw = this.spec.keep;
2147
+ const fallback = live ? 128 : null;
2148
+ if (raw === undefined || raw.trim() === "")
2149
+ return fallback;
2150
+ const text = raw.includes("{{") ? interpolateGated(raw, this.store, this.item, []) : raw;
2151
+ const n = Number(text.trim());
2152
+ return Number.isFinite(n) && n >= 0 ? Math.floor(n) : fallback;
2153
+ };
2154
+ // Undeclared finite SSE still sniffs Content-Type. Only live-only machinery may fold.
2155
+ const deliverStreamMessage = (chunk, persistent = false, meta) => {
2156
+ if (!this.rr.isCurrent(gen))
2157
+ return;
2158
+ leaveApiCohort(member); // Law 6: a stream is delivered as it arrives and holds nobody
2159
+ const event = meta?.event ?? "message";
2160
+ const id = meta?.id ?? null;
2161
+ if (id !== null && id !== lastEventId) {
2162
+ lastEventId = id;
2163
+ this.store.setPath(`${as}.lastEventId`, id);
2164
+ }
2165
+ if (event === "error") {
2166
+ // realtime.md R1.4: the server's `event: error` frame is the envelope's error
2167
+ streamError = { status: 200, message: "stream_error", body: chunk };
2168
+ this.store.batch(() => {
2169
+ this.store.setPath(`${as}.loading`, false);
2170
+ this.store.setPath(`${as}.refreshing`, false);
2171
+ this.store.setPath(`${as}.error`, { status: 200, message: "stream_error", body: chunk });
2172
+ this.store.setPath(`${as}.status`, "error");
2173
+ });
2174
+ this.emitEvent("error", { status: 200, message: "stream_error", body: chunk });
2175
+ return;
2176
+ }
2177
+ deliveredThisConnection = true;
2178
+ streamedChunks.push(chunk);
2179
+ const limit = persistent && !live && this.spec.keep === undefined ? 128 : keepLimit();
2180
+ if (limit !== null && streamedChunks.length > limit)
2181
+ streamedChunks.splice(0, streamedChunks.length - limit);
2182
+ this.store.batch(() => {
2183
+ this.store.setPath(`${as}.data`, [...streamedChunks]);
2184
+ // A persistent stream may never reach EOF. The first delivered event is
2185
+ // enough to leave the initial loading/refreshing posture.
2186
+ this.store.setPath(`${as}.loading`, false);
2187
+ this.store.setPath(`${as}.refreshing`, false);
2188
+ this.store.setPath(`${as}.error`, null);
2189
+ this.store.setPath(`${as}.fetchedAt`, this.now());
2190
+ if (live) {
2191
+ this.store.setPath(`${as}.status`, "ready");
2192
+ this.store.setPath(`${as}.reconnectAttempt`, 0);
2193
+ }
2194
+ });
2195
+ this.emitEvent("message", { data: chunk, event, id });
2196
+ };
2197
+ const onStreamRetry = (ms) => { serverRetryMs = ms; };
2198
+ if (this.egress !== null && !this.egress(string(req["url"]))) {
2199
+ // the refused-egress answer, the fetchFunnel shape verbatim: it never left the process
2200
+ res = { ok: false, status: -2, data: null, error: "invalid_request" };
2201
+ }
2202
+ else {
2203
+ let reconnectAttempt = 0;
2204
+ for (let attempt = 0; attempt <= retries; attempt++) {
2205
+ const wire = live && lastEventId !== null
2206
+ ? { ...req, headers: { ...(isDict(req["headers"]) ? req["headers"] : {}), "Last-Event-ID": lastEventId } }
2207
+ : req;
2208
+ deliveredThisConnection = false;
2209
+ const onLiveReady = () => {
2210
+ if (!this.rr.isCurrent(gen))
2211
+ return;
2212
+ this.store.batch(() => {
2213
+ this.store.setPath(`${as}.loading`, false);
2214
+ this.store.setPath(`${as}.refreshing`, false);
2215
+ this.store.setPath(`${as}.status`, "ready");
2216
+ this.store.setPath(`${as}.error`, null);
2217
+ this.store.setPath(`${as}.fetchedAt`, this.now());
2218
+ if (streamedChunks.length === 0)
2219
+ this.store.setPath(`${as}.data`, []);
2220
+ });
2221
+ this.graph?.notifySettled(as);
2222
+ };
2223
+ const wireFetch = (sig) => doFetch(string(req["url"]), wire, sig, deliverStreamMessage, (globalThis.__DSX_OPTIONAL_API_STREAMS__ !== false) ? onLiveReady : undefined, (globalThis.__DSX_OPTIONAL_API_STREAMS__ !== false) ? onStreamRetry : undefined);
2224
+ res = sharesInFlight(req)
2225
+ ? await sharedRead(this.store, cacheKey, signal, wireFetch)
2226
+ : await wireFetch(signal);
2227
+ if (truthy(res["aborted"]))
2228
+ return null; // superseded — the newer request owns the store
2229
+ if (live && this.rr.isCurrent(gen) && liveShouldReconnect(res)) {
2230
+ // realtime.md R1.2: the WebSocket module's ladder, floored by the server's `retry:`.
2231
+ // `attempt` is held at zero: a live stream is not bounded by `retry=`, it is bounded
2232
+ // by the author (cancel, unmount, an input change) and by a terminal answer.
2233
+ reconnectAttempt = deliveredThisConnection ? 1 : reconnectAttempt + 1;
2234
+ const ladder = ApiStreamClock.random() * Math.min(2 ** (reconnectAttempt - 1), 30) * 1000;
2235
+ const delay = Math.max(ladder, serverRetryMs ?? 0);
2236
+ this.store.batch(() => {
2237
+ this.store.setPath(`${as}.status`, "waitingReconnect");
2238
+ this.store.setPath(`${as}.reconnectAttempt`, reconnectAttempt);
2239
+ });
2240
+ const woke = await abortableSleep(delay, signal);
2241
+ if (!woke || !this.rr.isCurrent(gen))
2242
+ return null;
2243
+ attempt = -1;
2244
+ continue;
2245
+ }
2246
+ if (truthy(res["ok"]) || (number(res["status"]) ?? 0) !== 0)
2247
+ break; // only network errors retry
2248
+ }
2249
+ }
2250
+ if (!this.rr.isCurrent(gen))
2251
+ return null; // superseded while awaiting
2252
+ // ERROR-IF: the author's test replaces the status test,
2253
+ // both ways, for an answered response; the error then takes the whole error path below
2254
+ // (error envelope, status "error", on:error, stale data kept, nothing cached, no targeted
2255
+ // invalidation). A streamed answer is judged by its frames (`event: error`), not here.
2256
+ if (!Array.isArray(res.stream)) {
2257
+ const judged = apiErrorIf(this.spec["error-if"], res, this.store, this.item);
2258
+ if (judged === true && truthy(res["ok"]))
2259
+ res = { ...res, ok: false, error: "error_if" };
2260
+ else if (judged === false && !truthy(res["ok"]))
2261
+ res = { ...res, ok: true };
2262
+ }
2263
+ // stable UI Law 6: a streamed answer is delivered as it arrives and never waits; any other
2264
+ // answer waits for the rest of its cohort (at most 300 ms after the first one settled).
2265
+ if (!(truthy(res["ok"]) && Array.isArray(res.stream))) {
2266
+ const gate = arriveApiCohort(member);
2267
+ if (gate !== null) {
2268
+ await gate;
2269
+ if (!this.rr.isCurrent(gen))
2270
+ return null; // superseded while its cohort settled
2271
+ }
2272
+ }
2273
+ // networking.md N2: progress entries publish + fire BEFORE the terminal settle
2274
+ this.publishProgress(res["progress"]);
2275
+ // streamed responses: chunks append to data, message per chunk (seam or SSE)
2276
+ if (truthy(res["ok"]) && Array.isArray(res.stream)) {
2277
+ const chunks = truthy(res.streamDelivered) ? streamedChunks : [];
2278
+ if (!truthy(res.streamDelivered)) {
2279
+ for (const chunk of res.stream) {
2280
+ chunks.push(chunk);
2281
+ this.store.setPath(`${as}.data`, [...chunks]);
2282
+ this.emitEvent("message", { data: chunk, event: "message", id: null });
2283
+ }
2284
+ }
2285
+ this.store.batch(() => {
2286
+ this.store.setPath(`${as}.loading`, false);
2287
+ this.store.setPath(`${as}.refreshing`, false);
2288
+ // realtime.md R1.4: a stream the server failed with an `event: error` frame settles in
2289
+ // error, with whatever it delivered before the frame still drawn
2290
+ this.store.setPath(`${as}.error`, streamError);
2291
+ if (streamError !== null)
2292
+ this.store.setPath(`${as}.data`, [...chunks]);
2293
+ this.store.setPath(`${as}.fetchedAt`, this.now());
2294
+ this.store.setPath(`${as}.status`, streamError === null ? "ready" : "error");
2295
+ });
2296
+ if (streamError !== null) {
2297
+ this.graph?.notifySettled(as);
2298
+ return res;
2299
+ }
2300
+ const method = string(req["method"]).toUpperCase();
2301
+ if (method !== "GET" && method !== "HEAD") {
2302
+ notifyApiWrite(this.store, this.resourceKey);
2303
+ }
2304
+ else if ((globalThis.__DSX_OPTIONAL_API_CACHE__ !== false) && this.policy.kind !== "no-store") {
2305
+ cachePut(this.store, cacheKey, { data: chunks, at: this.now(), resource: this.resourceKey });
2306
+ }
2307
+ this.emitEvent("success", { data: chunks, status: number(res["status"]) ?? 200 });
2308
+ this.graph?.notifySettled(as);
2309
+ return res;
2310
+ }
2311
+ this.store.batch(() => {
2312
+ this.store.setPath(`${as}.loading`, false);
2313
+ this.store.setPath(`${as}.refreshing`, false);
2314
+ this.store.setPath(`${as}.fetchedAt`, this.now());
2315
+ this.store.setPath(`${as}.status`, truthy(res["ok"]) ? "ready" : "error");
2316
+ if (truthy(res["ok"])) {
2317
+ this.store.setPath(`${as}.data`, res["data"] ?? null);
2318
+ this.store.setPath(`${as}.error`, null);
2319
+ }
2320
+ else {
2321
+ this.store.setPath(`${as}.error`, {
2322
+ status: number(res["status"]) ?? 0,
2323
+ message: string(res["error"] ?? `http ${string(res["status"])}`),
2324
+ body: res["data"] ?? null,
2325
+ });
2326
+ }
2327
+ });
2328
+ if (truthy(res["ok"])) {
2329
+ const method = string(req["method"]).toUpperCase();
2330
+ if (method !== "GET" && method !== "HEAD") {
2331
+ // The write names the resource it changed; the readers that declared a
2332
+ // dependency on it drop their entries and revalidate, and nobody else moves.
2333
+ // A write that rotates an implicit session touches more than the route it posts
2334
+ // to: that write declares `depends="/"` and the whole surface refetches.
2335
+ notifyApiWrite(this.store, this.resourceKey);
2336
+ }
2337
+ else if ((globalThis.__DSX_OPTIONAL_API_CACHE__ !== false) && this.policy.kind !== "no-store") {
2338
+ cachePut(this.store, cacheKey, { data: res["data"] ?? null, at: this.now(), resource: this.resourceKey });
2339
+ }
2340
+ this.emitEvent("success", { data: res["data"] ?? null, status: number(res["status"]) ?? 200 });
2341
+ }
2342
+ else {
2343
+ this.emitEvent("error", {
2344
+ error: { status: number(res["status"]) ?? 0, message: string(res["error"] ?? `http ${string(res["status"])}`), body: res["data"] ?? null },
2345
+ });
2346
+ }
2347
+ // doc 11: this block settled — its dependents fire the moment THEIR inputs are whole.
2348
+ this.graph?.notifySettled(as);
2349
+ return res;
2350
+ }
2351
+ /** THE INVOKE FACE, and the only verb a document reaches (`await dsx.api.<as>(args?)`).
2352
+ * ONE word, because the declaration already says what the request IS: a GET called is the
2353
+ * re-read `rerun` performs, a non-GET called is the submit `submit` performs, and `args` is
2354
+ * the optional body override a submit accepts. `refresh` and `send` were two names for one
2355
+ * idea whose difference was already written in `method=`, so the author had to restate it
2356
+ * at every call site and could state it WRONGLY; they are retired, not aliased (constitution
2357
+ * "Experimental release compatibility policy"), and no runner dispatches them under any
2358
+ * spelling. Twins: ApiBlock.kt `call`, ApiBlock.swift `call`. */
2359
+ async call(args, listener) {
2360
+ if (listener === undefined)
2361
+ return this.isReader ? await this.rerun() : await this.submit(args);
2362
+ // THE CALL'S OWN HANDLERS (reference/jse.md): bound to the request this call
2363
+ // fires and to nothing after it. Any later fire (a dependency refetch, another call)
2364
+ // replaces the binding, and the call settling releases it.
2365
+ const binding = { fn: listener, done: undefined };
2366
+ this.pendingListener = binding;
2367
+ try {
2368
+ const answer = this.isReader ? await this.rerun() : await this.submit(args);
2369
+ await binding.done; // the call answers after its own handlers ran, in order
2370
+ return answer;
2371
+ }
2372
+ finally {
2373
+ if (this.listener === binding)
2374
+ this.listener = null;
2375
+ if (this.pendingListener === binding)
2376
+ this.pendingListener = null;
2377
+ }
2378
+ }
2379
+ /** The call handlers of the request in flight, and the ones the next `fire` adopts. */
2380
+ listener = null;
2381
+ pendingListener = null;
2382
+ /** re-run now - revalidates (bypasses freshness, rewrites cache); data stays until it
2383
+ * resolves. Answers the same `{ ok, status, data | error }` envelope a submit answers, so
2384
+ * `await dsx.api.<as>()` reads one way whatever the declaration's method is. */
2385
+ async rerun() {
2386
+ return this.fire(this.materialize(), { refreshing: true, forceNetwork: true });
2387
+ }
2388
+ /** fire with a body override; mutations always hit the network (awaitable envelope).
2389
+ * doc 11: a manual submit IGNORES gating but not HOLES - submitting with a hole in the
2390
+ * inputs returns an `incomplete_input` envelope instead of a malformed request. */
2391
+ async submit(args) {
2392
+ const req = this.materialize();
2393
+ if (args !== undefined && args !== null)
2394
+ req["body"] = args;
2395
+ const missing = req["_missing"];
2396
+ if (Array.isArray(missing) && missing.length > 0) {
2397
+ return { ok: false, status: -3, data: null, error: { kind: "incomplete_input", missing: [...missing] } };
2398
+ }
2399
+ return this.fire(req, { forceNetwork: true });
2400
+ }
2401
+ cancel() {
2402
+ leaveApiCohort(this.cohort); // Law 6: a cancelled read never holds its cohort
2403
+ this.cohort = null;
2404
+ this.inflightRead = null;
2405
+ this.rr.cancelTimer();
2406
+ this.rr.supersede(); // orphan anything in flight
2407
+ this.store.batch(() => {
2408
+ this.store.setPath(`${this.spec.as}.loading`, false);
2409
+ this.store.setPath(`${this.spec.as}.refreshing`, false);
2410
+ if (string(this.store.getPath(`${this.spec.as}.status`)) !== "error") {
2411
+ this.store.setPath(`${this.spec.as}.status`, "ready");
2412
+ }
2413
+ });
2414
+ }
2415
+ dispose() {
2416
+ if (this.spec.strings !== undefined && !this.disposedTable) {
2417
+ this.disposedTable = true;
2418
+ JSESeams.remoteTableBlocks(-1);
2419
+ }
2420
+ this.cancel();
2421
+ this.rr.dispose();
2422
+ this.graph?.detach(this.spec.as);
2423
+ if (this.isReader)
2424
+ unregisterApiReader(this.store, this);
2425
+ }
2426
+ /** A write this block declared a dependency on landed: revalidate. A block the author
2427
+ * fires by hand stays the author's to fire, and doc 11's gate still holds: a block
2428
+ * whose inputs are not whole never issues a request, write or no write. */
2429
+ invalidatedByWrite() {
2430
+ if (!(globalThis.__DSX_OPTIONAL_API_INVALIDATION__ !== false))
2431
+ return;
2432
+ if (!this.rr.running || this.declaredError !== null)
2433
+ return;
2434
+ if (this.rr.trackedBlocked.length > 0)
2435
+ return;
2436
+ const req = this.rr.trackedRequest;
2437
+ if (req !== null && !truthy(req["auto"]))
2438
+ return;
2439
+ void this.rerun();
2440
+ }
2441
+ }
2442
+ //# sourceMappingURL=api.js.map