gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit49533a5049533a50gitoria#43: signed events to connected apps (merge w43-events)mre49533a50/plugins/web/WebFramework.hl

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

Only the first lines are shown.

Branches

Latest commits

  • 49533a50gitoria#43: signed events to connected apps (merge w43-events)mre
  • 1a1e87d5gitoria#43: the sender never writes the apps row; Settings shows the newest deliverymre
  • cd442066gitoria#43: app-auth unit test reads the apps table from its new filemre
  • 5dccbe38gitoria#43: in-flight rows are left alone by the other process; gate in deploy.sh; READMEmre
  • 8c8805f3merge main (gitoria#42), delivery log and redelivery routes, sweep fixmre
  • 5a996ea8gitoria#42: short-lived app tokens, read-only git fetch with them (merge w42-app-token)mre
  • afdb0cbfgitoria#43: rename the moved helper (name clash in the browser build)mre
  • 15e01e94gitoria#43: tests/events.mjs and its probemre
  • 77829b73gitoria#43: signed events to connected apps (deliveries table, sender timer, pull_request events, ping)mre
  • b5d696fegitoria#42: app tokens (gat_, one hour), appOfRequest, app token as the git read passwordmre
  • 1997e77dgitoria#40: stable PR numbers, refs/pull/N/head, ssh pushes reach the app (merge w40-pr-number)mre
  • 9364fb16gitoria#40: ssh pushes call /__git/pushed before and after (ensurePulls, notifyPush, syncPulls); gate over the sshd imagemre
  • fdb9ed28gitoria#41: repo owners can connect an app (merge w41-apps-connect)mre
  • 2ef23df0gitoria#40: the browser gate reads the title without the #Nmre
  • 9af07ecegitoria#41: connect an app to a repo (apps table, connect flow, manual add, allow-list, settings)mre
  • b9137ff0gitoria#40: pull requests are stored with a number, refs/pull/N/head, syncPulls and pullObject; /pulls shows #Nmre
  • 06d622daown image tag gitoria-runtime:debian12 for gitoria and standby (shared tag lost git)mre
  • 20caa33agitoria#37: media queries in the language's @media block (minWidth = '60rem') in list, codebrowser and repomre
  • c4175e6dgitoria: a startup error prints its message before exit 1 (hybriel#247)mre
  • c50d17efKeep function-route not-found style in shared stylesheetmre