gitoriaLog in with ident

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit38f9d10f38f9d10ftickets: Hybriel master 06617221 (plugin allocators 3a781359 + 413f60e4, mpackdb 2cb7ae5e, http1 773de63e); gate 249/0, connect 60/0mre38f9d10f/plugins/web/WebFramework.hl

169.8 KB

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

Only the first lines are shown.

Branches

Latest commits

  • 38f9d10ftickets: Hybriel master 06617221 (plugin allocators 3a781359 + 413f60e4, mpackdb 2cb7ae5e, http1 773de63e); gate 249/0, connect 60/0mre
  • d3db6139tickets: Hybriel master 190aa11d (fc838894 GC correctness, #126 closure scopes, #127); gate 249/0, connect 60/0mre
  • bce182e3tickets: Hybriel master 7eea0d32 (#126 memory, #48 lambda copies its argument); migrate.hl lambdas take &logmre
  • 4137be0fantcolony#40: mission references point to the moved missionsmre
  • 9bfba36aantcolony#40: history (LOG.md), worker briefs (missions/) and reports moved here from antcolony, numbered per project; old numbers in antcolony docs/mission-map.mdmre
  • c7bd2645tickets: Hybriel master 73267707 (#122 fixed); compactNow workaround removed (#110 covered)mre
  • 2ab91ee9tickets: gate checks rows appear once (session sync); re-vendor to ff51cf46 stopped on hybriel#122, stays 837fe120mre
  • e01c2b1dtickets#24: installable app (manifest, service worker, offline list), own icon; gate waits for the hello's pongmre
  • 752fbb7fdeploy.sh: back up live storage/.sessions/.env before every deploy (newest 5 kept)mre
  • 38bdd5e4deploy.sh: never send .git or .gitignore to Byrodinmre
  • f12fa1bcState of 2026-09-27, before the move to gitoriamre