gitoriaLog in with ident

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit68dcb60368dcb603deploy.sh: back up live storage/.sessions/.env before every deploy (newest 5 kept)mre68dcb603/plugins/web/WebFramework.hl

152.2 KB

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

Only the first lines are shown.

Branches

Latest commits

  • 68dcb603deploy.sh: back up live storage/.sessions/.env before every deploy (newest 5 kept)mre
  • e2deed6dgitoria#20: "Add code" only on the Code page of an empty repository, no collapsiblemre
  • 8bb97ffddeploy.sh: never send .git or .gitignore to Byrodinmre
  • fd981932State of 2026-09-27; bin/ no longer tracked (Hybriel commit is in README)mre
  • 4a2d7125initial commitmre