gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit4b54f6f94b54f6f9Merge branch 'records-audit' into mainTracker4b54f6f9/plugins/web/WebFramework.hl

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

Only the first lines are shown.

Branches

Latest commits

  • 4b54f6f9Merge branch 'records-audit' into mainTracker
  • cab4a3bc|||PR records: branch audit, PR-onlyTracker
  • 641e1c4cMerge branch 'records-dp71' into mainTracker
  • 85a6e9f5|||PR records: DP71 checked in ChromeTracker
  • f5be5f18records: gitoria PR-only planTracker
  • 46a37036records: DP71 liveTracker
  • 3bcb7039Status/log: DP71 in progressTracker
  • 5b3a5693Log: SR1b merged via PR 2, DP71 startedTracker
  • 783957c2Merge branch 'sr1-search' into mainTracker
  • 792b9652README: search results come from the routeTracker
  • fd8570b1|||PR search: one server exchange per keystrokeTracker
  • e8f5cbcaLog: SR1 result, SR1bTracker
  • 8ad275a4Log/status: tracker 68, SR1Tracker
  • f5a06a0fLog: gitoria push setup, SR1Tracker
  • d6b109baMission SR1mre
  • 608b7558Log: FF1 merged via PR #1mre
  • 2939d94cMerge branch 'ff1-gate-failfast' into mainTracker
  • c934361a|||PR tests: gates fail fast when the app exits during startmre
  • d714ae42Log/status: AP56 closed out, FF1mre
  • a429d088Mission FF1mre