gitoria

kunibert

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit900ffcd4900ffcd4status: routgermre900ffcd4/plugins/web/WebFramework.hl

268.7 KB

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

Only the first lines are shown.

Branches

Latest commits

  • 900ffcd4status: routgermre
  • 59b0b793log: routger merge waitmre
  • e52f094alog: routger intake check (hycon#122)mre
  • f979027frecords: design rule livemre
  • 71efaf84Merge branch 'design-guard' into mainKunibert
  • c0656581|||PR Flag removal of a documented design as major unless his recorded yes is linked; rules version 5mre
  • 901cdd75records: L10 update 2 livemre
  • 4a68016bMerge branch 'hl-standard-l10b' into mainKunibert
  • 246d0f30|||PR HL-STANDARD L10 update (hybriel ab293e5a), rules version 4mre
  • 1aa4d64crecords: HL-STANDARD L10 update livemre
  • 2b04c240Merge branch 'hl-standard-l10' into mainKunibert
  • 88c7b09d|||PR HL-STANDARD L10 update (hybriel 5885d688), rules version 3mre
  • 00869ecbrecords: gitoria#50 step 3 livemre
  • f97a0e5fMerge branch 'hl-standard' into mainKunibert
  • 9710e39fType STANDARD as String (L10, Kunibert review)mre
  • 4140b664|||PR Review against HL-STANDARD and cite rule ids (gitoria#50 step 3)mre
  • 75c6888drecords: gitoria#50 step 1 connected and provenmre
  • aa6d997frecords: gitoria#50 connect plan, Anton reportmre
  • 8a190ba7Records: kunibert#18 and #15 donemre
  • 2eee9dbbMerge branch 'revendor-day44' into mainKunibert