gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit5b0b4b9e5b0b4b9ereadme-cache gate: use the security gate's ports when no own ports are givenmre5b0b4b9e/plugins/web/WebFramework.hl

240.8 KB

  1. // The framework's server half — the SERVER REALM's entrypoint, and the EDGE
  2. // MODULE for the carriers the manifest declares.
  3. // Its jobs: answer a URL with the HTML of a constructed component (SSR), ship
  4. // the browser the client, the View tree and the state to continue from, carry
  5. // the boundary in both directions (a websocket on the same port, a POST for a
  6. // peer that has none), and run the server faces an inbound emit names.
  7. import { NativeWebSocketServer, Response, randomToken } from 'hl:http1'
  8. import HlwView from './view.hl'
  9. import HlwRouter from './router.hl'
  10. import HlwSessions from './sessions.hl'
  11. import HlwSession from './session.hl'
  12. // the Style walk — named Css here because `Style` is a well-known MEMBER name
  13. import HlwCss from './css.hl'
  14. import HlwCompile from './compile.hl'
  15. import { readFile, exists, watch } from 'hl:fs'
  16. import { file, env, setEnv, args } from 'hl:proc'
  17. import { now } from 'hl:time'
  18. import { sha256, base64urlDecode, base64urlEncode, p256PublicKey } from 'hl:crypto'
  19. // the statics of push.hl that server.hl (the app's import of sendPush) and the app use are named here: a package
  20. // file's statics are live only for the names the framework's own import selects
  21. import { configure as configurePush, sendPush as pushSender } from './push.hl'
  22. import { newline, tab } from './view.hl'
  23. Hybrid routes = [] // bound by `new WebFrameworkServer(routes = …)`
  24. // THE PROJECT'S STYLES FILE, declared by the app as a property of the framework:
  25. // `new WebFrameworkServer(…, styles = './styles.hl')`. A file of statics and one
  26. // `Style { }` root member (COMPONENTS §4) — the design tokens and the global
  27. // rules, under every component's own Style in the one stylesheet. null: none.
  28. styles = null // the app's styles file: the class it imported, or a path
  29. // WHO AN OUTWARD EVENT IS FOR (creator, 2026-09-12): per event, a function the app
  30. // declares — `audience = { postCreated = (p, session) => … }` — called for every
  31. // connection that has a listener for the event mounted, with the event's
  32. // arguments and that connection's session; a true answer sends the frame. An
  33. // event with no entry reaches the emitting connection only. Only the app knows
  34. // who is entitled; the face stays pure; the framework applies the answer.
  35. Hybrid audience = {}
  36. // THE SESSION STORE (the archive's manifest members, mission 252/255): nothing said →
  37. // `<project>/.sessions`; a path → that path; `false` → memory only. The three clocks
  38. // are seconds; null takes the layer's defaults (14 days valid, 15 min resident, sweep
  39. // every 5 min).
  40. // THE DEV WATCHER (the archive's `watch`): every save under the project arrives as an
  41. // event; a save that changes the analysis re-reads the graph, drops every cache and tells
  42. // every open tab to reload. Off by default — a deploy never re-analyses itself.
  43. Boolean minify = false // production: one-line HTML, compact JavaScript modules
  44. Boolean watchMode = true
  45. lastChange = 0 // epoch ms of the last save acted on (the debounce)
  46. String | Boolean sessionDir = null
  47. Number sessionMaxAge = null
  48. Number sessionIdle = null
  49. Number sweepInterval = null
  50. // THE SESSION COOKIE'S NAME (ticket #10). Cookies ignore the port, so two apps on one
  51. // host that both answered `hlsid` overwrote each other's sessions; an app names its own.
  52. // null: `hlsid`.
  53. String sessionCookie = null
  54. // THE COOKIE'S `Secure` FLAG (ticket #27): true when the app is reached over https —
  55. // behind a TLS proxy the server itself speaks plain http and cannot tell, so the app
  56. // says so. The browser then never sends the session over plain http. null (W124): `Secure` when THE REQUEST
  57. // came over https (X-Forwarded-Proto: https from the proxy); true: always; false: never.
  58. Boolean sessionSecure = null
  59. // THE MOST ANONYMOUS SESSIONS KEPT (W124): a visitor gets a session (and a file) only when something is stored
  60. // in it; the ones nobody logged in to are capped, the oldest evicted first.
  61. Number sessionAnonMax = 10000
  62. // THE COOKIE'S `Domain` (ticket #44): 'example.org' shares one session with every
  63. // <sub>.example.org, which a host-only cookie cannot. null: host-only, no attribute.
  64. String sessionDomain = null
  65. \* THE PORT: the app's own `--port=N` argument (hybriel hands every argument
  66. after the entry to the program, creator ruling 2026-09-27), else the
  67. constructor's, else HL_PORT (hybriel resolves PORT and `.env` into it),
  68. else 8080. *\
  69. Number port = null
  70. // THE OFFLINE ALLOW-LIST (COMPONENTS §10, D38): the pages this app promises with the
  71. // network down, named as the route table names them — the imported class or a path
  72. // string. null: no service worker, no cache, no IndexedDB, nothing on the device.
  73. offline = null
  74. // THE OFFLINE FALLBACK PAGE (ticket #120): a data-free page — a route component with no
  75. // parameters, the class or its path string — the service worker keeps once, fetched with
  76. // NO credentials, and shows for any page it has nothing for while the network is down.
  77. // null: the "Unavailable offline" page, as before. Needs `offline`.
  78. offlineFallback = null
  79. // THE APP'S OWN FILES KEPT OFFLINE (ticket #170): a list of urls — each a path the app's
  80. // `file` routes answer (`/md-editor.js`, or one file under a directory route) — the worker
  81. // precaches at install and serves cache-first. Only the urls listed: a directory route is
  82. // never kept as a tree. Needs `offline`. null: none beyond the files a kept page's View
  83. // loads through a literal `<script src>` or `<link href>`.
  84. offlineFiles = null
  85. // WEB PUSH (ticket #173): the app's VAPID PUBLIC key, base64url (the 65-byte uncompressed P-256
  86. // point). Setting it serves the service worker — which then shows a pushed notification and
  87. // focuses the app on a click — and lets a component call `subscribePush()` (hl:web). null: no push.
  88. pushKey = null
  89. // …and the SERVER'S half: the VAPID PRIVATE key (base64url, the 32-byte P-256 scalar of `pushKey`) and the
  90. // contact `pushSubject` ('mailto:…' or 'https://…', the push service may write to it). Both set: the app can
  91. // `import { sendPush } from 'hl:web/push'` and send. A key that is not the private half of `pushKey` is refused at boot.
  92. pushPrivateKey = null
  93. pushSubject = null
  94. // THE DEAD-SOCKET CLOCK (COMPONENTS §10), in seconds. The browser pings every `pingEvery`,
  95. // and a socket whose pong has not come back within `pongWithin` is taken for dead: it is
  96. // closed, and the reconnect and the queue's replay start. A network that drops without a
  97. // close frame is noticed within pingEvery + pongWithin (35 s by default). null: 25 and 10.
  98. // THE RENDER CACHE (W141, COMPONENTS §12): how many finished renders are kept in memory, least
  99. // recently used out first. A component opts in by declaring `cacheKey`. 0 switches the cache off;
  100. // null: 64.
  101. Number renderCacheMax = null
  102. Number pingEvery = null
  103. Number pongWithin = null
  104. // AN UPLOAD THAT GOES SILENT — no progress, no answer — is read as dropped after this
  105. // many seconds (COMPONENTS §10, an emit's file). null: 15.
  106. Number uploadStall = null
  107. // THE LARGEST FILE AN EMIT MAY CARRY (ticket #94), in bytes: a bigger one is refused
  108. // at its first request, and the emit ends with that error. 1 GiB.
  109. Number uploadMax = 67108864
  110. // THE UPLOAD BUDGETS (W115): the bytes announced by the unfinished uploads of ONE session,
  111. // and of ALL sessions together (a part is held in memory until its emit claims it). 256 MiB, 1 GiB.
  112. Number uploadSessionMax = 268435456
  113. Number uploadHeldMax = 1073741824
  114. // THE LARGEST BODY `POST /__hl/emit` takes, in bytes (W115): a bigger one is answered 413. 16 MiB.
  115. // (hl:http1 reads a request's body whole before hl:web sees it, so this refuses the answer, not the read.)
  116. Number emitMax = 16777216
  117. // ONE PART OF AN UPLOAD, at most (the client half sends 1 MiB): 8 MiB.
  118. Number uploadPartMax = 8388608
  119. // THE HEADERS EVERY ANSWER CARRIES (W115, COMPONENTS §7): the safe defaults are nosniff,
  120. // Referrer-Policy strict-origin-when-cross-origin, X-Frame-Options SAMEORIGIN and a CSP of
  121. // `frame-ancestors 'self'`. `pageHeaders = { 'Content-Security-Policy' = "…" }` adds to or replaces
  122. // them on every answer (a header set to null is removed); a route's own header wins over both.
  123. Hybrid pageHeaders = {}
  124. // ORIGINS BESIDES THE REQUEST'S OWN HOST that may call `/__hl/emit`, `/__hl/upload` and open the
  125. // socket (W115): `['https://app.example.org']`. A request whose Origin is another is refused 403.
  126. trustedOrigins = []
  127. // THE PUSH LOG (ticket #143). A push is addressed to the TAB, not to its socket: each tab
  128. // keeps the last `pushKept` pushes it was sent (and no more than `pushKeptBytes` of them),
  129. // numbered, and a tab whose socket comes back gets what it missed again, in order. A tab
  130. // whose socket left is kept `tabKept` seconds, and pushed to and logged meanwhile; a gap
  131. // longer than the log (or a server restart) resyncs the tab's server-derived state instead.
  132. // THE BYTES BOUND IS THE ONE THAT GOVERNS (ticket #160): a push is small (a streamed delta is some
  133. // 150 bytes), and a count of 500 ran out within a 15-second gap on a server streaming several
  134. // chats to the tab while 1 MiB was far off. The count is the guard for the degenerate case only.
  135. Number pushKept = 10000
  136. Number pushKeptBytes = 1048576
  137. Number tabKept = 600
  138. String host = null // the interface to bind; null → HL_HOST/HOST, the manifest's `host`, 0.0.0.0
  139. // THE ONE RUNTIME URL, and the reason it is a member and not a literal in two
  140. // places: a module's `import … from "./hl-runtime.js"` resolves against the
  141. // MODULE's own url, so a server answering modules at two directory depths hands
  142. // the browser two runtime urls — two ES-module instances, two `globalEvents`
  143. // buses, two `__hlRealm` variables, and a crossing emit announced on a bus the
  144. // edge module never taps. Every module this server compiles is handed this one
  145. // specifier (hlJs's third argument).
  146. // THE DIRECTORY THE FRAMEWORK ANSWERS FROM, and the reason it is its own member:
  147. // a package's browser half is served BESIDE THE RUNTIME, and the compiler derives
  148. // that url from the runtime's own (`js_module.zig browserHalfUrl`:
  149. // `<dirname(runtime)>/<pkg>/client.js`). Two sides deriving one url from one
  150. // directory is what keeps the module's `import` and this server's route table
  151. // from drifting apart.
  152. static halfDir = '/__hl'
  153. static runtimeUrl = halfDir + '/hl-runtime.js'
  154. clientUrl = halfUrl('web')
  155. styleUrl = halfDir + '/app.css'
  156. // THE BUILD'S VERSION IS IN EVERY URL THE BROWSER CACHES (after ticket #82): the
  157. // runtime, the package halves, the component modules and the stylesheet were served
  158. // at fixed urls, and a browser or Cloudflare kept the old client against a new
  159. // deploy's pages. Each is now asked for as `<url>?v=<hash>`, the hash of everything
  160. // this build serves, and answered with a year's `immutable` caching — a new build is
  161. // a new url. The modules are COMPILED against this mark and it is replaced with the
  162. // hash when they are served: the hash is of the compiled texts, so it cannot be in
  163. // them while they are compiled, and a binary's baked modules carry the mark too (the
  164. // one form both paths share). The route patterns stay the bare paths.
  165. static buildMark = '?v=__hlbuild__'
  166. static runtimeSpec = runtimeUrl + buildMark
  167. // the web app manifest and the service worker's entry script (COMPONENTS §10)
  168. static manifestUrl = halfDir + '/manifest.webmanifest'
  169. static workerUrl = halfDir + '/sw.js'
  170. // TEST-ONLY CONSTRUCTION COUNTER (mission 343, W133). Only with HL_WEB_COUNT=1: `construct` counts every server
  171. // construction by component file, and GET /__hl/constructs answers the counts. Without the flag nothing is
  172. // counted and the route does not exist.
  173. countConstructs = env('HL_WEB_COUNT') == '1'
  174. constructTotal = { n = 0 }
  175. constructByFile = {}
  176. // THE FRAMEWORK'S OWN URLS ARE ROUTES (creator: "just use routes"), appended to
  177. // the app's table with `routes[] = …` — the append that takes on a caller's
  178. // pinned argument during construction, where `routes = routes + […]` is dropped.
  179. // Three of them here — the runtime, the REST carrier and the app's one
  180. // stylesheet — and then one per PACKAGE BROWSER HALF the app's graph holds,
  181. // appended below where the graph is known. There is no catch-all that compiles
  182. // any graph file a url names.
  183. routes[] = { pattern = runtimeUrl framework = true function = (route, req) => {
  184. return new Response(runtime, { headers = cached(req, 'text/javascript; charset=utf-8') })
  185. } }
  186. // THE REST CARRIER, the same emit/ack pair for a peer that cannot hold a socket
  187. // (SPEC: `POST /__hl/emit`).
  188. // ITS SESSION IS THE COOKIE'S (creator, 2026-09-14): this is an HTTP request like
  189. // the page request, so it resolves the SAME session the page route would for that
  190. // cookie — a `session.user` a face writes here is what the next document reads.
  191. // Before this the face was handed null and a login over the fallback was lost.
  192. // AN OUTWARD EMIT RAISED UNDER IT RIDES BACK IN THE ANSWER: there is no
  193. // connection to push to, so the frames a face raised for the CALLER are
  194. // collected while it runs and shipped in the ack as `emits`, which the client
  195. // half delivers before it resolves the emit. The audience fan-out to the other
  196. // connections of that user is the same walk it always was.
  197. routes[] = { pattern = '/__hl/emit' framework = true function = (route, req) => {
  198. if (req.method != 'POST') { return notFound(req.path) }
  199. if (crossSite(req.headers)) { return refused(403, 'cross-site request refused') }
  200. if (req.body != null && req.body.length > emitMax) { return refused(413, 'the emit is longer than ' + emitMax + ' bytes (`emitMax`)') }
  201. // NO COOKIE, NO SESSION (W124): a face that stores something in the session it was handed makes one,
  202. // `inbound` leaves it in `postAdopted`, and the answer sets the cookie
  203. let s = sessions.resolve(req.headers['cookie'] != null ? req.headers['cookie'] : req.headers['Cookie'])
  204. let idBefore = s != null ? s.id : null
  205. // the session travels in a MEMBER, not an argument: a call argument is a copy,
  206. // an instance inside it included, and a copied session loses the face's write
  207. postSession = s
  208. postHost = hostOf(req.headers['host'])
  209. postHeaders = requestHeaders(req.headers)
  210. postReq = requestInfo(req.headers, req.remoteAddress, req.secure)
  211. postAdopted = null
  212. let res = new Response(inbound(null, JSON.parse(req.body)), { headers = { 'Content-Type' = 'application/json; charset=utf-8' } })
  213. // the session a face made (W124), or the one a face's `session.rotate()` moved to a new id (W120): this answer carries the cookie
  214. if (postAdopted != null) { res.headers['Set-Cookie'] = sessions.cookieHeader(postAdopted.id, isHttps(req.headers, req.secure)) } else if (s != null && s.id != idBefore) { res.headers['Set-Cookie'] = sessions.cookieHeader(s.id, isHttps(req.headers, req.secure)) }
  215. // W137: several cookies of the session's name: the answer re-issues the chosen one and expires the host-only stray
  216. let fx = sessions.repair(req.headers['cookie'] != null ? req.headers['cookie'] : req.headers['Cookie'], s, isHttps(req.headers, req.secure))
  217. for (k of fx.keys()) { if (res.headers[k] == null) { res.headers[k] = fx[k] } }
  218. postAdopted = null
  219. postReq = null
  220. return res
  221. } }
  222. // THE SOCKET CARRIER'S HALF OF `session.rotate()` (W120): a frame cannot set a cookie, so the server pushed the
  223. // tab `{ t: 'rotate', token }` and the client half POSTs it here. Origin-checked, authenticated twice — by the
  224. // token only that socket was given (one-shot) and by the cookie it still holds (the OLD id the rotation
  225. // recorded) — and the answer carries the Set-Cookie of the new id. A planted id has no token: nothing to claim.
  226. routes[] = { pattern = '/__hl/rotate' framework = true function = (route, req) => {
  227. if (req.method != 'POST') { return notFound(req.path) }
  228. if (crossSite(req.headers)) { return refused(403, 'cross-site request refused') }
  229. let sent = req.body != null && req.body != '' ? JSON.parse(req.body) : null
  230. let token = sent != null ? sent.token : null
  231. let rec = token != null ? pendingRotate['r' + token] : null
  232. let cks = sessions.cookieValues(req.headers['cookie'] != null ? req.headers['cookie'] : req.headers['Cookie'])
  233. if (rec == null || !cks.includes(rec.old) || now() - rec.at > 300000) { return refused(403, 'no rotation to claim') }
  234. pendingRotate['r' + token] = null
  235. let res = new Response('', { status = 204 headers = { 'Cache-Control' = 'no-store' } })
  236. res.headers['Set-Cookie'] = sessions.cookieHeader(rec.id, isHttps(req.headers, req.secure))
  237. return res
  238. } }
  239. // A FILE IN AN EMIT TRAVELS OVER HTTP (ticket #94, creator 2026-09-25): the client half
  240. // sends each file of an `emit server …` here, in parts, before the emit itself; the emit's
  241. // frame then names the upload, and `inbound` hands the face the file in its place.
  242. // POST /__hl/upload { name, type, size, q, n } → { id, have } (an upload; see uploadRequest)
  243. // POST /__hl/upload?id=&at= one part, raw → { have } (appended when `at` is what arrived so far)
  244. // GET /__hl/upload?id= → { have } (after a dropped connection)
  245. // An upload belongs to the session of the cookie that started it, and only an emit
  246. // of that session can claim it. A part cut short by a dropped connection keeps what
  247. // arrived; the client asks for `have` and goes on from there.
  248. routes[] = { pattern = '/__hl/upload' framework = true function = (route, req) => {
  249. if (crossSite(req.headers)) { return refused(403, 'cross-site request refused') }
  250. // W124: sessions are lazy (a page mints none), so the START of an upload is what makes one for a
  251. // visitor with no cookie; the answer sets it. A part or a question about `id` needs the session
  252. // that started it. The caps (uploadMax, uploadSessionMax, uploadHeldMax) still hold the memory.
  253. let s = sessions.resolve(req.headers['cookie'] != null ? req.headers['cookie'] : req.headers['Cookie'])
  254. if (s == null && req.query != null && req.query.id != null) { return uploadAnswer(404, { error = 'no upload ' + req.query.id + ' in this session' }) }
  255. let made = s == null
  256. if (made) {
  257. if (req.method != 'POST') { return notFound(req.path) }
  258. s = sessions.fresh()
  259. }
  260. postAdopted = null
  261. let out = uploadRequest(&s, req)
  262. // a visitor whose start was refused (too big, bad body) keeps no session: `uploadRequest` adopts it
  263. // only when the upload is accepted
  264. if (postAdopted != null) { out.headers['Set-Cookie'] = sessions.cookieHeader(postAdopted.id, isHttps(req.headers, req.secure)) }
  265. // W137: several cookies of the session's name: re-issue the chosen session's id, expire the host-only stray
  266. let fx = made ? sessions.strays(req.headers['cookie'] != null ? req.headers['cookie'] : req.headers['Cookie'], isHttps(req.headers, req.secure)) : sessions.repair(req.headers['cookie'] != null ? req.headers['cookie'] : req.headers['Cookie'], s, isHttps(req.headers, req.secure))
  267. for (k of fx.keys()) { if (out.headers[k] == null) { out.headers[k] = fx[k] } }
  268. postAdopted = null
  269. return out
  270. } }
  271. // A SESSION MADE OVER THE SOCKET GETS ITS COOKIE HERE (W124): a socket cannot set one, so the ack of the
  272. // face that made the session carries a one-time token and the page POSTs it here; the answer sets the cookie.
  273. routes[] = { pattern = '/__hl/adopt' framework = true function = (route, req) => {
  274. if (req.method != 'POST') { return notFound(req.path) }
  275. if (crossSite(req.headers)) { return refused(403, 'cross-site request refused') }
  276. let t = req.query != null ? req.query.t : null
  277. let a = t != null ? adoptTokens[t] : null
  278. if (a == null || now() - a.at > 60000) { return refused(404, 'no such token') }
  279. adoptTokens[t] = null
  280. let res = new Response('', { status = 204 headers = { 'Cache-Control' = 'no-store' 'Set-Cookie' = sessions.cookieHeader(a.sid, isHttps(req.headers, req.secure)) } })
  281. // W137: the new cookie must be the only one of its name: a host-only stray is expired
  282. let fx = sessions.strays(req.headers['cookie'] != null ? req.headers['cookie'] : req.headers['Cookie'], isHttps(req.headers, req.secure))
  283. for (k of fx.keys()) { res.headers[k] = fx[k] }
  284. return res
  285. } }
  286. if (countConstructs) {
  287. routes[] = { pattern = '/__hl/constructs' framework = true function = (route, req) => {
  288. return new Response(JSON.stringify({ total = constructTotal.n; byFile = constructByFile; }), { headers = { 'Content-Type' = 'application/json; charset=utf-8' 'Cache-Control' = 'no-store' } })
  289. } }
  290. }
  291. // THE SERVER IS UP (ticket #153): an empty answer the client half asks for while its socket
  292. // waits to reconnect, so a tab is back within about a second of a restarted server listening
  293. routes[] = { pattern = '/__hl/up' framework = true function = (route, req) => {
  294. return new Response('', { status = 204 headers = { 'Cache-Control' = 'no-store' } })
  295. } }
  296. // THE APP'S ONE STYLESHEET — the `styles` file's rules and every mounted
  297. // component's `Style { }`, walked in style.hl and cached after the first ask.
  298. routes[] = { pattern = styleUrl framework = true function = (route, req) => {
  299. return new Response(stylesheet(), { headers = cached(req, 'text/css; charset=utf-8') })
  300. } }
  301. // THE COMPONENT MODULES ARE ROUTES TOO — the framework's, not the app's: one per
  302. // file a page route mounts and per wrapper above it (the graph's `parent`
  303. // chain), served at the file's own `.hl` url as the browser's projection. A
  304. // browser executes a module by its MIME type, so `text/javascript` at
  305. // `/components/home.hl` is a module, and the url is the path the author wrote.
  306. // Nothing else is served as a module: a file no page route reaches has no url.
  307. // THE LANGUAGE GRAPH, AND THE REALMS ARE THIS PACKAGE'S (creator, 2026-09-12: "the project.hl
  308. // defines no realms so the framework just fills them itself"). This file is the server
  309. // realm's entrypoint, client.hl beside it the browser's; the app reaches both by
  310. // importing hl:web, and the graph follows that reference into the package.
  311. graph = hlProject(
  312. realms = {
  313. server = { entrypoint = './WebFramework.hl' }
  314. client = { entrypoint = './client.hl' }
  315. }
  316. transports = [
  317. ['websocket' 'client' 'server']
  318. ['websocket' 'server' 'client']
  319. ['rest' 'client' 'server']
  320. ]
  321. )
  322. gen = graph.analysisGen // the syntax reflection's handle: the routes below read Views
  323. // TWO WEB FRAMEWORKS IN ONE APP IS NOT AN APP (creator, 15 Sep: project.hl switched
  324. // to the other framework the repo had then while styles.hl still said 'hl:web/css').
  325. // Both packages load, both `on server page` faces answer the same navigation, and
  326. // the second answers on a blank instance — a NotCallable deep inside the other framework's dispatch, which
  327. // says nothing about the two import rows that caused it. So it is refused HERE,
  328. // before anything is served, naming both rows.
  329. oneFrameworkOnly()
  330. // A VALUE-FORM EMIT HAS ONE ANSWERER (SPEC "An emit ANSWERS", ticket #20): checked here,
  331. // before anything is served, because the wire does not say which form an emit was
  332. oneAnswererEach()
  333. // THE APP'S SETTINGS come from the file that constructed this one when they were not
  334. // passed (the archive's `configure()`): `styles`, `audience`, `sessionDir`, the clocks,
  335. // `watchMode`, `minify`, `port`
  336. cfg = hlConstructor()
  337. if (cfg != null) {
  338. if (styles == null && cfg.styles != null) { styles = cfg.styles }
  339. if (cfg.audience != null && audience.keys().length == 0) { audience = cfg.audience }
  340. if (sessionDir == null && cfg.sessionDir != null) { sessionDir = cfg.sessionDir }
  341. if (sessionMaxAge == null && cfg.sessionMaxAge != null) { sessionMaxAge = cfg.sessionMaxAge }
  342. if (sessionIdle == null && cfg.sessionIdle != null) { sessionIdle = cfg.sessionIdle }
  343. if (sweepInterval == null && cfg.sweepInterval != null) { sweepInterval = cfg.sweepInterval }
  344. if (sessionCookie == null && cfg.sessionCookie != null) { sessionCookie = cfg.sessionCookie }
  345. if (sessionSecure == null && cfg.sessionSecure != null) { sessionSecure = cfg.sessionSecure }
  346. if (cfg.sessionAnonMax != null) { sessionAnonMax = cfg.sessionAnonMax }
  347. if (sessionDomain == null && cfg.sessionDomain != null) { sessionDomain = cfg.sessionDomain }
  348. if (cfg.watchMode != null) { watchMode = cfg.watchMode }
  349. if (cfg.minify != null) { minify = cfg.minify }
  350. if (cfg.port != null) { port = cfg.port }
  351. if (offline == null && cfg.offline != null) { offline = cfg.offline }
  352. if (offlineFallback == null && cfg.offlineFallback != null) { offlineFallback = cfg.offlineFallback }
  353. if (offlineFiles == null && cfg.offlineFiles != null) { offlineFiles = cfg.offlineFiles }
  354. if (pushKey == null && cfg.pushKey != null) { pushKey = cfg.pushKey }
  355. if (pushPrivateKey == null && cfg.pushPrivateKey != null) { pushPrivateKey = cfg.pushPrivateKey }
  356. if (pushSubject == null && cfg.pushSubject != null) { pushSubject = cfg.pushSubject }
  357. if (pingEvery == null && cfg.pingEvery != null) { pingEvery = cfg.pingEvery }
  358. if (renderCacheMax == null && cfg.renderCacheMax != null) { renderCacheMax = cfg.renderCacheMax }
  359. if (pongWithin == null && cfg.pongWithin != null) { pongWithin = cfg.pongWithin }
  360. if (uploadStall == null && cfg.uploadStall != null) { uploadStall = cfg.uploadStall }
  361. if (cfg.uploadMax != null) { uploadMax = cfg.uploadMax }
  362. if (cfg.uploadSessionMax != null) { uploadSessionMax = cfg.uploadSessionMax }
  363. if (cfg.uploadHeldMax != null) { uploadHeldMax = cfg.uploadHeldMax }
  364. if (cfg.emitMax != null) { emitMax = cfg.emitMax }
  365. if (cfg.pageHeaders != null && pageHeaders.keys().length == 0) { pageHeaders = cfg.pageHeaders }
  366. if (cfg.trustedOrigins != null && trustedOrigins.length == 0) { trustedOrigins = cfg.trustedOrigins }
  367. if (cfg.pushKept != null) { pushKept = cfg.pushKept }
  368. if (cfg.pushKeptBytes != null) { pushKeptBytes = cfg.pushKeptBytes }
  369. if (cfg.tabKept != null) { tabKept = cfg.tabKept }
  370. }
  371. served = {}
  372. mounted = []
  373. for (r of routes) { if (r.component != null) { mounted[] = keyOf(r.component) } }
  374. for (k of mounted) {
  375. let key = k
  376. // a file the graph does not hold is refused at its route row, below (servedKeys
  377. // → routeComponentKey: this walk reads the evaluated table, which has no lines)
  378. if (graph.files[key] == null) { key = null }
  379. while (key != null) {
  380. serveComponent(key)
  381. let child = key
  382. key = graph.files[key].parent
  383. // A PARENT IS A COMPONENT (COMPONENTS §5): one without a View wraps nothing, and
  384. // every page under it answered a 500 while the boot said nothing (322 row 13)
  385. if (key != null && viewHandle(key) == 0) {
  386. hlError("hl:web: the `parent` clause of " + child + " names " + key + ", which declares no View: a parent is a component whose View places `slot` where the page renders")
  387. }
  388. }
  389. }
  390. // EVERY PACKAGE'S BROWSER HALF IS SERVED, BY ONE RULE. A package whose browser
  391. // side is written in this language ships it as `client.hl` beside its
  392. // plugin.json; the compiler compiles it like any other file and writes the
  393. // importing module `import { … } from "<halfDir>/<pkg>/client.js"`
  394. // (js_module.zig browserHalf / browserHalfUrl). Something has to answer that url,
  395. // and this is it — for EVERY such package the graph holds, because the rule
  396. // belongs to the language and not to one package. hl:web's own half is the first
  397. // case of it and no longer a hard-coded route of its own; hl:dnd is the second.
  398. //
  399. // The graph is the whole guard: a key is here only because the entry's closure
  400. // REACHED that package's half through an import, which is the same reason a
  401. // component has a module url. A package nothing imports is served nothing.
  402. for (gk of graph.files.keys()) {
  403. if (gk.startsWith('hl:') && gk.endsWith('/client.hl')) { serveHalf(gk) }
  404. }
  405. // ---- INSTALLABLE, AND OFFLINE (COMPONENTS §10, tickets #95–#97) ------------------
  406. // Two declarations in the app's manifest, and nothing written by hand in the app:
  407. // · `appIcons` (with `appTitle`, and optionally `appShortName`, `appThemeColor`,
  408. // `appBackgroundColor`, `appManifest`) makes the app INSTALLABLE — the web app
  409. // manifest below, linked from every page's head with its apple-touch-icon;
  410. // · `offline = [ … ]` makes the pages it names work OFFLINE — the service worker
  411. // (worker.hl) that keeps the shell and those pages, and in the client half the
  412. // IndexedDB copy of their state and the queue of the emits they make.
  413. // An app that declares neither is served nothing of either.
  414. offlineKeys = offlinePages()
  415. fallbackPattern = offlineFallbackPattern()
  416. dataFreeKeys = dataFreePages()
  417. queueEvents = offlineKeys != null ? queueable() : []
  418. if (installable()) {
  419. routes[] = { pattern = manifestUrl framework = true function = (route, req) => {
  420. return new Response(JSON.stringify(webManifest()), { headers = { 'Content-Type' = 'application/manifest+json; charset=utf-8' 'Cache-Control' = 'no-cache' } })
  421. } }
  422. }
  423. if (pushKey != null && hlTypeName(pushKey) != 'String') { refuseAtSetting('pushKey', 'hl:web: pushKey is the VAPID public key as a base64url string, and this one is a ' + hlTypeName(pushKey)) }
  424. if (pushPrivateKey != null || pushSubject != null) {
  425. if (pushKey == null || pushPrivateKey == null || pushSubject == null) { refuseAtSetting('pushPrivateKey', 'hl:web: sending a push needs pushKey, pushPrivateKey and pushSubject together') }
  426. if (hlTypeName(pushPrivateKey) != 'String' || hlTypeName(pushSubject) != 'String') { refuseAtSetting('pushPrivateKey', 'hl:web: pushPrivateKey is a base64url string and pushSubject a string (mailto:… or https://…)') }
  427. if (!pushSubject.startsWith('mailto:') && !pushSubject.startsWith('https://')) { refuseAtSetting('pushSubject', 'hl:web: pushSubject is a mailto: or https:// contact, and this one is ' + pushSubject) }
  428. let vapidPriv = base64urlDecode(pushPrivateKey)
  429. let vapidPub = vapidPriv != null && vapidPriv.length == 32 ? p256PublicKey(vapidPriv) : null
  430. if (vapidPub == null || base64urlEncode(vapidPub) != pushKey) { refuseAtSetting('pushPrivateKey', 'hl:web: pushPrivateKey is not the private half of pushKey (32 bytes, base64url)') }
  431. configurePush(pushKey, vapidPriv, pushSubject)
  432. }
  433. if (offlineKeys != null || pushKey != null) {
  434. // the ENTRY SCRIPT is served at the framework's directory, and its scope is the
  435. // whole app: `Service-Worker-Allowed` is what lets a script under /__hl/ say so
  436. routes[] = { pattern = workerUrl framework = true function = (route, req) => {
  437. return new Response(workerEntry(), { headers = { 'Content-Type' = 'text/javascript; charset=utf-8' 'Cache-Control' = 'no-cache' 'Service-Worker-Allowed' = '/' } })
  438. } }
  439. routes[] = { pattern = halfDir + '/web/worker.js' framework = true function = (route, req) => {
  440. return new Response(workerModule(), { headers = cached(req, 'text/javascript; charset=utf-8') })
  441. } }
  442. }
  443. // ---- WHAT THIS APP SERVES, OFF THE ANALYSIS ALONE (mission 315) ----------------
  444. // These four are STATIC, so they answer with no instance and without constructing
  445. // anything: the compiler evaluates `servedModulesOf(graph)` at BUILD time to bake
  446. // each module's text, and this file's own root uses the very same functions at
  447. // boot. One definition, two callers — a second derivation would drift, and a
  448. // compiled binary would then serve text generated against different urls.
  449. //
  450. // The seed is the entry's route table AS WRITTEN, read through `hlSyntax`, not
  451. // the evaluated `routes` member: evaluating it means constructing the app, and
  452. // constructing this class binds a socket. The graph carries the entry's record
  453. // since 2026-09-16, which is what makes that readable at all.
  454. // A ROUTE'S COMPONENT IS A PAGE: a file without a View answered every request with a 500
  455. // ("declares no View", raised without a span) while the boot said nothing (mission 322
  456. // row 13). Refused at the row instead.
  457. static routePage = (gen, entryKey, valueNode, key) => {
  458. if (!hasViewMember(gen, key)) { hlSourceError(gen, entryKey, valueNode, key + " declares no View, so it is no page: a route's component is a file whose View renders") }
  459. return key
  460. }
  461. // The key a route row's `component` names: an imported class, or a path string.
  462. // Anything else is a located refusal AT THE ROW — never silently unserved.
  463. static routeComponentKey = (&graph, gen, entryKey, imports, valueNode) => {
  464. let v = hlSyntax(gen, entryKey, valueNode)
  465. if (v == null) { return null }
  466. if (v.tag == 'literal' && v.kind == 'string') {
  467. let t = v.text
  468. let k = t.startsWith('./') ? t.slice(2) : t
  469. // A PATH NO FILE OF THE APP IMPORTS IS NOT IN THE GRAPH: the analysis never read
  470. // it, so nothing can be served for it — refused here, at the row, instead of a
  471. // null deep in the framework once the server is already up (STATUS §2 item 0)
  472. if (graph.files[k] == null) { hlSourceError(gen, entryKey, valueNode, "the app never imports " + t + ", so the analysis never read it and the app would serve no module for it: import it in this file (`import Page from '" + t + "'`) and write `component = Page`") }
  473. return routePage(gen, entryKey, valueNode, k)
  474. }
  475. if (v.tag == 'identifier') {
  476. for (imp of imports) {
  477. if (imp.default == v.name && imp.key != null) { return routePage(gen, entryKey, valueNode, imp.key) }
  478. }
  479. }
  480. hlSourceError(gen, entryKey, valueNode, "a route's component must be an imported component class or a path string — this one the analysis cannot resolve to a file, so the app would serve no module for it")
  481. return null
  482. }
  483. // does the file at `key` declare a View? (a component, as opposed to a plain class)
  484. static hasViewMember = (gen, key) => {
  485. for (m of hlMembers(gen, key)) {
  486. if (m.name == 'View') { return true }
  487. }
  488. return false
  489. }
  490. // `key` and every component it composes, once each — the same walk
  491. // `serveComponent` performs, as a function of the graph.
  492. static collectServed = (&graph, gen, &out, key) => {
  493. if (key == null || graph.files[key] == null) { return null }
  494. for (k of out) { if (k == key) { return null } }
  495. out[] = key
  496. for (imp of graph.files[key].imports) {
  497. if (imp.default != null && imp.key != null && hasViewMember(gen, imp.key)) {
  498. collectServed(graph, gen, out, imp.key)
  499. }
  500. }
  501. return null
  502. }
  503. // Every key this app answers a module for: each route's component and the wrapper
  504. // chain above it, the components those compose, and every package's browser half.
  505. static servedKeys = (&graph) => {
  506. let gen = graph.analysisGen
  507. let entryKey = graph.manifest.file
  508. let out = []
  509. if (entryKey != null && graph.files[entryKey] != null) {
  510. let imports = graph.files[entryKey].imports
  511. let routesNode = 0
  512. for (m of hlMembers(gen, entryKey)) {
  513. if (m.name == 'routes') { routesNode = m.node }
  514. }
  515. if (routesNode != 0) {
  516. let arr = hlSyntax(gen, entryKey, routesNode)
  517. if (arr != null && arr.tag == 'array_expression') {
  518. for (e of arr.elements) {
  519. let row = hlSyntax(gen, entryKey, e)
  520. if (row != null && row.tag == 'object_expression') {
  521. for (pe of row.entries) {
  522. let prop = hlSyntax(gen, entryKey, pe)
  523. if (prop != null && prop.tag == 'object_property' && prop.key == 'component') {
  524. let key = routeComponentKey(graph, gen, entryKey, imports, prop.value)
  525. // the wrapper chain above it, deepest last — a page is
  526. // served inside whatever wraps it
  527. let k = key
  528. while (k != null) {
  529. collectServed(graph, gen, out, k)
  530. k = graph.files[k] != null ? graph.files[k].parent : null
  531. }
  532. }
  533. }
  534. }
  535. }
  536. }
  537. }
  538. }
  539. return out
  540. }
  541. // EVERY PACKAGE'S BROWSER HALF, BY ONE RULE — a package whose browser side is
  542. // written in this language ships it as `client.hl`, the compiler writes
  543. // `<halfDir>/<pkg>/client.js` into every importing module, and something has to
  544. // answer that url. The graph is the whole guard: a key is here only because the
  545. // entry's closure reached that package.
  546. //
  547. // SEPARATE FROM `servedKeys` ON PURPOSE: a half gets a ROUTE but is not a module
  548. // url of this app, so it is not in the map `hlJs` is handed. That asymmetry is
  549. // the existing `serveHalf`/`serveComponent` split, stated rather than inherited
  550. // by accident — measured 2026-09-16, when folding the two together made the
  551. // analysis set one key wider than the route walk's.
  552. static packageHalfKeys = (&graph) => {
  553. let out = []
  554. for (gk of graph.files.keys()) {
  555. if (gk.startsWith('hl:') && gk.endsWith('/client.hl')) { out[] = gk }
  556. }
  557. return out
  558. }
  559. // The browser realm's NAME, off the graph — the declared realm whose entrypoint
  560. // is this framework's client half. Static, so the compiler can ask it too.
  561. static clientRealmOf = (&graph) => {
  562. for (name of graph.realms.keys()) {
  563. if (graph.realms[name].entrypoint == 'hl:web/client.hl') { return name }
  564. }
  565. return null
  566. }
  567. // EVERY MODULE THIS APP SERVES, COMPILED — what a native binary answers `hlJs`
  568. // with (mission 315). The emitter needs the runtime specifier, the browser
  569. // realm and the served-url map; all three are functions of the analysis, so the
  570. // whole map is, and the COMPILER can build it without an instance.
  571. //
  572. // `minify` is NOT: it is an app setting bound at construction, and the analysis
  573. // cannot evaluate a construction. The value used is recorded beside each
  574. // module so a binary asked for a different one refuses at the call instead of
  575. // answering text generated the other way.
  576. // HOW THE APP ASKED FOR ITS MODULES. A build bakes ONE form of every module and
  577. // a binary answering the other form would be different bytes, so the build must
  578. // read the app's own answer — and the app writes it where it configures the
  579. // framework: `new WebFramework(… minify = true …)` in the manifest. The analysis
  580. // carries a construction's named arguments, so this is a READ of the same syntax
  581. // `servedKeys` reads for the routes, not a second declaration.
  582. //
  583. // A COMPUTED `minify` IS NOT READ HERE, and nothing is guessed from it: a build
  584. // cannot evaluate an expression the running app has not reached yet. Such an app
  585. // bakes the unminified form, exactly as every app did before this, and if it
  586. // then asks for the other form at run time the binary says so at the request —
  587. // "this binary carries the module compiled the other way", located, which is
  588. // the refusal that already exists and the one measured on the creator's social
  589. // app (2026-09-17). Writing the literal in the manifest is what removes it.
  590. static manifestMinify = (&graph) => {
  591. let gen = graph.analysisGen
  592. let key = graph.manifest.file
  593. if (key == null || graph.files[key] == null) { return false }
  594. for (m of hlMembers(gen, key)) {
  595. let s = hlSyntax(gen, key, m.node)
  596. if (s != null && s.tag == 'new_expression' && s.named != null) {
  597. for (h of s.named) {
  598. let p = hlSyntax(gen, key, h)
  599. if (p != null && p.tag == 'object_property' && p.key == 'minify') {
  600. let v = hlSyntax(gen, key, p.value)
  601. if (v != null && v.tag == 'literal' && v.kind == 'boolean') { return v.text == 'true' }
  602. }
  603. }
  604. }
  605. }
  606. return false
  607. }
  608. static bakeModules = (graph) => {
  609. let realm = clientRealmOf(graph)
  610. let served = servedModulesOf(graph)
  611. let min = manifestMinify(graph)
  612. let out = {}
  613. for (k of servedKeys(graph)) {
  614. if (graph.files[k] != null) {
  615. let p = graph.files[k].path
  616. out[p] = {
  617. text = hlJs(p, min, runtimeSpec, realm, served)
  618. minify = min
  619. runtime = runtimeSpec
  620. realm = realm
  621. }
  622. }
  623. }
  624. // EVERY PACKAGE HALF TOO. The root walk above serves `<halfDir>/<pkg>/client.js`
  625. // for every `hl:<pkg>/client.hl` the graph holds, and a compiled binary answers
  626. // from BAKED text alone — so a bake that skipped them served the page and then
  627. // 404'd on the module the page imports, leaving the client half of the app
  628. // dead with nothing reported (measured on projects/framework, 2026-09-16).
  629. // Same rule, same list, one loop later: what the server routes, the build bakes.
  630. // AN OFFLINE APP'S SERVICE WORKER MODULE (COMPONENTS §10), under its own path
  631. if (manifestOffline(graph)) {
  632. let wp = workerPathOf(graph)
  633. out[wp] = {
  634. text = hlJs(wp, min, runtimeSpec, realm, served)
  635. minify = min
  636. runtime = runtimeSpec
  637. realm = realm
  638. }
  639. }
  640. for (gk of graph.files.keys()) {
  641. if (gk.startsWith('hl:') && gk.endsWith('/client.hl') && graph.files[gk] != null) {
  642. let hp = graph.files[gk].path
  643. if (out[hp] == null) {
  644. out[hp] = {
  645. text = hlJs(hp, min, runtimeSpec, realm, served)
  646. minify = min
  647. runtime = runtimeSpec
  648. realm = realm
  649. }
  650. }
  651. }
  652. }
  653. return out
  654. }
  655. // file path → the url this server answers its module at. What `hlJs` is handed,
  656. // and what the compiler bakes against.
  657. static servedModulesOf = (&graph) => {
  658. let out = {}
  659. for (k of servedKeys(graph)) {
  660. if (graph.files[k] != null) { out[graph.files[k].path] = '/' + k + buildMark }
  661. }
  662. return out
  663. }
  664. // ONE PACKAGE HALF'S ROUTE. It is a FUNCTION and not the body of the loop above
  665. // because the url's route closure must hold THIS key: a `let` in a loop body is
  666. // one binding the closures share, so every route built that way would serve the
  667. // last package's half (measured 2026-09-14 — both /__hl/web/client.js and
  668. // /__hl/dnd/client.js answered with hl:web's module). A parameter is a fresh
  669. // binding per call, which is the same reason serveComponent below is a function.
  670. serveHalf(key) {
  671. routes[] = { pattern = halfUrl(key.slice(3, key.length - 10)) framework = true function = (route, req) => { return serveHl('/' + key, req) } }
  672. return null
  673. }
  674. // a mounted file's module route, and the routes of the components it composes
  675. // (an import with a View), recursively — off the graph, once each
  676. serveComponent(key) {
  677. if (served[key] != null) { return null }
  678. served[key] = true
  679. routes[] = { pattern = modulePath(key) framework = true function = (route, req) => { return serveHl(req.path, req) } }
  680. for (imp of graph.files[key].imports) {
  681. if (imp.default != null && imp.key != null && viewHandle(imp.key) != 0) { serveComponent(imp.key) }
  682. }
  683. return null
  684. }
  685. // THE PROJECT DIRECTORY: this file lives in a package, so the app's directory is read
  686. // off a file that is the app's — the first route component's key against its path
  687. root = projectRoot()
  688. view = new HlwView
  689. css = new HlwCss(minify = minify, view = view)
  690. compiler = new HlwCompile
  691. sessions = new HlwSessions(dir = sessionDirPath(), maxAge = sessionMaxAge != null ? sessionMaxAge : 1209600, idle = sessionIdle != null ? sessionIdle : 900, sweepEvery = sweepInterval != null ? sweepInterval : 300, cookie = cookieName(), secure = sessionSecure, anonMax = sessionAnonMax, domain = sessionDomain != null ? sessionDomain : '')
  692. sessions.open()
  693. // THE STYLES FILE IS NAMED AT BOOT, not at the first request for the stylesheet: a value
  694. // that names no file, or a file the graph does not hold, is the app's mistake and the
  695. // app does not start with it (ticket #12)
  696. if (styles != null) {
  697. if (hlTypeName(styles) != 'String' && hlTypeName(styles) != 'Class') { refuseAtSetting('styles', "hl:web: styles is the styles file — the class the app imported (`styles = Styles`) or a path string ('./styles.hl') — and this one is a " + hlTypeName(styles)) }
  698. if (graph.files[keyOf(styles)] == null) { refuseAtSetting('styles', "hl:web: styles names " + keyOf(styles) + ", which is not in the project graph — import it from the app's entry (`import Styles from './styles.hl'`) and write `styles = Styles`") }
  699. }
  700. // the whole tree, nothing excluded: dot directories (the session store) are skipped by
  701. // the walker's own rule, and a custom store inside the tree is the app's choice to pay for
  702. if (watchMode) { __native("eventloop.register", watch(root), "hlFileChanged") }
  703. sheetText = null // the stylesheet, walked once at the first request for it
  704. // hl:web's OWN urls (/__hl/*, /components/*.hl) win over the app's routes whatever the
  705. // app's table ends in (ticket #129: a last `/:slug/:n` answered /__hl/app.css with HTML):
  706. // the framework's routes first, the app's after them in their own order
  707. let ownFirst = []
  708. for (r of routes) { if (r.framework == true) { ownFirst[] = r } }
  709. for (r of routes) { if (r.framework != true) { ownFirst[] = r } }
  710. let oi = 0
  711. for (r of ownFirst) {
  712. routes[oi] = r
  713. oi = oi + 1
  714. }
  715. router = new HlwRouter(routes = routes)
  716. trees = {} // key → the View tree, built once
  717. preloaded = {} // key → true: the closure of the Views it reaches is loaded (preload)
  718. declared = {} // key → { member name → true } of its non-static members (declares)
  719. reach = {} // key → the component keys its View reaches, in the order blueprintsIn walks them (blueprintOf)
  720. renderCache = {} // id → the finished mount of a component that declares `cacheKey` (renderCacheId); null once evicted
  721. renderOrder = [] // the ids, least recently used first
  722. renderNulls = 0 // evicted ids still standing as null in renderCache
  723. kidless = {} // key → 'yes' / 'no': does its View reference a component (holdsKids)
  724. fillsOf = {} // key → the named-region fills its View root writes (`side { … }`), lifted out of the tree
  725. slotAt = {} // key → where its View places its one `slot`
  726. styleNames = {} // key → the rule names of the file's Style, off the syntax
  727. styleRefs = {} // key → [{ tag rule }] the View wrote
  728. styleTags = {} // key → the element names this file's View renders
  729. styleIds = {} // key → the literal `id` values this file's View writes (R3)
  730. staticHolders = {} // key → an instance of a file whose statics another file imports
  731. modules = {} // key → the browser module (JavaScript text), compiled once at boot
  732. buildHash = null // the hash of everything this build serves, in every cached url (build())
  733. workerCompiled = null // the service worker's module as compiled (offline apps only, workerText())
  734. shipped = {} // key → the module as served: its build marks replaced with the hash
  735. servedUrls = null // file path → the url this server answers its module at, for hlJs
  736. runtime = hlJsRuntime() // the runtime library every module imports as "./hl-runtime.js"
  737. peers = {} // connection key → the WsClient, while it is open
  738. peerSession = {} // connection key → its session, from the tab's `hello` (null = anonymous)
  739. peerHost = {} // connection key → the host its upgrade request named (null = none sent)
  740. peerHeaders = {} // connection key → its upgrade request's headers (requestHeaders)
  741. peerMounts = {} // connection key → the component keys the tab has mounted
  742. peerParams = {} // connection key → the route params the tab's shell and page were mounted with
  743. // A TAB OUTLIVES ITS SOCKET (ticket #143): 't' + the tab's id → { id, n, log, bytes, conn,
  744. // session, mounts, params, host, headers, left }. `n` counts the pushes sent to it, `log`
  745. // keeps the last of them as sent ([{ n, text }], bounded by pushKept/pushKeptBytes),
  746. // `conn` is its open socket's key or null, `left` when that socket went (tabKept)
  747. tabs = {}
  748. peerTab = {} // connection key → the id of the tab its `hello` named
  749. // SESSIONS (web/sessions.hl): named by the cookie, at the page request and at the
  750. // socket's handshake alike. Nothing about a session ever reaches page script.
  751. sending = null // the WsClient whose inbound emit is being handled — the peer
  752. // an outward emit reaches, and null under the POST fallback
  753. // THE POST FALLBACK'S PEER IS ITS OWN ANSWER. While a face dispatched over
  754. // `POST /__hl/emit` runs, `posting` is true and every outward emit meant for the
  755. // CALLER is appended here instead of pushed; `inbound` ships the list in the ack.
  756. Boolean posting = false
  757. postEmits = []
  758. // …AND ITS TAB (#143): the tab a POST named (`tab` in its frame, of the same session) has
  759. // what is raised for it numbered and logged like a push, so the replay on its next socket
  760. // does not run it a second time
  761. postTab = null
  762. postSession = null // the cookie's session of the POST being dispatched
  763. pendingRotate = {} // 'r' + token → { old, id, at }: a socket-carrier rotation waiting for its browser's POST /__hl/rotate (W120)
  764. postAdopted = null // the session a POST's face (or an upload start) just made: its answer sets the cookie (W124)
  765. postReq = null // the request context of the POST being dispatched (requestInfo)
  766. faceReq = null // the request context of the carrier whose inbound emit is being dispatched
  767. peerReq = {} // connection key → its upgrade request's context (requestInfo)
  768. adoptTokens = {} // one-time token → { sid, at }: a socket cannot set a cookie, so the page asks for it (/__hl/adopt)
  769. postHost = null // the host of the POST being dispatched
  770. faceInst = null // the BLANK instance the running face writes on (step 2 of #201): read back as the tab's delta
  771. faceKey = null
  772. faceSent = {} // name -> JSON of what the delta already carried, so a later flush sends only the change
  773. faceHost = null // the host of the carrier whose inbound emit is being dispatched
  774. postHeaders = null // the headers of the POST being dispatched (requestHeaders)
  775. faceHeaders = null // the headers of the carrier whose inbound emit is being dispatched
  776. // EXACTLY ONCE (COMPONENTS §10): a queued emit carries a stable id `q`, and the ids handled
  777. // are kept per session, the last `handledKept` of them (Session.handled). A connection
  778. // with no session keeps its ids here, in one list under the same bound.
  779. Number handledKept = 200
  780. anonHandled = []
  781. // WHAT A KEPT ID WAS ANSWERED (ticket #107). An emit in flight when its socket closed
  782. // is sent again with its id, and its caller is still waiting — for a page, say. The
  783. // first delivery's ack went out on the dead socket, so the repeat is answered from
  784. // here: `answers[session id + ' ' + q]` is that ack as sent (its `i` replaced), or
  785. // `running` while the first delivery has not finished, which answers the repeat
  786. // `later` and the client asks again. In memory, the last `handledKept` of them: a
  787. // repeat comes seconds after the first try, and a restart loses nothing a live peer
  788. // still waits for but the ack, which is then plain `ok`, as before.
  789. answers = {}
  790. answerKeys = []
  791. uploads = {} // 'u' + upload id → { sid, name, type, size, have, parts, at, key }: a file on its way in (ticket #94)
  792. uploadKeys = {} // 'k' + session id + ' ' + q + ' ' + n → the upload id the n-th file of emit q went up under
  793. uploadParts = {} // 'u' + id + ':' + n → the n-th part as it arrived, a Bytes
  794. // ONE PORT, TWO CARRIERS. hl:http1's WebSocket engine answers the Upgrade
  795. // inline on the port this server already bound, so `websocket` and `rest` are
  796. // the same listener — which is why the manifest can declare both for the same
  797. // direction and this file needs no second server.
  798. // EVERY VIEW IS BUILT AT BOOT, not at the first request for its route: a View that
  799. // reads a name its file declares nowhere (checkRead) is the app's mistake, and the
  800. // app does not start with it — the port is bound on the line below this pass.
  801. // THE TWO DERIVATIONS MUST AGREE (mission 315). `served` is built above from the
  802. // EVALUATED route table; `servedKeys(graph)` derives the same set from the
  803. // analysis alone, and the compiler bakes each module's text against the second.
  804. // If they ever disagree the binary would serve modules generated against urls
  805. // this server does not answer, so the disagreement is a refusal, here, at boot.
  806. analysedKeys = servedKeys(graph)
  807. for (k of analysedKeys) {
  808. if (served[k] == null) {
  809. hlError('hl:web: the analysis says this app serves ' + k + ', the route walk did not — the two derivations of the served set disagree')
  810. }
  811. }
  812. for (k of served.keys()) {
  813. let seen = false
  814. for (a of analysedKeys) { if (a == k) { seen = true } }
  815. if (seen == false) {
  816. let why = ''
  817. for (imp of graph.files[k] != null ? [] : []) { why = why }
  818. hlError('hl:web: the route walk serves ' + k + ', the analysis did not — the two derivations of the served set disagree')
  819. }
  820. }
  821. for (k of served.keys()) { if (viewHandle(k) != 0) { tree(k) } }
  822. // the compiler reads a kid mount's View through this (a mount no longer carries a copy of it)
  823. compiler.treeOf = (key) => { return tree(key) }
  824. // A COMPONENT-REFERENCE CYCLE IS REFUSED HERE (COMPONENTS §12): a View that renders
  825. // itself, directly or through another, is a mount that never ends — it overflowed the
  826. // stack at the first request and the server died of a segfault with nothing said
  827. // (mission 322 row 1).
  828. acyclic = {}
  829. for (k of served.keys()) { if (viewHandle(k) != 0) { referenceCycle(k, [], []) } }
  830. // …and a page a shell wraps is placed at the shell's slot, inside its body: a page whose
  831. // root is `body` there emitted a second, nested <body> (mission 322 row 5)
  832. for (k of mounted) {
  833. if (graph.files[k] != null && graph.files[k].parent != null && viewHandle(k) != 0 && bodyRooted(k)) {
  834. hlError("hl:web: " + k + " is wrapped by " + graph.files[k].parent + " (its `parent` clause), but its View's root is `body { … }`, the page's body: the shell owns the body, so write the page's root as an element (`main { … }`, `section { … }`)")
  835. }
  836. }
  837. // THE SHEET IS WALKED AT BOOT, so the rules it drops are listed at boot (COMPONENTS §4,
  838. // css.hl's own header): walked at the first request for it, a dead rule was listed only
  839. // once some browser had asked, and a boot log said nothing (mission 322 row 11)
  840. stylesheet()
  841. // EVERY SERVED MODULE IS COMPILED AT BOOT: a free name in a View handler is a located
  842. // compile error (COMPONENTS §6b), and compiled at the first request for the module it
  843. // was a 500 behind a page that had already answered 200 (mission 322 row 14)
  844. for (k of served.keys()) { module(k) }
  845. // THE INTERFACE IS THE OPERATOR'S (ticket #24), on the ladder graph.zig's OperatorBind
  846. // states: the constructor's `host` > HL_HOST (the binary fills it from HOST) > the
  847. // manifest's > 0.0.0.0. Binding the default regardless put an app meant to sit behind
  848. // a proxy on every interface of the machine.
  849. if (host == null) { host = env('HL_HOST') }
  850. if (host == null && cfg != null && cfg.host != null) { host = cfg.host }
  851. if (host == null) { host = '0.0.0.0' }
  852. // A --PORT AFTER THE ENTRY OUTRANKS THE APP'S OWN PORT (creator ruling
  853. // 2026-09-27), but `port` ITSELF CANNOT SAY SO: the reference app passes an
  854. // explicit `port = …` to `new WebFramework(…)` (server.hl, computed from
  855. // HL_FW_PORT so a test run can sit beside a developer's own instance), which
  856. // PINS the member for the whole construction (SPEC.md "The file root is the
  857. // constructor" — "a root assignment to [a pinned] property… is a no-op").
  858. // `port = port_arg` below was exactly that no-op: `hybriel server.hl
  859. // --port=11499` still bound 44333, server.hl's own default, because this
  860. // line's write never landed. `boundPort`, a plain local nothing ever pins,
  861. // carries the actual ladder instead — CLI argument, else the (possibly
  862. // pinned) member, else HL_PORT, else 8080 — and IS what binds and what the
  863. // boot line names.
  864. checkRenderCaches()
  865. let port_arg = portArgument()
  866. let boundPort = port_arg
  867. if (boundPort == null) { boundPort = port }
  868. if (boundPort == null && env('HL_PORT') != null) { boundPort = toNumber(env('HL_PORT')) }
  869. if (boundPort == null) { boundPort = 8080 }
  870. http = new NativeWebSocketServer(port = boundPort, host = host)
  871. echo 'framework listening on ' + boundPort
  872. module('web/client.hl')
  873. // ---- the browser's modules: compiled IN PROCESS, served from memory --------------
  874. // The JavaScript target is this binary's own function (hlJs), the same one `--js`
  875. // runs from the command line. No child process, no build directory.
  876. //
  877. // THE CLIENT is compiled at boot — every page needs it, and it carries the View
  878. // and the Router with it (one module, three classes). A COMPONENT is compiled ON
  879. // DEMAND, at the request for its own `.hl` url, and kept: a route nobody visits
  880. // costs nothing, and the browser asks for a component's module the first time it
  881. // mounts one.
  882. //
  883. // THE TABLE THE EMITTER WRITES IS DROPPED. `hlJs` puts each file's members,
  884. // handlers and methods — every node of every initializer, with the names it reads —
  885. // into the module, because the old hl:web's browser half reduces that table on every boot.
  886. // This framework asked the same questions at COMPILE time and wrote the answers into
  887. // the component's own statements, so the table is dead weight in the page: 58 KB of
  888. // syntax on the reference app's home page alone. What the framework SERVES is its own
  889. // text, so it leaves that statement out; the language is not asked to change, and
  890. // The old hl:web kept its table untouched.
  891. // THE TABLE STATEMENT'S NAME in this module: `hlTablesDef`, or in a compact module the
  892. // alias its import clause gives it (`hlTablesDef as _51`). Each statement stands at the
  893. // start of its own line, which is how it is found — an alias alone is a suffix of other
  894. // names (`$_51(` is a compiler temporary).
  895. tablesCall(text) {
  896. let alias = text.indexOf('hlTablesDef as ')
  897. if (alias < 0) { return newline + 'hlTablesDef(' }
  898. let first = alias + 15
  899. let stop = first
  900. while (stop < text.length && text[stop] != ',' && text[stop] != '}') { stop = stop + 1 }
  901. return newline + text.slice(first, stop) + '('
  902. }
  903. // the `fns` of the file's own table — the first table statement the module carries is
  904. // the file's; the ones after it are the classes it bundles
  905. tableFns(text) {
  906. let at = text.indexOf(tablesCall(text))
  907. if (at < 0) { return [] }
  908. let open = text.indexOf('{', at)
  909. let end = text.indexOf(');', at)
  910. if (open < 0 || end < 0) { return [] }
  911. let t = JSON.parse(text.slice(open, end))
  912. return t.fns == null ? [] : t.fns
  913. }
  914. withoutTables(text) {
  915. // one per FILE the module carries — the client half bundles three classes. A compact
  916. // module calls it by its alias, and was served with every table until ticket #98's
  917. // follow-up: 50 KB and more of syntax on a minified app's page
  918. let call = tablesCall(text)
  919. let out = text
  920. let at = out.indexOf(call)
  921. while (at >= 0) {
  922. let end = out.indexOf(');', at)
  923. if (end < 0) { return out }
  924. // the newline before it stays: it ends the statement above
  925. out = out.slice(0, at + 1) + out.slice(end + 2)
  926. at = out.indexOf(call)
  927. }
  928. return out
  929. }
  930. // THE APP RUNS ON ONE WEB FRAMEWORK. Which packages are frameworks is READ OFF THE
  931. // GRAPH and not off a list this file keeps: a package the app's entry reached that
  932. // holds a `WebFramework.hl` is one. hl:dnd, hl:http1 and every other package an app
  933. // imports hold none and are untouched by this.
  934. //
  935. // The refusal names the ROW of each import, because the mistake IS an import line —
  936. // a sub-file import (`'hl:web/css'`) counts as much as the package itself, which is
  937. // exactly the case that made it: a lone braced import of a stylesheet helper puts the
  938. // whole package into the graph, and with it a second navigation face.
  939. oneFrameworkOnly() {
  940. let frameworks = {}
  941. for (gk of graph.files.keys()) {
  942. if (gk.startsWith('hl:') && gk.endsWith('/WebFramework.hl')) { frameworks[gk.slice(0, gk.length - 16)] = true }
  943. }
  944. if (frameworks.keys().length < 2) { return null }
  945. // the first row of the app's OWN files that reached each package
  946. let sites = {}
  947. for (k of graph.files.keys()) {
  948. if (!k.startsWith('hl:')) {
  949. for (imp of graph.files[k].imports) {
  950. for (pkg of frameworks.keys()) {
  951. if (sites[pkg] == null && (imp.source == pkg || imp.source.startsWith(pkg + '/'))) {
  952. sites[pkg] = { key = k; node = imp.node; where = k + ':' + imp.line + ':' + imp.col + " imports '" + imp.source + "'" }
  953. }
  954. }
  955. }
  956. }
  957. }
  958. let said = ''
  959. for (pkg of frameworks.keys()) {
  960. if (said != '') { said = said + ', and ' }
  961. if (sites[pkg] == null) { said = said + "'" + pkg + "' (reached through a package, not from a file of the app)" }
  962. else { said = said + sites[pkg].where }
  963. }
  964. let msg = 'this app imports TWO web frameworks: ' + said + '. Both packages load, both answer a page navigation, and the second one answers on a blank instance. An app runs on ONE of them — switch EVERY hl: import in EVERY file of the app to the same package, a sub-file import like \'/css\' included. Switching one line is not switching the app.'
  965. // THE CARET GOES ON ONE OF THE ROWS, and the sentence names them all: two
  966. // import lines are equally the mistake, and a diagnostic can only underline one.
  967. for (pkg of frameworks.keys()) {
  968. if (sites[pkg] != null) { hlSourceError(gen, sites[pkg].key, sites[pkg].node, msg) }
  969. }
  970. hlError(msg)
  971. return null
  972. }
  973. // ONE ANSWERER PER VALUE-FORM EMIT. SPEC: "if more than one class in the destination
  974. // realm declares a non-tap handler for the event, the VALUE form is refused at the emit
  975. // site naming both. As a statement it stays a broadcast and every handler still fires."
  976. // The statement form is what `inbound` does — every face runs. The value form cannot be
  977. // told apart on the wire, so every `x = emit server ev()` the app's files hold is read
  978. // off the analysis here, and one whose event two files answer is refused at its site,
  979. // naming both, before anything is served. Until ticket #20 both faces ran and the first
  980. // answer was taken in silence.
  981. oneAnswererEach() {
  982. let realm = serverRealm()
  983. for (k of graph.files.keys()) {
  984. if (!k.startsWith('hl:')) {
  985. for (e of hlEvents(gen, k).emits) {
  986. if (e.value == true && e.realm == realm) {
  987. let owners = facesOf(e.event)
  988. if (owners.length > 1) {
  989. let named = ''
  990. for (o of owners) { named = named == '' ? o : named + ' and ' + o }
  991. let msg = "hl:web: " + k + ':' + e.line + ':' + e.col + " — this emit waits for the answer of '" + e.event + "', and " + owners.length + " files answer it in the '" + realm + "' realm: " + named + ". A value-form emit has ONE answerer — rename the event in one of them, or emit it as a statement (a broadcast every handler receives)"
  992. hlSourceError(gen, k, e.node, msg)
  993. hlError(msg)
  994. }
  995. }
  996. }
  997. }
  998. }
  999. return null
  1000. }
  1001. // WHAT THIS SERVER SERVES AS A MODULE OF ITS OWN, by the file's path (mission 314
  1002. // rule 0). Handed to `hlJs`, it is what turns `import PostCard from './post_card.hl'`
  1003. // into an ES import of `/components/post_card.hl` instead of PostCard's whole class
  1004. // text copied into the importing module — EditHistory's class shipped three times on
  1005. // the social demo's home page before this. The urls are THIS file's (`moduleUrl`);
  1006. // the compiler invents none, and a file this server does not answer for is inlined
  1007. // exactly as it always was.
  1008. servedModules() {
  1009. if (servedUrls == null) {
  1010. let out = {}
  1011. for (k of served.keys()) { out[pathOf(k)] = modulePath(k) + buildMark }
  1012. servedUrls = out
  1013. }
  1014. return servedUrls
  1015. }
  1016. // A key the graph holds no file for is answered `null`, and the caller makes
  1017. // that a 404: a file the entry's closure never referenced is not part of this
  1018. // app, which is what keeps this from being a read of any path a url asks for.
  1019. module(key) {
  1020. if (modules[key] == null) {
  1021. let f = graph.files[key]
  1022. if (f == null) { return null }
  1023. // THE BROWSER GETS THE BROWSER'S PROJECTION, and nothing else. hlJs's
  1024. // fourth argument is the realm the module is produced for: a handler
  1025. // written `on server …` is not emitted at all, and a member whose
  1026. // initializer reaches a name the browser does not have is declared
  1027. // without one, for this server to lay over the instance with the state
  1028. // it already ships. The realm NAME comes off the manifest (clientRealm()
  1029. // above), never a literal — a project names its own realms.
  1030. let text = hlJs(f.path, minify, runtimeSpec, clientRealm(), servedModules())
  1031. // AND THE COMPILE STEP'S OWN OUTPUT BESIDE IT (mission 313): a component with a
  1032. // View carries, after its class, the paint statements this framework compiled
  1033. // from that View — one per bound spot, with its read written in (compile.hl).
  1034. // The browser calls them instead of walking the tree at paint time. Text
  1035. // produced here and served from memory like the module itself; nothing is
  1036. // written to disk and no JavaScript file lives under plugins/.
  1037. // THE FUNCTION VALUES' SITES are the one part of that table the browser still
  1038. // needs (tickets #98, #99): the compile step turns them into write sets
  1039. let fns = tableFns(text)
  1040. text = withoutTables(text)
  1041. if (viewHandle(key) != 0) { text = text + newline + compiler.module(gen, key, tree(key), fns, fillsOf[key]) }
  1042. modules[key] = text
  1043. }
  1044. return modules[key]
  1045. }
  1046. // the file the graph knows under this key — the graph carries every file's own path
  1047. pathOf(key) {
  1048. let f = graph.files[key]
  1049. if (f == null) { hlError('the graph holds no file ' + key + ' — nothing referenced it from the entry') }
  1050. return f.path
  1051. }
  1052. // THE BROWSER'S REALM, off the manifest: the realm whose declared entrypoint is
  1053. // this framework's client half. The framework's own two files ARE the two
  1054. // realms' entrypoints, so this is a lookup and never a guess.
  1055. clientRealm() {
  1056. for (name of graph.realms.keys()) {
  1057. if (graph.realms[name].entrypoint == 'hl:web/client.hl') { return name }
  1058. }
  1059. hlError('the manifest declares no realm whose entrypoint is ./client.hl — the browser half of this framework IS a realm, and a page cannot say which realm it is running in until the manifest names it')
  1060. }
  1061. // THIS realm, off the graph: the declared realm whose entrypoint REACHES this
  1062. // file (the app's entry imports it). A face names it, and so does the refusal
  1063. // when nothing answers.
  1064. serverRealm() {
  1065. let mine = graph.files['hl:web/WebFramework.hl'].realms
  1066. if (mine.length == 1) { return mine[0] }
  1067. hlError('the manifest declares no realm whose entrypoint reaches hl:web/WebFramework.hl — this file cannot dispatch a face without knowing which realm it is')
  1068. }
  1069. // the app's directory: a route component is the app's file, its key project-relative
  1070. projectRoot() {
  1071. for (r of routes) {
  1072. if (r.component != null) { return rootOf(keyOf(r.component)) }
  1073. }
  1074. // AN APP OF FUNCTION ROUTES ONLY (ticket #19) has no component to read it off, and
  1075. // needs no other: the manifest is the app's file too, and the graph knows its key
  1076. if (graph.manifest.file != null && graph.files[graph.manifest.file] != null) { return rootOf(graph.manifest.file) }
  1077. hlError('hl:web: the route table names no component and the graph names no manifest file, so the app\'s directory cannot be read off either')
  1078. }
  1079. // a project-relative key against its absolute path: what is left is the project's directory
  1080. rootOf(key) {
  1081. let path = pathOf(key)
  1082. // A COMPILED BINARY'S PATH IS ITS KEY (mission 318): it carries no
  1083. // build directory, so the file's path and its key are the same
  1084. // string and the root is the process's own directory. The
  1085. // interpreter's path is the script's absolute one, and the key is
  1086. // its tail — the root is what stands before it.
  1087. if (path == key) { return '.' }
  1088. return path.slice(0, path.length - key.length - 1)
  1089. }
  1090. // THE KEY OF A FILE THE APP NAMED — as the class it imported (`component = SortList`,
  1091. // `styles = Styles`: the import is the guarantee the graph reached it) or as a path
  1092. // ('./components/home.hl'). A class knows its file (`file(cls)`), and the graph knows
  1093. // the file's key.
  1094. keyOf(named) {
  1095. if (hlTypeName(named) == 'Class') {
  1096. let path = file(named)
  1097. for (k of graph.files.keys()) {
  1098. if (graph.files[k].path == path) { return k }
  1099. }
  1100. hlError('hl:web: the class at ' + path + ' is not in the project graph — import it from the app\'s entry')
  1101. }
  1102. // ANYTHING ELSE NAMES NO FILE (ticket #12): `styles = {}` booted and every request
  1103. // for the stylesheet was then a NotCallable on this line, with no line of the app's
  1104. if (hlTypeName(named) != 'String') { hlError("hl:web: a file the app names — a route's component, or `styles` — is the class it imported or a path string ('./styles.hl'), and this one is a " + hlTypeName(named)) }
  1105. if (named.startsWith('./')) { return named.slice(2) }
  1106. return named
  1107. }
  1108. // ---- the View tree: the member's syntax, reflected into plain hybrids ----------
  1109. viewHandle(key) {
  1110. for (m of hlMembers(gen, key)) {
  1111. if (m.name == 'View') { return m.node }
  1112. }
  1113. return 0
  1114. }
  1115. tree(key) {
  1116. treeLoad(key)
  1117. return trees[key]
  1118. }
  1119. // THE TREE IS BUILT ONCE PER KEY and read in place afterwards (`&trees[key]`): `tree(key)` hands out a COPY of the whole
  1120. // View tree on each call, and a mount, a render and a seed each asked for one (W116)
  1121. treeLoad(key) {
  1122. if (trees[key] != null) { return null }
  1123. let handle = viewHandle(key)
  1124. if (handle == 0) { hlError('component ' + key + ' declares no View') }
  1125. let v = hlSyntax(gen, key, handle)
  1126. let nodes = []
  1127. let fills = []
  1128. for (h of v.entries) {
  1129. let n = node(key, h, [], false, [])
  1130. // A NAMED REGION'S FILL (D-CHAIN addendum): `side { … }` at this View's root, where a level
  1131. // above declares `slot { name = 'side' … }`, is the content of THAT region and not of this
  1132. // page's own column: the region renders it, in this page's frame (compile.hl skips it here)
  1133. if (n != null && n.k == 'if' && n.regionfill != null) { fills.push({ name = n.regionfill; site = n.site; children = n.then; cond = null; }) }
  1134. // A CONDITIONAL FILL: `if (x) { side { … } }` at the View root fills while x holds (the default
  1135. // stands otherwise); the `if` itself stays in the page's tree (its branch holds the fill's
  1136. // components for the mounts, and the browser's `if` site is what hears x change)
  1137. else if (n != null && n.k == 'if' && n.region == null) {
  1138. for (c of n.then) {
  1139. if (c.k == 'if' && c.regionfill != null) { fills.push({ name = c.regionfill; site = c.site; children = c.then; cond = n.cond; }) }
  1140. }
  1141. }
  1142. if (n != null) { nodes.push(n) }
  1143. }
  1144. for (n of nodes) {
  1145. if (n.k == 'if' && n.regionfill == null && n.region == null) {
  1146. strayFill(key, n.then, true)
  1147. strayFill(key, n.other, false)
  1148. } else if (n.regionfill == null) { strayFill(key, [n], false) }
  1149. }
  1150. fillsOf[key] = fills
  1151. trees[key] = nodes
  1152. return null
  1153. }
  1154. // a fill standing anywhere but a View's root (or the root-level `if` that makes it conditional) is
  1155. // refused where it stands, rather than left to render nothing
  1156. strayFill(key, nodes, direct) {
  1157. for (n of nodes) {
  1158. if (n.k == 'if' && n.regionfill != null) {
  1159. if (!direct) { hlError('hl:web: ' + n.site + " — a region's fill (`" + n.regionfill + " { … }`) stands at a View's root or directly inside a root-level `if`; this one stands deeper (inside a nested `if`, an `else` or an element)") }
  1160. }
  1161. else if (n.k == 'if') { strayFill(key, n.then, false) strayFill(key, n.other, false) }
  1162. else if (n.k == 'el') { strayFill(key, n.children, false) }
  1163. else if (n.k == 'for') { strayFill(key, n.body, false) }
  1164. else if (n.k == 'component' && n.fill != null) { strayFill(key, n.fill, false) }
  1165. }
  1166. return null
  1167. }
  1168. // whether a node list holds a component anywhere (a region default that does is mounted late)
  1169. holdsComponent(nodes) {
  1170. for (n of nodes) {
  1171. if (n.k == 'component') { return true }
  1172. if (n.k == 'el' && holdsComponent(n.children)) { return true }
  1173. if (n.k == 'if' && (holdsComponent(n.then) || holdsComponent(n.other))) { return true }
  1174. if (n.k == 'for' && holdsComponent(n.body)) { return true }
  1175. }
  1176. return false
  1177. }
  1178. // the named regions the levels ABOVE this file declare (`slot { name = 'side' … }`)
  1179. regionsAbove(key) {
  1180. let out = []
  1181. let w = hlFile(gen, key).wrapper
  1182. let guard = 0
  1183. while (w != null && guard < 64) {
  1184. regionNamesIn(&out, tree(w))
  1185. w = hlFile(gen, w).wrapper
  1186. guard = guard + 1
  1187. }
  1188. return out
  1189. }
  1190. regionNamesIn(&out, nodes) {
  1191. for (n of nodes) {
  1192. if (n.k == 'if') {
  1193. if (n.region != null) { out.push(n.region) }
  1194. regionNamesIn(&out, n.then)
  1195. regionNamesIn(&out, n.other)
  1196. }
  1197. else if (n.k == 'el') { regionNamesIn(&out, n.children) }
  1198. else if (n.k == 'for') { regionNamesIn(&out, n.body) }
  1199. else if (n.k == 'component' && n.fill != null) { regionNamesIn(&out, n.fill) }
  1200. }
  1201. return null
  1202. }
  1203. // one entry of a hybrid literal → a tree node (null for an attribute: the
  1204. // element that owns it reads it)
  1205. node(key, handle, path, inFor, rows) {
  1206. let n = hlSyntax(gen, key, handle)
  1207. if (n == null) { return null }
  1208. if (n.tag == 'object_property') {
  1209. let v = hlSyntax(gen, key, n.value)
  1210. if (v.tag == 'object_expression') {
  1211. // A NAMED REGION: `slot { name = 'side' <default> }` is a region a lower level may fill
  1212. // (an `if` that always stands, carrying its name: the walkers already know the shape);
  1213. // `side { … }` at a View's root where a level above declares it is that region's fill
  1214. if (n.key == 'slot') {
  1215. let rname = regionName(key, v)
  1216. if (rname != null) {
  1217. let el = element(key, 'slot', v, path, inFor, rows)
  1218. let kids = []
  1219. for (c of el.children) { kids.push(c) }
  1220. return { k = 'if'; region = rname; deferred = holdsComponent(kids); cond = { k = 'text'; text = 'true'; kind = 'boolean'; }; then = kids; other = []; site = el.site; }
  1221. }
  1222. }
  1223. if (inFor && path.length == 0 && componentKeyOf(key, n.key) == null && regionsAbove(key).includes(n.key)) {
  1224. hlError('hl:web: ' + baseName(pathOf(key)) + ':' + n.line + ':' + n.col + " — a region's fill (`" + n.key + " { … }`) cannot stand inside a `for`: a fill stands at a View's root, or directly inside a root-level `if`")
  1225. }
  1226. if (path.length == 0 && !inFor && componentKeyOf(key, n.key) == null && regionsAbove(key).includes(n.key)) {
  1227. let el = element(key, n.key, v, path, inFor, rows)
  1228. // (an `if` that never renders in this column, so every walk of the tree that finds the
  1229. // components standing in it — mounts, seed, browser — sees them as it does an `if`'s)
  1230. return { k = 'if'; regionfill = n.key; cond = { k = 'text'; text = 'true'; kind = 'boolean'; }; then = el.children; other = []; site = el.site; }
  1231. }
  1232. let childKey = componentKeyOf(key, n.key)
  1233. if (childKey != null) { return component(key, n.key, childKey, v, v, path, inFor, rows) }
  1234. return element(key, n.key, v, path, inFor, rows)
  1235. }
  1236. return null
  1237. }
  1238. if (n.tag == 'literal') { return { k = 'text'; text = n.text; kind = n.kind; } }
  1239. if (n.tag == 'identifier') {
  1240. // A BARE CAPITALISED REFERENCE IS A COMPOSITION WITH AN EMPTY FILL (§12:
  1241. // "`Name { }` is the same reference as bare `Name`"). It is not a read, so it
  1242. // is answered before the read rules below refuse the name.
  1243. let bareKey = componentKeyOf(key, n.name)
  1244. if (bareKey != null) { return component(key, n.name, bareKey, null, n, path, inFor, rows) }
  1245. if (n.name == 'slot') { oneSlot(key, n) }
  1246. // AN IMPORTED STATIC IN A VIEW IS FOLDED (the archive did the same at build):
  1247. // `h1 { siteTitle }` with `import { siteTitle } from '../store.hl'` is not a
  1248. // member of this class, it is a constant of another file — read off that
  1249. // file's class once, here, and written into the tree as text
  1250. return nameRead(key, n.name, rows, n)
  1251. }
  1252. if (n.tag == 'view_for') {
  1253. // `for (row of list) { … }` — the list is a member (or a row field), the
  1254. // body's entries are rendered once per entry with `row` bound to it
  1255. let body = hlSyntax(gen, key, n.body)
  1256. let children = []
  1257. // THE ROW VARIABLE IS IN SCOPE INSIDE THE BODY, and nowhere else: the list is
  1258. // read in the scope that stands around the `for`
  1259. let list = ref(key, n.list, rows)
  1260. let inner = rows.slice(0)
  1261. inner.push(n.varName)
  1262. for (h of body.entries) {
  1263. let c = node(key, h, path, true, inner)
  1264. if (c != null) { children.push(c) }
  1265. }
  1266. // THE SITE, as every element node carries one: the id the module's tables
  1267. // file this `for`'s row under, so the browser reads what the list depends
  1268. // on from the compiler instead of guessing it off `list.name`.
  1269. return { k = 'for'; row = n.varName; list = list; body = children; site = baseName(pathOf(key)) + ':' + n.line + ':' + n.col; }
  1270. }
  1271. if (n.tag == 'view_if') {
  1272. let then = []
  1273. let cons = hlSyntax(gen, key, n.consequent)
  1274. for (h of cons.entries) {
  1275. let c = node(key, h, path, inFor, rows)
  1276. if (c != null) { then.push(c) }
  1277. }
  1278. let other = []
  1279. let alt = hlSyntax(gen, key, n.alternate) // null when there is no else
  1280. if (alt != null) {
  1281. if (alt.tag == 'view_if') {
  1282. other.push(node(key, n.alternate, path, inFor, rows))
  1283. } else {
  1284. for (h of alt.entries) {
  1285. let c = node(key, h, path, inFor, rows)
  1286. if (c != null) { other.push(c) }
  1287. }
  1288. }
  1289. }
  1290. // A BRANCH CONDITION IS A READ (COMPONENTS: a member or a loop path).
  1291. // Anything else came back null here and the branch rendered nothing, on the
  1292. // server and after hydration, with no word said (ticket #17: `if (!flag)`).
  1293. let cond = ref(key, n.condition, rows)
  1294. if (cond == null) {
  1295. let c = hlSyntax(gen, key, n.condition)
  1296. hlError("hl:web: " + baseName(pathOf(key)) + ':' + c.line + ':' + c.col + " — a View `if` takes a member, a field path or a `for` row variable as its condition, and this one is an expression: declare it at the root of " + baseName(pathOf(key)) + " (`showIt = !flag`) and write `if (showIt)`")
  1297. }
  1298. return { k = 'if'; cond = cond; then = then; other = other; site = baseName(pathOf(key)) + ':' + n.line + ':' + n.col; }
  1299. }
  1300. if (n.tag == 'member_expression') {
  1301. // `p.title` — a field path off a member or a row variable
  1302. let r = ref(key, handle, rows)
  1303. if (r != null) { return r }
  1304. }
  1305. if (n.tag == 'binary_expression' || n.tag == 'unary_expression' || n.tag == 'conditional_expression') {
  1306. // AN EXPRESSION IN A VIEW: its tree, and the names it reads (what repaints it)
  1307. let names = []
  1308. let x = exprTree(key, handle, rows, &names)
  1309. return { k = 'expr'; x = x; names = names; }
  1310. }
  1311. if (n.tag == 'on_statement') {
  1312. // a DOM event handled by the literal that carries it: the browser finds the
  1313. // literal in the instance's View by the path of keys and fires the event at it
  1314. // THE SITE IS THE HANDLER'S ID: the tables file this handler's write set
  1315. // under it, and the browser repaints exactly those members when it runs.
  1316. return { k = 'on'; event = n.event; site = baseName(pathOf(key)) + ':' + n.line + ':' + n.col; }
  1317. }
  1318. return { k = 'other'; tag = n.tag; }
  1319. }
  1320. // the literal name of a `slot { name = 'side' … }` region, null for anything else
  1321. regionName(key, v) {
  1322. for (h of v.entries) {
  1323. let e = hlSyntax(gen, key, h)
  1324. if (e.tag == 'object_property' && e.key == 'name') {
  1325. let val = hlSyntax(gen, key, e.value)
  1326. if (val.tag == 'literal' && val.kind == 'string') { return val.text }
  1327. }
  1328. }
  1329. return null
  1330. }
  1331. // A COMPONENT HAS EXACTLY ONE SLOT (COMPONENTS §2 table, §12): a second one rendered the
  1332. // child a second time, with no word said (mission 322 row 4)
  1333. oneSlot(key, n) {
  1334. let here = baseName(pathOf(key)) + ':' + n.line + ':' + n.col
  1335. if (slotAt[key] != null) {
  1336. hlError("hl:web: " + here + " — a second `slot` in this View (the first is at " + slotAt[key] + "): a component has exactly one slot, where the page it wraps or the fill it is given renders")
  1337. }
  1338. slotAt[key] = here
  1339. return null
  1340. }
  1341. isMember(key, name) {
  1342. for (m of hlMembers(gen, key)) { if (m.name == name) { return true } }
  1343. return false
  1344. }
  1345. // THE READ OF A BARE NAME IN A VIEW — wherever the name stands. A text child, an
  1346. // attribute's value and a reference-site binding are ONE lookup with ONE refusal:
  1347. //
  1348. // a `for` row variable standing around the read → read at render, from the row
  1349. // a member of this file → read at render, from the instance
  1350. // a name this file imports by BRACE → a STATIC of another file:
  1351. // constant-folded here, at build
  1352. // anything else → the located refusal (checkRead)
  1353. //
  1354. // An ATTRIBUTE used to skip the middle two and record every name as a member read,
  1355. // so `a { href = brandHref }` on a braced import asked the instance for a member it
  1356. // does not have and the renderer raised error.UndefinedProperty with view.hl's line
  1357. // and nothing of the app's — while the same name as a TEXT CHILD rendered fine
  1358. // (creator, routger migration W8). A read is a read; where it stands decides
  1359. // nothing about what it names.
  1360. nameRead(key, name, rows, at) {
  1361. if (rows != null && rows.includes(name)) { return { k = 'member'; name = name; } }
  1362. if (isMember(key, name)) { return { k = 'member'; name = name; } }
  1363. // A BRACED IMPORT FOLDS EVEN WHEN ITS VALUE IS NULL: the name resolved, so the
  1364. // read is answered here and never reaches the instance (a null static used to
  1365. // fall through to a member read and raise the same UndefinedProperty).
  1366. if (importsName(key, name)) {
  1367. let folded = importedStatic(key, name)
  1368. // THE VALUE AS WELL AS THE TEXT: an attribute and a text child want the text,
  1369. // and a reference binding wants the value the author's file declared (§12)
  1370. return { k = 'text'; text = folded == null ? '' : '' + folded; kind = 'folded'; value = folded; }
  1371. }
  1372. checkRead(key, name, rows, at)
  1373. return { k = 'member'; name = name; }
  1374. }
  1375. // A VIEW READS ONLY WHAT ITS FILE DECLARES. A name that is neither a member of
  1376. // this class, nor a static it imports by brace, nor a `for` row variable standing
  1377. // around this read, is a typo or a missing declaration — refused HERE, at the
  1378. // build of the tree (boot), naming the file and the line, instead of a 500 out of
  1379. // the renderer with the language's UndefinedProperty and no line of the app's.
  1380. checkRead(key, name, rows, n) {
  1381. if (rows != null && rows.includes(name)) { return null }
  1382. if (isMember(key, name)) { return null }
  1383. if (importsName(key, name)) { return null }
  1384. let hint = name == 'session' ? "`session = null` to receive the connection's session" : name == 'host' ? "`host = null` to receive the request's host" : name == 'headers' ? "`headers = null` to receive the request's headers" : name == 'route' ? "`route = null` to receive the matched route" : "`" + name + " = null`"
  1385. hlError("hl:web: " + baseName(pathOf(key)) + ':' + n.line + ':' + n.col + " — the View reads '" + name + "', which this file declares nowhere: declare it at the file's root (" + hint + "), or write the name it was meant to be")
  1386. }
  1387. // does this file import that name by brace from another file?
  1388. \* `--port=N` or `--port N` among the program's arguments, or null. *\
  1389. portArgument() {
  1390. let given = args()
  1391. let i = 0
  1392. while (i < given.length) {
  1393. let a = given[i]
  1394. let text = null
  1395. if (a.startsWith('--port=')) {
  1396. text = a.slice(7)
  1397. } else if (a == '--port' && i + 1 < given.length) {
  1398. text = given[i + 1]
  1399. }
  1400. if (text != null) {
  1401. let digits = text.length > 0 && text.length <= 5
  1402. let b = toBytes(text)
  1403. let k = 0
  1404. while (k < b.length) {
  1405. if (b[k] < 48 || b[k] > 57) { digits = false }
  1406. k = k + 1
  1407. }
  1408. if (!digits || toNumber(text) > 65535) {
  1409. hlError("hl:web: invalid --port value '" + text + "' — a port is a number 0-65535")
  1410. }
  1411. return toNumber(text)
  1412. }
  1413. i = i + 1
  1414. }
  1415. return null
  1416. }
  1417. importsName(key, name) {
  1418. for (imp of graph.files[key].imports) {
  1419. if (imp.key != null && memberOfImport(imp, name) != null) { return true }
  1420. }
  1421. return false
  1422. }
  1423. // the member of the imported file that the name `name` is bound to here, or null:
  1424. // the name itself, or what `import { a as name }` selected (#142)
  1425. memberOfImport(imp, name) {
  1426. if (imp.locals == null) { return imp.names.includes(name) ? name : null }
  1427. let i = 0
  1428. while (i < imp.locals.length) {
  1429. if (imp.locals[i] == name) { return imp.names[i] }
  1430. i = i + 1
  1431. }
  1432. return null
  1433. }
  1434. // the value of a static this file imports by brace from another .hl file, or null —
  1435. // read off an instance of that file (a class value takes no computed index, an
  1436. // instance does; the file is constructed once, its statics were evaluated at load)
  1437. importedStatic(key, name) {
  1438. for (imp of graph.files[key].imports) {
  1439. let member = imp.key != null ? memberOfImport(imp, name) : null
  1440. if (member != null) {
  1441. if (staticHolders[imp.key] == null) { staticHolders[imp.key] = construct(imp.key, constructionArgs(imp.key, {}, anonSession(), null, null)) }
  1442. return staticHolders[imp.key][member]
  1443. }
  1444. }
  1445. return null
  1446. }
  1447. // THE TREE OF A VIEW EXPRESSION: operators, literals and reads — evaluated by view.hl's
  1448. // `evalExpr`, with the language's own operators. `names` collects the members it reads.
  1449. exprTree(key, handle, rows, &names) {
  1450. let n = hlSyntax(gen, key, handle)
  1451. if (n.tag == 'literal') { return { k = 'text'; text = n.text; kind = n.kind; } }
  1452. if (n.tag == 'identifier') {
  1453. let r = nameRead(key, n.name, rows, n)
  1454. if (r.k == 'member' && !names.includes(r.name)) { names.push(r.name) }
  1455. return r
  1456. }
  1457. if (n.tag == 'member_expression' && !n.computed) {
  1458. let r = ref(key, handle, rows)
  1459. if (r != null) {
  1460. if (!names.includes(r.name)) { names.push(r.name) }
  1461. return r
  1462. }
  1463. }
  1464. if (n.tag == 'binary_expression') {
  1465. return { k = 'bin'; op = n.operator; l = exprTree(key, n.left, rows, &names); r = exprTree(key, n.right, rows, &names); }
  1466. }
  1467. if (n.tag == 'unary_expression') {
  1468. return { k = 'un'; op = n.operator; x = exprTree(key, n.operand, rows, &names); }
  1469. }
  1470. if (n.tag == 'conditional_expression') {
  1471. return { k = 'cond'; c = exprTree(key, n.condition, rows, &names); a = exprTree(key, n.consequent, rows, &names); b = exprTree(key, n.alternate, rows, &names); }
  1472. }
  1473. hlError("hl:web: " + baseName(pathOf(key)) + ':' + n.line + ':' + n.col + " — a View expression holds names, literals, member paths and operators; a " + n.tag + " is none of those — declare it at the root of " + baseName(pathOf(key)) + " and write its name")
  1474. }
  1475. // a READ in the View: a member (`title`), or a field path (`p.title`) whose root
  1476. // is a member or a `for` row variable — the client decides which at render time
  1477. ref(key, handle, rows) {
  1478. let n = hlSyntax(gen, key, handle)
  1479. if (n.tag == 'identifier') { checkRead(key, n.name, rows, n) return { k = 'member'; name = n.name; } }
  1480. // A LIST WRITTEN IN PLACE (`for (n of [1, 2])`) is a literal, read as its value: the
  1481. // same folded 'text' node a folded static is, so every reader takes it the way it takes
  1482. // that one. Its entries are literals — anything else has no value before a read.
  1483. if (n.tag == 'array_expression') {
  1484. let items = []
  1485. for (e of n.elements) {
  1486. let el = hlSyntax(gen, key, e)
  1487. if (el == null || el.tag != 'literal') {
  1488. hlError("hl:web: " + baseName(pathOf(key)) + ':' + n.line + ':' + n.col + " — a list written in a View can hold literals only; declare it as a member to loop over anything else")
  1489. }
  1490. items.push(view.literalValue(el.kind, el.text))
  1491. }
  1492. return { k = 'text'; text = ''; kind = 'folded'; value = items; }
  1493. }
  1494. if (n.tag == 'member_expression' && !n.computed) {
  1495. let obj = hlSyntax(gen, key, n.object)
  1496. let prop = hlSyntax(gen, key, n.property)
  1497. if (obj.tag == 'identifier') { checkRead(key, obj.name, rows, obj) return { k = 'field'; name = obj.name; path = [prop.name]; } }
  1498. let inner = ref(key, n.object, rows)
  1499. if (inner != null && inner.k == 'field') {
  1500. let path = inner.path.slice(0)
  1501. path.push(prop.name)
  1502. return { k = 'field'; name = inner.name; path = path; }
  1503. }
  1504. }
  1505. return null
  1506. }
  1507. // THE COMPOSED CHILD: an entry named after a class the file imports, whose file
  1508. // has a View. `Child { count = count on done(v) { … } }` — the entries are the
  1509. // BINDINGS (host values handed to the child's construction as named arguments)
  1510. // and the reference-site handlers. The graph says which name is which file.
  1511. componentKeyOf(key, name) {
  1512. for (imp of graph.files[key].imports) {
  1513. if (imp.default == name && imp.key != null && viewHandle(imp.key) != 0) { return imp.key }
  1514. }
  1515. return null
  1516. }
  1517. // THE REFERENCE'S SITE IS IN ITS PATH. A path of class names alone made two
  1518. // references of one class under one parent (`body/Card` twice) the SAME node key,
  1519. // so both collapsed onto one mount and one of the two fills was lost. A reference
  1520. // is a construction: each one is its own mount, so each one is its own path.
  1521. componentStep(cls, at) {
  1522. return cls + '@' + at.line + ':' + at.col
  1523. }
  1524. // is this entry a `Style.rule` reference? (the `Style` of THIS file, by name)
  1525. styleRef(key, e) {
  1526. let obj = hlSyntax(gen, key, e.object)
  1527. return obj.tag == 'identifier' && obj.name == 'Style'
  1528. }
  1529. // THE REFERENCE'S POSITIONAL SIGNATURE (§12: "a reference is a construction, so its
  1530. // POSITIONAL entries bind to the class's declared properties in declaration order —
  1531. // the same rule `new X(a, b)` follows").
  1532. //
  1533. // MEASURED, not guessed (2026-09-13, this worker): `new X(a, b, …)` fills the class's
  1534. // root PROPERTY DECLARATIONS in SOURCE ORDER, one slot each — `on` handlers and
  1535. // methods take no slot, and `hlMembers` returns exactly that list in exactly that
  1536. // order, so the tree builder reads the signature straight off it. Three of those
  1537. // declarations are not properties of the COMPOSITION and are left out here:
  1538. //
  1539. // `View` and `Style` — what the component renders and paints WITH, not what it is
  1540. // constructed from. The language does give them a slot (a
  1541. // bare `new` binds them), but §12 says `Card { "text" }` with
  1542. // no declared property takes its text as FILL, and a
  1543. // component always declares a View: counting it would make
  1544. // the positional-literal fill unreachable in every component
  1545. // there is.
  1546. // `slot` — the late-bound child, not state (§12); and with the fill
  1547. // rendered where the child places it the two readings emit
  1548. // the same HTML anyway.
  1549. // every `static` — a static belongs to the CLASS (§12 build-time constants), so
  1550. // a reference cannot seed one for every other reference.
  1551. //
  1552. // A NAMED assignment does NOT free its slot — measured: `new Q('n1', beta = 'B', 'n2')`
  1553. // puts 'n2' in the SECOND declaration and 'B' in beta. It is applied AFTER the
  1554. // positional ones and wins, which is why the positional bindings are emitted first
  1555. // below. (COMPONENTS.md:711 reads "a property the reference also assigns by name is
  1556. // not in the signature"; the interpreter says otherwise and the parenthetical in the
  1557. // same line — "named is applied after positional; the name wins, as in `new`" — is
  1558. // what this follows.)
  1559. positionalSignature(key) {
  1560. let out = []
  1561. for (m of hlMembers(gen, key)) {
  1562. if (!m.isStatic && m.name != 'View' && m.name != 'Style' && m.name != 'slot') { out.push(m.name) }
  1563. }
  1564. return out
  1565. }
  1566. component(key, cls, childKey, v, at, path, inFor, rows) {
  1567. let bindings = []
  1568. let positional = []
  1569. let ons = []
  1570. let fill = []
  1571. let here = path.slice(0)
  1572. here.push(componentStep(cls, at))
  1573. let sig = positionalSignature(childKey)
  1574. let taken = 0
  1575. if (v != null) {
  1576. for (h of v.entries) {
  1577. let e = hlSyntax(gen, key, h)
  1578. if (e.tag == 'object_property') {
  1579. let val = hlSyntax(gen, key, e.value)
  1580. // A BINDING NAMES A DECLARED MEMBER OF THE CHILD (COMPONENTS §12): the value
  1581. // otherwise went into the construction and nowhere, with no word said
  1582. // (mission 322 row 12). An element entry is the fill, not a binding.
  1583. if (val.tag != 'object_expression' && !isMember(childKey, e.key)) {
  1584. hlError("hl:web: " + baseName(pathOf(key)) + ':' + e.line + ':' + e.col + " — " + cls + " has no member '" + e.key + "' to bind: " + baseName(pathOf(childKey)) + " declares " + positionalSignature(childKey).join(', '))
  1585. }
  1586. // A LITERAL ON A REFERENCE KEEPS ITS TYPE (§12 "typed, not stringified"):
  1587. // the binding carries the literal's KIND, and `view.refValue` turns the
  1588. // pair into the value the child's member is given. Written as text alone,
  1589. // `Level2 { n = 1 }` handed the child the String "1" and `n * 97` refused
  1590. // (measured 2026-09-14, demo-nested wall 3).
  1591. if (val.tag == 'literal') { bindings.push({ name = e.key; text = val.text; kind = val.kind; }) }
  1592. else if (val.tag == 'identifier') {
  1593. // a binding is a read at the reference site, so it is the same lookup
  1594. let r = nameRead(key, val.name, rows, val)
  1595. // …and a folded static crosses as its VALUE, for the same reason
  1596. if (r.k == 'text') { bindings.push({ name = e.key; text = r.text; kind = 'folded'; value = r.value; }) }
  1597. else { bindings.push({ name = e.key; member = val.name; }) }
  1598. }
  1599. else if (val.tag == 'member_expression') { bindings.push({ name = e.key; ref = ref(key, e.value, rows); }) }
  1600. else {
  1601. // `Card { span { … } }` — an element entry is not a binding, it is the FILL
  1602. let c = node(key, h, here, inFor, rows)
  1603. // …and an EXPRESSION is neither, so it is refused rather than dropped:
  1604. // the same rule an attribute follows (mission 312 wall 4).
  1605. if (c == null) {
  1606. hlError("hl:web: " + baseName(pathOf(key)) + ':' + val.line + ':' + val.col + " — '" + e.key + "' is bound to an expression on the reference " + cls + ", and a binding is a literal, a member or a field path: declare the expression at the root of " + baseName(pathOf(key)) + " (`" + e.key + "Value = …`) and write `" + e.key + " = " + e.key + "Value`")
  1607. }
  1608. fill.push(c)
  1609. }
  1610. } else if (e.tag == 'on_statement') {
  1611. // A HANDLER WRITTEN ON A REFERENCE IS THE HOST'S, bound on the child's ROOT
  1612. // element. The reference is a literal of THIS file's View, so its behaviour
  1613. // is minted from THIS file's site and its body reaches this file through the
  1614. // owner rule — the same path an element's own handler takes. The child's own
  1615. // handler on that element is not replaced: both are listeners on one element
  1616. // and both run, the child's first, because it was bound when the child's tree
  1617. // was claimed. (Until 2026-09-13 the event was collected here and dropped: a
  1618. // reference with `on submit` never bound, and a form submitted natively.)
  1619. // …AND ITS SITE, because the tables file this handler's write set
  1620. // under it: the browser repaints exactly what it wrote (mission 309).
  1621. ons.push({ event = e.event; site = baseName(pathOf(key)) + ':' + e.line + ':' + e.col; })
  1622. } else if (e.tag == 'member_expression' && !e.computed && styleRef(key, e)) {
  1623. // a `Style.rule` written on a reference: the reference renders no element
  1624. // of its own, so there is nothing for the class to land on (§12)
  1625. hlError("hl:web: " + baseName(pathOf(key)) + ':' + at.line + ':' + at.col + " — a Style rule cannot be written on the component reference '" + cls + "': a reference renders no element of its own. Write the rule on an element inside " + baseName(pathOf(childKey)) + ", or name a '#" + cls + "' local rule in this file")
  1626. } else {
  1627. // AN ORDERED ENTRY. A literal or a read is the next declared property's
  1628. // value while the signature has room — `Button { "SD" }` is `Button
  1629. // { label = "SD" }` — and everything else, plus everything that EXCEEDS
  1630. // the signature, is the FILL: a fragment of THIS file's View, with its
  1631. // reads, its handlers and its `for` rows (§12 "host content").
  1632. let c = node(key, h, here, inFor, rows)
  1633. if (c != null) {
  1634. if (taken < sig.length && (c.k == 'text' || c.k == 'member' || c.k == 'field')) {
  1635. // the same rule as the named form above: a literal keeps its kind and a
  1636. // folded static crosses as its value
  1637. if (c.k == 'text') { positional.push({ name = sig[taken]; text = c.text; kind = c.kind; value = c.value; }) }
  1638. else if (c.k == 'member') { positional.push({ name = sig[taken]; member = c.name; }) }
  1639. else { positional.push({ name = sig[taken]; ref = c; }) }
  1640. taken = taken + 1
  1641. } else { fill.push(c) }
  1642. }
  1643. }
  1644. }
  1645. }
  1646. // THE NAMED ASSIGNMENTS COME LAST, so the name wins over the positional entry that
  1647. // landed on the same property (measured: that is what `new` does)
  1648. let allBindings = []
  1649. for (b of positional) { allBindings.push(b) }
  1650. for (b of bindings) { allBindings.push(b) }
  1651. bindings = allBindings
  1652. // FILLING WHAT PLACES NO SLOT IS A LOCATED ERROR (§12): the child would drop the
  1653. // content silently, which is exactly the bug this rule was written for.
  1654. if (fill.length > 0 && !isMember(childKey, 'slot')) {
  1655. hlError("hl:web: " + baseName(pathOf(key)) + ':' + at.line + ':' + at.col + " — " + cls + " is filled here, but " + baseName(pathOf(childKey)) + " declares no 'slot' to fill: declare `slot = null` there and place `slot` in its View, or write the content outside the reference")
  1656. }
  1657. let classes = []
  1658. if (styleRules(key).includes('#' + cls) && !viewIds(key).includes(cls)) {
  1659. classes.push(view.localClass(key))
  1660. for (t of rootTags(childKey)) { noteRef(key, t, '#' + cls) }
  1661. }
  1662. // THE NODE NAMES ITS CHILD, it does not carry it. What the browser needs to build
  1663. // a child the server never mounted — the module url and the View tree — stands
  1664. // ONCE in the seed's blueprint table, keyed by this `key` (blueprintsIn below).
  1665. // The node used to carry that pair itself, and only when it stood inside a `for`:
  1666. // a child deeper in a minted child's own tree therefore had nothing to build from
  1667. // and was silently missing after a push (a comment card's like button and its
  1668. // edit history, creator's social app, 2026-09-13).
  1669. // THE REFERENCE'S OWN SITE: `file:line:col` of the reference literal, the id the
  1670. // JavaScript target mints ITS behaviour class under — what a handler written on
  1671. // the reference is built from, in the host's frame (client.hl bindRefOns)
  1672. let site = baseName(pathOf(key)) + ':' + at.line + ':' + at.col
  1673. return { k = 'component'; cls = cls; key = childKey; path = here; bindings = bindings; ons = ons; classes = classes; row = inFor; fill = fill; site = site; }
  1674. }
  1675. // ---- Style, the View side (§4, as the archive did it) --------------------------
  1676. // The tree builder writes the class on the element and REPORTS what it wrote
  1677. // (`styleRefs[key]` = [{ tag rule }]) and the element names it rendered
  1678. // (`styleTags[key]`); web/style.hl spells the selectors from those. Three ways
  1679. // a rule reaches an element: `Style.rule` written on it (class = the tag-prefix
  1680. // strip of the rule name), a `#rule` local of this file matching the element by
  1681. // NAME (class = this file's four-character class; `#Child` matches a composed
  1682. // child's root elements), and — decided in style.hl, no class — a rule named
  1683. // like an element of this file's own View.
  1684. styleRules(key) {
  1685. if (styleNames[key] != null) { return styleNames[key] }
  1686. let names = []
  1687. for (m of hlMembers(gen, key)) {
  1688. if (m.name == 'Style') {
  1689. let v = hlSyntax(gen, key, m.node)
  1690. for (h of v.entries) {
  1691. let e = hlSyntax(gen, key, h)
  1692. if (e.tag == 'object_property' && !names.includes(e.key)) { names.push(e.key) }
  1693. }
  1694. }
  1695. }
  1696. styleNames[key] = names
  1697. return names
  1698. }
  1699. noteRef(key, tag, rule) {
  1700. if (styleRefs[key] == null) { styleRefs[key] = [] }
  1701. for (r of styleRefs[key]) { if (r.tag == tag && r.rule == rule) { return null } }
  1702. styleRefs[key].push({ tag = tag; rule = rule; })
  1703. return null
  1704. }
  1705. noteTag(key, tag) {
  1706. if (styleTags[key] == null) { styleTags[key] = [] }
  1707. if (!styleTags[key].includes(tag)) { styleTags[key].push(tag) }
  1708. return null
  1709. }
  1710. // `#name` IS AN ID WHEN THE VIEW HAS ONE (creator's ruling, ticket #51 / R3): a
  1711. // `#name` rule targets the element with `id = 'name'` if this file's View writes
  1712. // that id, and is the file-local class of the elements named `name` otherwise. The
  1713. // ids are read off the View's SYNTAX before the tree is built, because an element
  1714. // named `name` may stand before the element that carries the id. Only a literal id
  1715. // counts — a member-bound one has no value until render. A component reference's
  1716. // own `id = …` is a binding for the child, not an element of this View; its fill is.
  1717. viewIds(key) {
  1718. if (styleIds[key] != null) { return styleIds[key] }
  1719. let out = []
  1720. let handle = viewHandle(key)
  1721. if (handle != 0) { idsIn(key, hlSyntax(gen, key, handle), false, &out) }
  1722. styleIds[key] = out
  1723. return out
  1724. }
  1725. idsIn(key, block, isRef, &out) {
  1726. if (block == null || block.entries == null) { return null }
  1727. for (h of block.entries) {
  1728. let n = hlSyntax(gen, key, h)
  1729. if (n != null && n.tag == 'object_property') {
  1730. let v = hlSyntax(gen, key, n.value)
  1731. if (v.tag == 'object_expression') { idsIn(key, v, componentKeyOf(key, n.key) != null, &out) }
  1732. else if (!isRef && n.key == 'id' && v.tag == 'literal' && !out.includes(v.text)) { out.push(v.text) }
  1733. } else if (n != null && n.tag == 'view_for') {
  1734. idsIn(key, hlSyntax(gen, key, n.body), false, &out)
  1735. } else if (n != null && n.tag == 'view_if') {
  1736. idsIn(key, hlSyntax(gen, key, n.consequent), false, &out)
  1737. let alt = hlSyntax(gen, key, n.alternate)
  1738. if (alt != null && alt.tag == 'view_if') { idsIn(key, { entries = [n.alternate] }, false, &out) }
  1739. else { idsIn(key, alt, false, &out) }
  1740. }
  1741. }
  1742. return null
  1743. }
  1744. // the root element tags of a component's tree (a composed child under `#Child`)
  1745. rootTags(key) {
  1746. let out = []
  1747. for (n of tree(key)) { if (n.k == 'el' && !out.includes(n.tag)) { out.push(n.tag) } }
  1748. return out
  1749. }
  1750. baseName(p) {
  1751. let i = p.lastIndexOf('/')
  1752. return i < 0 ? p : p.slice(i + 1)
  1753. }
  1754. element(key, tag, v, path, inFor, rows) {
  1755. let attrs = []
  1756. let children = []
  1757. let here = path.slice(0)
  1758. here.push(tag)
  1759. let domTag = view.domTag(tag)
  1760. // `body { }` IS THE PAGE'S BODY, and only as the View's root (COMPONENTS §6): below
  1761. // the root it rendered a second, nested <body> no browser keeps (mission 322 row 5)
  1762. if (domTag == 'body' && path.length > 0) {
  1763. hlError("hl:web: " + baseName(pathOf(key)) + ':' + v.line + ':' + v.col + " — a `body` element below the View's root: `body { … }` is the page's body and stands only as a View's root")
  1764. }
  1765. noteTag(key, tag)
  1766. let classes = []
  1767. for (h of v.entries) {
  1768. let e = hlSyntax(gen, key, h)
  1769. let styled = false
  1770. if (e.tag == 'member_expression' && !e.computed) {
  1771. let obj = hlSyntax(gen, key, e.object)
  1772. let prop = hlSyntax(gen, key, e.property)
  1773. if (obj.tag == 'identifier' && obj.name == 'Style') {
  1774. if (!styleRules(key).includes(prop.name)) { hlError("no Style rule named '" + prop.name + "' in " + key) }
  1775. if (prop.name.startsWith('#')) { hlError("'" + prop.name + "' in " + key + " is a LOCAL rule and applies by NAMING the element, not by being referenced — every '" + prop.name.slice(1) + "' this file's View renders already carries it; delete the reference") }
  1776. let cls = view.kebab(view.className(prop.name, tag)) // the class is kebab-case (creator, 2026-09-12)
  1777. if (!classes.includes(cls)) { classes.push(cls) }
  1778. noteRef(key, tag, prop.name)
  1779. styled = true
  1780. }
  1781. }
  1782. if (styled) {
  1783. // a Style reference is not a child
  1784. } else if (e.tag == 'object_property') {
  1785. let val = hlSyntax(gen, key, e.value)
  1786. if (val.tag == 'literal' && view.isBoolAttr(e.key) && val.kind == 'boolean') {
  1787. // A BOOLEAN ATTRIBUTE IS ITS PRESENCE (ticket #33): `disabled = true` is the
  1788. // attribute, `disabled = false` its absence — decided here, once, for every
  1789. // writer of the markup
  1790. if (val.text == 'true') { attrs.push({ name = e.key; text = ''; }) }
  1791. } else if (val.tag == 'literal') {
  1792. attrs.push({ name = e.key; text = val.text; })
  1793. } else if (val.tag == 'identifier') {
  1794. // THE SAME LOOKUP A TEXT CHILD USES: a folded static becomes the
  1795. // attribute's literal text, a member or a row stays a read
  1796. let r = nameRead(key, val.name, rows, val)
  1797. if (r.k == 'text' && view.isBoolAttr(e.key)) { if (view.boolOn(r.value)) { attrs.push({ name = e.key; text = ''; }) } }
  1798. else if (r.k == 'text') { attrs.push({ name = e.key; text = r.text; }) }
  1799. else { attrs.push({ name = e.key; member = val.name; }) }
  1800. } else if (val.tag == 'member_expression') {
  1801. attrs.push({ name = e.key; ref = ref(key, e.value, rows); })
  1802. } else {
  1803. let c = node(key, h, here, inFor, rows)
  1804. // AN EXPRESSION AS AN ATTRIBUTE VALUE IS REFUSED HERE, AND WAS DROPPED IN
  1805. // SILENCE (mission 312 wall 4). `span { id = 'L3t' + n }` rendered no `id`
  1806. // at all and said nothing — the element came back with empty attributes and
  1807. // the author had no line to look at. A View attribute takes a literal, a
  1808. // member or a field path; anything else is a member of this file, declared
  1809. // at its root. The nested-element form (`div { span { … } }`) is the entry
  1810. // whose value is a hybrid, and it is what `node` answers for above.
  1811. if (c == null) {
  1812. hlError("hl:web: " + baseName(pathOf(key)) + ':' + val.line + ':' + val.col + " — the attribute '" + e.key + "' is given an expression, and a View attribute is a literal, a member or a field path: declare the expression at the root of " + baseName(pathOf(key)) + " (`" + e.key + "Value = …`) and write `" + e.key + " = " + e.key + "Value`")
  1813. }
  1814. children.push(c)
  1815. }
  1816. } else {
  1817. let c = node(key, h, here, inFor, rows)
  1818. if (c != null) { children.push(c) }
  1819. }
  1820. }
  1821. // a `#tag` LOCAL rule of this file matches this element by name: the file's class
  1822. // — unless the View writes `id = 'tag'` somewhere, then the rule is that id's (R3)
  1823. if (styleRules(key).includes('#' + tag) && !viewIds(key).includes(tag)) {
  1824. let cls = view.localClass(key)
  1825. if (!classes.includes(cls)) { classes.push(cls) }
  1826. noteRef(key, domTag, '#' + tag)
  1827. }
  1828. if (classes.length > 0) {
  1829. let joined = ''
  1830. for (c of classes) { joined = joined == '' ? c : joined + ' ' + c }
  1831. let merged = false
  1832. for (a of attrs) {
  1833. if (a.name == 'class' && a.text != null) { a.text = a.text + ' ' + joined merged = true }
  1834. }
  1835. if (!merged) { attrs.push({ name = 'class'; text = joined; }) }
  1836. }
  1837. // (§6 sibling entries: inside the literal `tag` would name the entry just written,
  1838. // so the source key is taken before the literal is built)
  1839. let srcKey = tag
  1840. // THE SITE: `file:line:col` of the literal, the id the JavaScript target mints the
  1841. // literal's class under — the browser builds this element's literal from it
  1842. // (hlLiteralNew), so a row created after a list changed has a literal too
  1843. let site = baseName(pathOf(key)) + ':' + v.line + ':' + v.col
  1844. return { k = 'el'; tag = domTag; key = srcKey; path = here; attrs = attrs; children = view.implied(domTag, children, here, site); site = site; }
  1845. }
  1846. // ---- an instance and its state -------------------------------------------------
  1847. // THE ROUTE'S GROUPS ARE THE CONSTRUCTION'S NAMED ARGUMENTS (creator ruling
  1848. // 2026-09-12): `:id` is a parameter of the class like any other, set and pinned
  1849. // before its root runs, so `_post = db.fetch(id)` on line 1 sees it. Nothing is
  1850. // laid over an instance afterwards, and nothing is spelled with a sigil.
  1851. construct(key, &params) {
  1852. if (countConstructs) {
  1853. constructTotal.n = constructTotal.n + 1
  1854. let nm = baseName(pathOf(key))
  1855. constructByFile[nm] = (constructByFile[nm] == null ? 0 : constructByFile[nm]) + 1
  1856. }
  1857. return hlLoad(pathOf(key), params)
  1858. }
  1859. // THE VIEW IS COMPILER OUTPUT, NOT A VALUE — and so, for a render, is the Style.
  1860. // This half reads the View's SYNTAX (`tree()` below, through hlSyntax) and never its
  1861. // value; `state()` ships neither to the browser; the stylesheet is folded into class
  1862. // names at build, by a walk that constructs its OWN instance and reads `Style` there.
  1863. // Evaluating them for a render therefore built a behaviour literal per element per
  1864. // `for` row, per request, for nobody: half the construction time of a 2000-row
  1865. // component, measured 2026-09-14.
  1866. //
  1867. // The framework says so in the one way the language already offers: it PINS them.
  1868. // An explicitly passed construction value outranks every computed default (the
  1869. // creator's rule of 2026-07-26), and a pinned member does not compute its default at
  1870. // all. No language rule about a View was needed and none was added.
  1871. renderedArgs(key, &params, &s, host, &hdrs) {
  1872. let args = {}
  1873. for (k of params.keys()) { args[k] = params[k] }
  1874. pinArgs(key, &args, s, host, hdrs)
  1875. return args
  1876. }
  1877. // the session, host, headers and route a component declares, and the View/Style pins, set in the map handed in
  1878. pinArgs(key, &args, &s, host, &hdrs) {
  1879. if (declares(key, 'session')) { args.session = s }
  1880. if (declares(key, 'host')) { args.host = host }
  1881. if (declares(key, 'headers')) { args.headers = hdrs }
  1882. if (routeNow != null && declares(key, 'route')) { args.route = routeNow }
  1883. if (declares(key, 'View')) { args.View = null }
  1884. if (declares(key, 'Style')) { args.Style = null }
  1885. return null
  1886. }
  1887. // a construction from an argument map the caller built for it alone (`mountKids`): pinned in place, copied by nobody here
  1888. constructOwned(key, &args, &s, host, &hdrs) {
  1889. pinArgs(key, &args, s, host, hdrs)
  1890. return construct(key, args)
  1891. }
  1892. renderArgs(key, &args) {
  1893. let out = args
  1894. if (declares(key, 'View')) { out.View = null }
  1895. if (declares(key, 'Style')) { out.Style = null }
  1896. return out
  1897. }
  1898. // does the file-class declare a member of this name?
  1899. declares(key, name) {
  1900. if (declared[key] == null) {
  1901. let names = {}
  1902. for (m of hlMembers(gen, key)) { if (!m.isStatic) { names[m.name] = true } }
  1903. declared[key] = names
  1904. }
  1905. return declared[key][name] == true
  1906. }
  1907. // EVERY SERVER REFERENCE SITE of `key` (compile.hl `derivList`'s `srv`: an initializer
  1908. // that calls an imported class) that transitively reads `root` — the same closure
  1909. // client.hl's `moved()` walks locally for an ordinary derivation, run here instead
  1910. // because a server reference site must never run in the browser (see that file's
  1911. // `d.srv` branch). The VALUES come from `state` at the call site, already correct —
  1912. // `mount()` just constructed it — this only decides WHICH of its keys belong in
  1913. // `sync`, the same as `moved()` decides which of an instance's members to repaint.
  1914. serverSyncNames(key, root) {
  1915. let list = compiler.tableOf(gen, key).derivations
  1916. let moved = [root]
  1917. let rounds = 0
  1918. let again = true
  1919. while (again && rounds <= list.length) {
  1920. again = false
  1921. rounds = rounds + 1
  1922. for (d of list) {
  1923. if (!moved.includes(d.name)) {
  1924. for (r of compiler.memberNames(d.reads)) {
  1925. if (r != d.name && moved.includes(r)) { moved.push(d.name) again = true }
  1926. }

Only the first lines are shown.

Branches

Latest commits

  • 5b0b4b9ereadme-cache gate: use the security gate's ports when no own ports are givenmre
  • bc8f20d9gitoria#25: re-vendor Hybriel c09538bb with the W141 render cache, cache the homepage per commit, add the readme-cache gatemre
  • 9feebbd3Re-vendor Hybriel to ded47c13 (W145: Firefox start script fix)mre
  • 28ed41e5gitoria#24: one sign-in comes from hl:web batch 20, the /session/share workaround is gonemre
  • 3b2669e4gs: drop the unbuildable legacy check, fix pwa fetchmre
  • 2a2fdd77gs: C2 check before cookie experimentsmre
  • 76e0587aWIP gs 2mre
  • a80da7bdWIP gs: security gate for lazy sessions, g24 browser checksmre
  • 23fb05d8re-vendor Hybriel aaa39e69 (hl:web batch 20: login emit and Sessions.mint, tab follows a login, signed-in session cookie wins among duplicates and is re-issued with the Domain, W85 faster render, lazy sessions)mre
  • a0727ca3ident#31: the selector's sign-in returns to the page the user started on (return attribute = the login callback with next), gate checkmre
  • a06975f9gitoria: a gap between your name and Log out in the phone header (they touched); gate checks itmre
  • 32ba9d59gitoria: leave the host-only cookie experiment out of the browser gate (gitoria#24 is a separate mission)mre
  • 43ad2bcfgitoria header: the selector alone plus your name and Log out as before the theme missions; tests follow (WIP: host-only cookie experiment fails)mre
  • ac2c4e3fident selector back in the header (creator 2026-10-24): selector top right signed in and out on phone and desktop, no second Log in button, new gate checks (WIP: gates not re-run after the last edits)mre
  • b279f536theme: sync from layouts 4994037 (list rows stack, td word-keep, heading code, edited tap target)mre
  • 2b01515ctests/ticketskit: a failed start kills the tickets server (own process group); stop() kills the groupmre
  • 109cfc5ctests/ticketskit: keep the rotated session cookie of the tickets login (tickets ST2 session rotation)mre
  • 7eb6be27sessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre
  • b3911918reports/MG-mobile.md: 404 fixed, rebased gatesMG
  • 9da65b42tests/browser.mjs: 404 checks (host, no hydration wait)MG