gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitc21aff6bc21aff6bMerge branch 'records-hm55c' into mainTrackerc21aff6b/plugins/web/README.md

40.0 KB

  1. # hl:web — the web framework
  2. `hl:web` serves an app's pages from the server and keeps them live in the browser. It is written
  3. in Hybriel: `WebFramework.hl` is the server half, `client.hl` the browser half, and `compile.hl`
  4. turns each component's View into that component's own code. `offline.hl` holds the optional
  5. browser state and durable queue. The model behind it (components,
  6. Views, realms, the boundary) is in [COMPONENTS.md](../../COMPONENTS.md). This page lists the rules
  7. an app is held to. Each rule is a located refusal at boot unless it says otherwise.
  8. ## Starting an app
  9. ```hybriel
  10. import WebFramework from 'hl:web'
  11. import Home from './components/home.hl'
  12. import Styles from './styles.hl'
  13. routes = [ { pattern = "/" component = Home } ]
  14. server = new WebFramework(routes = routes, styles = Styles, port = 8080)
  15. ```
  16. Settings may be passed as named arguments. Most of them may instead be members of the file that
  17. runs the `new`:
  18. | setting | default | meaning |
  19. |---|---|---|
  20. | `routes` | `[]` | the route table (below); pass it as an argument |
  21. | `styles` | none | the app's styles file: the imported class, or a path string. It must be in the project graph |
  22. | `port` | 8080 | the port to listen on |
  23. | `host` | `HL_HOST`/`HOST`, else 0.0.0.0 | the interface to bind |
  24. | `audience` | `{}` | per outward event, who receives it (see Events) |
  25. | `minify` | false | one-line HTML and compact modules; a compact module carries no position tables — the framework answers them at the module's url with `sites=1` in the query, and the browser fetches them once when a fault is reported (mission 505) |
  26. | `watchMode` | true | a saved `.hl` file re-analyses the app and reloads every open tab |
  27. | `sessionDir` | `<app>/.sessions` | where sessions are stored; `false` keeps them in memory |
  28. | `sessionMaxAge`, `sessionIdle`, `sweepInterval` | 14 days, 15 min, 5 min | the session clocks, in seconds |
  29. | `sessionCookie` | `hlsid` | the cookie's name: letters, digits, `-` and `_` |
  30. | `sessionSecure` | null | the cookie's `Secure` flag: null = set when the request came over https (this server speaks TLS, or `X-Forwarded-Proto: https`), true always, false never |
  31. | `sessionAnonMax` | 10000 | the most sessions nobody logged in to; the oldest go first |
  32. | `sessionAnonKeep` | 1 day | seconds an anonymous session with no data keeps its file; the store pass (a few milliseconds per request, never the whole store at once) removes older ones, and never a file that holds a user |
  33. | `appTitle`, `appDescription`, `appImage`, `appFavicon`, `meta` | none | the head every page gets unless it declares its own |
  34. | `links` | none | a list of hybrids, one `<link>` each in every page's head (`{ rel = 'preconnect' href = '…' }`) |
  35. | `appIcons`, `appShortName`, `appThemeColor`, `appBackgroundColor`, `appTouchIcon`, `appManifest` | none | make the app installable: a web app manifest, linked from every head (see Offline and installable) |
  36. | `offline` | none | the pages kept offline: a service worker, their state in IndexedDB, a queue for their emits |
  37. | `pushKey` | none | the app's VAPID public key (base64url): serves the service worker with Web Push, and enables `subscribePush()` (see Web Push) |
  38. | `pushPrivateKey`, `pushSubject` | none | the VAPID private key (base64url, the 32-byte scalar of `pushKey`) and a `mailto:`/`https://` contact: enable `sendPush()` (see Web Push). A key that is not `pushKey`'s other half is refused at boot |
  39. | `pingEvery`, `pongWithin` | 25, 10 | the dead-socket clock, in seconds: the browser pings every `pingEvery`, and a pong missing after `pongWithin` closes the socket and reconnects |
  40. | `uploadMax` | 64 MiB | the largest file an emit may carry, in bytes (see Files in an emit) |
  41. | `uploadSessionMax`, `uploadHeldMax`, `emitMax` | 256 MiB, 1 GiB, 16 MiB | the bytes announced by one session's unfinished uploads, by all sessions', and the largest `POST /__hl/emit` body (413 past them). An accepted upload start makes a session when the visitor has none |
  42. | `pageHeaders` | none | headers added to EVERY answer, over the safe defaults (see Security headers) |
  43. | `trustedOrigins` | none | origins besides the request's own host allowed to emit, upload and open the socket |
  44. | `pushKept`, `pushKeptBytes`, `tabKept` | 10000, 1 MiB, 600 | the push log per tab (see Events): the pushes kept for a socket that comes back, their bytes, and the seconds a tab without a socket is kept |
  45. An app runs on one web framework. If its files reach two packages that hold a `WebFramework.hl`
  46. (for example an old vendored copy beside this one), it is refused at boot, naming the import row
  47. of each.
  48. ## Routes
  49. After a successful login face returns, use `navigate(path, replace = true)` to replace the current login entry so Back reaches the page before it (#379; case `9379`).
  50. Import `{ navigate }` from `'hl:web'` and call `navigate(path)` to add a history entry, or `navigate(path, replace = true)` to replace the current entry. Both apply the matched route in the browser. A URL of another origin loads as a document, replacing the current history entry when `replace = true`. When the page component and its parent chain stay the same, its instance and DOM stand: typed text and open edits survive, while changed route parameters (including removed parameters, which become null), their client derivations and server values update in place. Navigation constructs no page on the server.
  51. Fragment links (#347) keep their fragment in the address. Same-page fragment links use the
  52. browser's native scroll and history without a page request. Cross-page links and
  53. `navigate('/page#section')` scroll to the element with that id after the page stands,
  54. including Back/Forward restores. The fragment never crosses to the server.
  55. Each entry has a `pattern` (`/posts/:id`, `/assets/*`) and one kind:
  56. | kind | answers with |
  57. |---|---|
  58. | `component = Home` or `"./components/home.hl"` | the page, rendered on the server; the component must be imported by the app, and must declare a View |
  59. | `function = (route, req, server) => { … }` | what the function returns (a Hybrid becomes JSON); `req.session` is the cookie's session, or null; `server` is the running WebFramework instance |
  60. | `direct = "text"` | that text |
  61. | `file = "./x"` | one file |
  62. | `directory = "./assets"` | the files under a directory |
  63. A function route may be imported from a separate file. Its third argument is the running
  64. framework, so it can read settings such as `server.appTitle` or call `server.page(…)`.
  65. Declare the third parameter as `&server` to write through it to the running instance.
  66. Existing handlers that declare only `(route, req)` keep working.
  67. `server.page(…)` includes the rendered component’s Style and browser module, its composed children and parent layouts when the component is imported anywhere in the project graph; no component route entry is required.
  68. A named group (`:id`) reaches the component as a construction argument of the same name: declare
  69. `id = null` at its root. A named wildcard does the same with the rest of the path:
  70. `/code/*path` gives `path = 'src/lib/util.hl'` for `/code/src/lib/util.hl`, on the first load and
  71. on a navigation. A bare `*` has no name a member could take; it is what a `directory` route
  72. serves from.
  73. The request itself reaches a component the same way, and only one that declares the member
  74. (COMPONENTS.md): `session = null` gets the session, `host = null` the host without its port,
  75. `headers = null` the request's headers as a hash with lowercase names —
  76. `headers['accept-language']`. On a client navigation they are the headers of the request the
  77. navigation crossed on, so they are still the browser's own: the socket's upgrade request, or the
  78. `POST /__hl/emit` under the fallback. `cookie`, `authorization` and `proxy-authorization` are left
  79. out, because a member is state and state reaches page script.
  80. ## Components
  81. A View `if` refuses expressions: derive `showRows = rows.length > 0` or `enabled = a && !b` at the root and use `if (showRows)` / `if (enabled)`; field paths such as `if (flags.enabled)` also update live (#379; case `9379`).
  82. A component is a `.hl` file with a `View`. Its root members are its state, and are constructed on
  83. the server for each request.
  84. **A View attribute is a literal, a member or a field path.** `href = "/"`, `href = url` and
  85. `href = p.url` are allowed. `href = '/posts/' + id` is refused at its line: declare
  86. `postUrl = '/posts/' + id` at the file's root and write `href = postUrl`. The same holds for a
  87. value bound on a component reference (`Card { title = t }`) and for the condition of an `if` in a
  88. View, which may also be a `for` row variable.
  89. **An attribute name that is not an identifier is quoted.** `"aria-hidden" = "true"` and
  90. `"data-page" = it.target` render as written and bind like any attribute, in a `for` row too. A
  91. camelCase name is not rewritten (`ariaHidden` renders as `ariaHidden`). `data-page = it.target`
  92. unquoted is refused at its line, naming the quoted form.
  93. **A bound attribute in a `for` row follows the row** on every update of the list: a new list, a
  94. `push`, an `upsert` and a write into a row's record (`items[0].title = …`) repaint it, as they
  95. repaint the row's text and class.
  96. Keyed row updates keep an independent snapshot of what was painted (#210). After the
  97. initial snapshot, a change updates its changed fields; unchanged text is retained without
  98. JSON serialisation. The compiled View supplies field read paths, so unrelated element,
  99. text-leaf and nested-region reads skip painting (#355). Reads of a whole record overlap
  100. all its fields. Insertions, removals and replacements still use the keyed row reconciliation.
  101. **The tree carries the elements the HTML parser implies.** `table { tr { td { … } } }` is rendered
  102. as `table > tbody > tr > td`, because that is the tree the browser builds from the HTML, and the
  103. page is continued from the tree the browser built. The pairs are listed in `view.hl`
  104. (`impliedElements`): `tr`, `td` and `th` under `table` get a `tbody`, `td` and `th` under `tbody`,
  105. `thead` or `tfoot` get a `tr`, and `col` gets a `colgroup`. Consecutive children that need the same
  106. container share one.
  107. **Build warnings (#348).** An `a` without `href`, and a click handler on a
  108. non-interactive element, each produce a located warning on stderr once per site
  109. per build; boot continues. Use `a { href = url }` for navigation and
  110. `button { type = "button" }` for actions. Buttons, anchors with href, input,
  111. select, textarea, summary, label, option and details accept click handlers.
  112. A literal role of button/link/tab/menuitem/checkbox/switch together with tabindex
  113. also qualifies. Elements with `contenteditable` are text-editing surfaces: their
  114. click places the caret, so they do not produce the click warning. A tabindex
  115. alone does not qualify. Composed components are checked at their own elements.
  116. The other rules:
  117. - A View reads only names the file declares. A name it declares nowhere is refused.
  118. - `parent './main.hl'` wraps a page in a shell. The shell declares `slot = null` and places
  119. `slot` in its View exactly once. A component that is filled (`Card { p { … } }`) must declare a
  120. slot too.
  121. - **`$parent` is the page or component whose View placed this one** (hybriel#63). In a handler,
  122. `$parent.save(x)` calls a method of that host and `$parent.title` reads one of its members; writing
  123. through it is refused when the file is built. In the browser, hl:web hands the component the live
  124. host instance (never a copy) when it builds it: when the page is hydrated, when a row or an `if`
  125. arm adds a component later, and after a client-side navigation. A page or shell has no host, so
  126. `$parent` there is an error when it runs. **Use it in handlers only for now:** the server builds
  127. the component for the first HTML without a host (the runtime's `hlLoad` takes no builder in the
  128. run form yet), so reading `$parent` in a member initializer or in the View fails the server's
  129. render with "'$parent' has no owner".
  130. - `body { … }` is allowed only as the root of a View, and a page wrapped by a parent cannot have
  131. one: the shell owns the body. A standalone page and a shell both use the existing
  132. document body: its root attributes and Style classes apply there, and its children
  133. render inside it. Client navigation updates that body in place and clears the prior
  134. root's attributes. A bound `class` and Style references share one class attribute.
  135. - A View cannot render itself, directly or through other components.
  136. - A Style rule cannot be written on a component reference. Write it on an element inside that
  137. component.
  138. - A page's head comes from its members `__title`, `__description`, `__image`, `__favicon` and
  139. `__meta`, and falls back to the app's `appTitle`, `appDescription`, `appImage`, `appFavicon` and
  140. `meta`. A handler that writes one of them updates the document.
  141. A plain `Style.notice` emits `.notice`, which loses to an older app `p.notice`; remove or rename the older app rule so the component's Style owns its look (F14), or, if that rule must stay, use a literal View id and its component `Style { '#strong' = { … } }` rule to win by specificity (#379; case `9379`).
  142. In a component, `import { colorText } from '../shared/tokens.hl'` and `Style { p { color = colorText } }` use a shared static token declared with `var()` and imported by the app's styles file; CSS emits `var(--color-text)` and the Style-only token import stays out of the browser module (core fix `6aeb0a48`, #239). Direct component imports of `var` from `'hl:web/css'` are still refused by the core; use token members ([repro](../../missions/web/repros/W327-style-tokens/)).
  143. A View may reference a nested Style rule with `Style.name` when the name is unique
  144. within its component's Style. The class follows the ordinary tag-prefix rule, and
  145. the CSS retains the enclosing descendant selector. Repeated names are ambiguous
  146. (including a top-level and nested pair); the error locates the reference and both
  147. rule declarations. Rename one rule to make the reference unique. A rule repeated
  148. under `@media`, `@supports` or `@container` at the same nesting path restyles
  149. the same rule and does not make the reference ambiguous.
  150. ## Events
  151. `on name(…)` handlers and `emit` statements cross between the browser and the server over a
  152. WebSocket on the app's own port. `POST /__hl/emit` is the fallback for a peer without a socket.
  153. A handler that takes `session` as its last parameter gets the connection's session from the
  154. server, never from the peer. A handler may end its parameters with `request` (after `session`):
  155. `on server login(user, session, request)` gets `{ ip, headers, userAgent, https }` of the carrier, read-only —
  156. `ip` is `X-Client-IP`, else the first `X-Forwarded-For` hop, else the peer address (a WebSocket's upgrade carries none yet).
  157. Trust the proxy headers only behind a proxy that sets them.
  158. The store pass queues filenames only; memory still grows with store size because `hl:fs listDir` buffers the directory.
  159. SESSIONS ARE LAZY: a visitor gets a session (id, file, cookie) only when something is stored in it — a login,
  160. `session.data`, an accepted upload start — so cookie-less requests cost nothing. Existing cookies (same name) and
  161. session files keep working unchanged; logins never expire. Over a socket the ack carries a one-time token the page
  162. trades for the cookie at `POST /__hl/adopt`.
  163. THE COOKIE IS RE-ISSUED (W138). Every HTTP answer that resolves a signed-in session (a page, a function route, a
  164. POST emit, an upload start) sends the session's `Set-Cookie` again when the cookie was never issued with the app's
  165. current attributes (name, `Domain`, `Path`, `Secure`, `SameSite`: a short signature is kept in the session file) or
  166. was last issued more than 24 hours ago. So an old host-only login moves onto the app's `sessionDomain` on its next
  167. visit, and a login with `sessionMaxAge` of 99 years stays inside Chrome's 400-day cap on a cookie's lifetime.
  168. Anonymous sessions are not refreshed, and a socket cannot set a cookie, so sockets are left alone.
  169. An outward event reaches the tab that caused it. To send it to other connections, give it an
  170. `audience` entry: a function of the event's arguments and the receiving connection's session that
  171. answers true or false.
  172. **No push is lost across a socket gap** (ticket #143). A push goes to the tab, not to its
  173. socket: the server numbers every push to a tab and keeps the last `pushKept` of them (at most
  174. `pushKeptBytes`), also while the tab has no socket. The bytes bound is the one that governs: a
  175. busy server pushes hundreds of small frames in a few seconds, and a count bound below the bytes one
  176. turns a short gap into a resync (#160). A tab whose socket comes back (a phone
  177. that slept, a network switch, a socket the ping gave up on) names the last push it got in
  178. its `hello` and is sent the rest again, in order, each once. A gap longer than that log, a
  179. tab gone longer than `tabKept` seconds, or a server that restarted resyncs the tab instead:
  180. the server mounts its shell and page again and sends the members it derives itself (those
  181. that call an imported class, and `session`), which the browser lays over the page. Then
  182. every mounted component that declares `on client reconnected(r)` gets
  183. `r = { how, missed, build, stale }`: `how` is `'replayed'` (nothing was lost; `missed` pushes came again)
  184. or `'resynced'` (a member only a push handler builds up may lack what was pushed meanwhile —
  185. ask the server for it here). `build` is the server's build and `stale` is true when it is not
  186. the build this page was rendered by — the server restarted onto changed sources (ticket #152;
  187. in every mode, `watchMode` additionally reloads the tab itself). It fires once per reopened
  188. socket, never on the first.
  189. **A page shown again** (#174). Every mounted component that declares `on client shown(r)` gets
  190. `r = { persisted }` when the browser shows the page: on `pageshow` (`persisted` is true for a restore
  191. from the back/forward cache, false for the first show) and when `visibilitychange` makes the tab
  192. visible (`persisted` false; turning hidden does not call it). An app re-plans here, without waiting
  193. for the user's first touch.
  194. ```hybriel
  195. on client reconnected(r) {
  196. if (r.stale) { location.reload() }
  197. if (r.how == 'resynced') { refresh() }
  198. }
  199. ```
  200. A value-form emit (`answer = emit server ask()`) waits for one answer, so it has one answerer.
  201. If two files in the target realm answer the event, it is refused.
  202. **A write anywhere repaints what it wrote** (tickets #98, #99), from the compiler's write
  203. sets, never by watching the members:
  204. - A listener repaints what its handler writes when the handler is done. A handler still
  205. waiting after the task that started it (a network answer, `new Promise(…)`) has its
  206. write set painted at the next animation frame too, so what it wrote before
  207. the wait shows while it waits, even when timers are throttled.
  208. - A function made inside a component — an `XMLHttpRequest`'s `onload` or `onprogress`, a
  209. timer, a Promise's executor, a `then` — is compiled so that every return of it is
  210. announced with the site it was made at. What it writes (a member, a push into one, a
  211. field inside one, and what the methods it calls and the events it emits write) is
  212. repainted at the next animation frame. A function that writes no member
  213. repaints nothing.
  214. - A repaint the listener already made before that frame is not made twice.
  215. - Late paints also schedule a zero-delay timer: it and the animation frame race,
  216. and only the first drains the pending writes. A hidden tab therefore paints
  217. without waiting to become visible; throttled timers still allow the frame to
  218. paint a visible tab (#378).
  219. **After a face that takes `session`** (tickets #121, #122), the server re-derives the
  220. members that read `session` for every mounted component of the tab that declares `session`,
  221. with each mount's current browser dependency values, carried on the original emit frame (#382). Only the
  222. required initializers run on a blank server instance; their values return in the ack
  223. (`sync`) before the emitting handler continues. No page is constructed and no extra
  224. round trip is needed.
  225. The REST carrier does the same for mounted components named in the emit's `sessionArgs`, including a held login replayed before the first socket opens (#349).
  226. A server face's own writes (its declared members) travel as a separate numbered push `{ t: 'sync', n, sync: { <file>: { member: value } } }`
  227. to the emitting tab only, sent before the face's outward `emit client` frames and before the ack (COMPONENTS §10).
  228. - A member that reads `session` and calls an imported class, directly or through a local
  229. method or static, is computed on the server only and never re-derived in the browser.
  230. - Such a member is already up to date when the handler continues, so a client handler that
  231. appends the face's returned row to a list derived from `session` shows it twice. Assign
  232. from what the sync brought, or leave the list to the sync.
  233. - A member derived from `session` that needs a server-only resource (a database) must reach
  234. it through an imported class or a static of one; a plain copy (`me = session.user.id`) is
  235. derived everywhere.
  236. ### Files in an emit
  237. A browser `File` (an input's `ev.target.files[0]`, a dropped file) or a list of them
  238. (`ev.target.files`) may be an argument of an `emit server …`. It never rides the socket:
  239. the first File-bearing emit loads `/__hl/uploads.js?v=<build>` once, then the upload provider sends each file to `/__hl/upload` as its own HTTP
  240. requests, with the page's session cookie, in parts of 1 MiB. The face gets the file in its
  241. place as `{ bytes, name, type, size }` (`bytes` a `Bytes`), or a list of those for a list:
  242. ```hybriel
  243. input { type = 'file' on change(ev) { emit send(ev) } }
  244. on send(ev) { saved = emit server saveFile(ev.target.files[0]) }
  245. on server saveFile(file) {
  246. writeFile('uploads/' + file.name, file.bytes)
  247. return file.size
  248. }
  249. ```
  250. - **Progress.** While a file is sent, every mounted component that declares
  251. `on client uploadProgress(p)` gets `p = { event, index, name, sent, size }`: the emit's
  252. event, the file's position among the emit's files, its name, the bytes sent so far and
  253. its size.
  254. - **A dropped connection.** A part that did not come back is asked for again: the client
  255. waits (250 ms, doubling up to 4 s), asks the server how much of the file it has, and goes
  256. on from there. After 8 drops in a row it gives up.
  257. - **A failed upload ends the emit.** A file the server refuses (bigger than `uploadMax`, an
  258. upload of another session) or a connection that stays down ends the emit with that error
  259. instead of sending it — except a queueable emit in an offline app, which is queued with its
  260. files when the connection is what failed (COMPONENTS §10): it gets the failed ack a failing face sends
  261. (`{ t: 'ack', i, ok: false, error }`), so a value-form emit answers null and the error is
  262. logged. The face does not run.
  263. - An upload belongs to the session that started it, and one emit takes it. An upload that
  264. nothing takes within an hour is dropped. The parts are held in the server's memory until
  265. the emit takes them.
  266. ## Offline and installable
  267. Browser `online`/`offline` events alone update `__hlOnline` and do not fire `on client reachability(r)`; socket/probe changes do, with `{ reach, was }` (for example `'down'`/`'up'` on socket loss), and online can prompt a reconnect (#379; case `9379`).
  268. The full model is [COMPONENTS.md §10](../../COMPONENTS.md). An app writes no JavaScript for any
  269. of it. Declaring `offline` (including `offline = []`) loads `/__hl/offline.js?v=<build>`
  270. before components are constructed and includes it in the worker precache. Apps without
  271. that declaration load the base client alone until an emit carries a File. Offline apps also precache the upload provider so queued Files can replay without a new module download.
  272. ```hybriel
  273. appTitle = "Hybriel Notes"
  274. appIcons = [ { src = "/static/icon-192.png" sizes = "192x192" } { src = "/static/icon-512.png" sizes = "512x512" } ]
  275. offline = [ NoteList, NoteEditor ]
  276. ```
  277. - `appIcons` (or `appManifest`, or `offline`) serves `/__hl/manifest.webmanifest` and links it,
  278. with an apple-touch-icon, from every page's head. `appManifest`'s entries are written over the
  279. generated manifest.
  280. - `offline` lists pages: route components, as classes or path strings. Anything else is refused
  281. at its line. The framework generates the service worker and registers it. The shell and the
  282. listed pages' documents are cached, and a real document load or start is network-first. When the network gives no answer for 1.5 s and a kept copy exists, the copy is served and the fetch refreshes it in the background. A document served from the cache is marked in its seed, and its first socket resyncs the page and shell (#143); a network-rendered document does not. What the server last
  283. said about a listed page is kept in IndexedDB and shown over an older cached document. A
  284. statement-form `emit server …` from a listed page that does not reach the server is queued and
  285. replayed in order when the socket reopens. Each queued emit carries a stable id, and the
  286. server runs it once: a replay whose ack was lost is answered again without running the handler
  287. (the last 200 ids per session are kept). A socket that goes silent without closing is noticed
  288. by the ping and reopened. A queued emit keeps its files: IndexedDB holds them with the entry,
  289. and they go up on the replay under the emit's id, once (COMPONENTS §10). A queueable emit on an
  290. open socket is written to the queue first and sent after, and leaves it on its ack, so an app
  291. killed while its connection stalls still has it; the replay sends it under the same id. A page that
  292. declares `__hlQueued = 0` /
  293. `__hlQueue = []` shows the queue. A page that declares `__hlOnline = true` has it follow the browser's
  294. connection (`navigator.onLine`, and the online/offline events), so a View can say "you are offline".
  295. `__hlReach = 'connecting'` follows whether the server answers (`'up'`, `'down'`), `on client reachability(r)` runs on a change,
  296. and `takeBack(q)` (an import from hl:web) takes a waiting emit back (a `__hlQueue` row's `q`); see COMPONENTS §10.
  297. - When reachability is `down`, a link or `navigate()` to a component declared in `offline`
  298. completes locally in the existing document (#377), with new parameters and route/query state.
  299. It uses the exact address's kept server data and component-wide server values. Client members
  300. get fresh initial values as online; no draft is copied from the origin into the destination.
  301. Back restores the origin's draft where the online history cache retains that page (a standing
  302. shell); shell-less pages are constructed fresh as online. A route-dependent server-read
  303. member is null until reconnect when no value is kept for that address. Reconnect requests a full
  304. values resync and patches the current page without a document load or server page construction.
  305. [COMPONENTS §10](../../COMPONENTS.md#10--offline-and-an-installable-app-current-hlweb) details the state rules.
  306. Online navigation and non-kept destinations keep #346's waiting carrier: document, draft and
  307. timers stay; the slot carries `aria-busy="true"` and `data-navigating` until recovery. The page
  308. request waits separately from the durable app-emit queue. Cached documents still serve real
  309. document loads or starts, with the bounded wait and cached-start resync described above.
  310. - `offlineFallback = Start` (a route component, class or path string, answered by a route with no
  311. parameter; needs `offline`) names a DATA-FREE page: the worker keeps its document once, fetched without
  312. credentials, and shows it for any page it has nothing for while the network is down. Without it, a kept
  313. document with a shell supplies the layout and app title; the framework puts an "Unavailable offline"
  314. status notice in its page slot before first paint, without constructing the donor page. Links in this notice document load
  315. through the worker so kept pages remain reachable offline (#350; navigation to a non-kept destination waits for
  316. the server, #346). When no kept document has a shell, the bare 503 notice remains. A page (kept or the fallback) that declares `__hlDataFree = true` is kept
  317. the same way — its document is the anonymous one, and the browser keeps neither its state nor a queue for it.
  318. - `offlineFiles = ['/md-editor.js', '/vendor/lib.js']` (needs `offline`) lists the app's OWN file-route urls the
  319. worker precaches at install and serves cache-first offline (ticket #170). Exactly the urls listed: a
  320. directory route is never kept as a tree, list each file you need. Not set: no extra file is kept.
  321. - Kept state is per component for a member no route parameter feeds (the same list at every url of
  322. the page), per url for the rest. A param page that was never loaded as a document is answered offline
  323. with a kept document of the same component, booted with the url's parameters. The shell, its
  324. parent levels and the components composed into them are kept by the same rules (per member, with
  325. the server's time, laid over a cached document only when newer), under keys that are never a page's.
  326. So are the components composed into the page itself, at any depth (#343), under `@page|…` keys.
  327. - An app that registered its own `/sw.js` before moving to `offline`: hl:web does not register while a
  328. worker controls the page (COMPONENTS §10).
  329. - What is kept belongs to the last user who was logged in. An expired or fresh anonymous session
  330. changes nothing: that user's queue is held, and replays when the same user logs in again (the server
  331. refuses a replay made for another user). Another user logging in forgets the copy (state, queue and the
  332. worker's documents); an entry from before users were kept is dropped unsent. A
  333. face that logs the session out forgets the copy by itself (the ack says whose session it is now);
  334. an app with its own logout calls `forgetOffline()` from `hl:web`.
  335. - In any app, an emit in flight when its socket closes is sent again with its id over the POST
  336. fallback or the next socket, and answered there (ticket #107). A page being left
  337. (`beforeunload`, `pagehide`) reopens nothing and posts nothing.
  338. - **A failed answer after a give-up means "not run".** An emit that waits for a socket that stays closed
  339. ends, at the give-up (`window.__hlGiveUp`, 120 s), with the failed answer (`null` for a value-form emit).
  340. The POST carrying it is aborted then, and the frame carries `by`, the give-up horizon in the *server's* clock
  341. (the time the server last told the page, in the clock frame after a hello or in a pong, plus the duration the page measured since, plus
  342. the give-up; client and server clocks are never compared). A frame that reaches the server after `by` (a proxy
  343. held it) is refused and run by no face, so the app that was told "failed" is never contradicted. The horizon is
  344. early by at most one message latency, which can only refuse an emit the page was about to give up anyway.
  345. - `import { notify, notifyAt, notifyIn } from 'hl:web'` shows a notification now, or at a time while the page
  346. is open. A closed app cannot be woken at a set time without a server push.
  347. ## Web Push
  348. A reminder for a closed app is a server push the service worker shows. This is the browser half
  349. (ticket #173); the server's VAPID signature and payload encryption are `hl:crypto`'s.
  350. - `pushKey = '<base64url VAPID public key>'` (a `WebFramework` argument or a manifest member) serves
  351. the service worker — also in an app with no `offline` (it then keeps nothing and answers every fetch
  352. from the network) — and tells the page the key.
  353. - The worker handles `push`: the payload is JSON text `{ "title", "body", "url", "tag", "icon" }`, shown
  354. with `registration.showNotification` (a payload that is not JSON becomes the body, titled with the
  355. host). On `notificationclick` it focuses an open window of the app, else opens `url` (default `/`).
  356. - `import { subscribePush } from 'hl:web'`: in a handler, asks for notification permission (on first
  357. use), registers the worker if the page has none, calls `pushManager.subscribe({ userVisibleOnly:
  358. true, applicationServerKey: pushKey })` and answers `{ endpoint, expirationTime, keys = { p256dh, auth } }`,
  359. or `null` (no push support, permission refused, no `pushKey`, subscribe failed — said in the console).
  360. The app hands it on with its own emit:
  361. ```
  362. import { subscribePush } from 'hl:web'
  363. View { button { "Turn on notifications" on click(e) { let s = subscribePush() emit server savePush(s) } } }
  364. on server savePush(s) { /* store s.endpoint, s.keys.p256dh, s.keys.auth for this user and device */ }
  365. ```
  366. ### Sending a push (the server half)
  367. - `pushKey`, `pushPrivateKey` and `pushSubject` together enable `import { sendPush } from 'hl:web'`, called in an `on server`
  368. handler or a route function (in a component's browser build the name binds to a refusal, like any server-only name).
  369. - `sendPush(subscription, payload, opts)`: `subscription` is what `subscribePush()` gave (`endpoint`, `keys.p256dh`,
  370. `keys.auth`), as the app stored it; `payload` a String or Bytes up to 3993 bytes (the worker shows JSON text
  371. `{ title, body, url, tag, icon }`); `opts` = `{ ttl` (seconds, default 86400), `urgency` (`'very-low'`, `'low'`, `'normal'`,
  372. `'high'`), `topic` (up to 32 URL-safe characters) `}`. It signs a VAPID JWT (ES256, `aud` the endpoint's origin, 12 h), encrypts
  373. the payload (RFC 8291 aes128gcm, one record) and POSTs it with hl:fetch.
  374. - It answers `{ ok, status, gone, error }`: `ok` is a 2xx (201 = accepted); `gone` is a 404/410, the subscription is dead and
  375. the app drops it; `status` 0 with `error` is a malformed subscription, or a push service that cannot be reached (the latter
  376. only where the caller has an `on Error(e)` handler — without one hl:fetch faults the call, as it does everywhere).
  377. - A call blocks its handler until the push service answers (15 s at most). A missing setting is a located error.
  378. ## What it serves
  379. | url | what |
  380. |---|---|
  381. | `/<file key>` (e.g. `/components/home.hl`) | a component's browser module |
  382. | `/__hl/modules/<sha256>.hl` | a module imported from above the project folder; its opaque key is `__hl/modules/<sha256>.hl` in seeds, component tables and transport frames |
  383. | `/__hl/hl-runtime.js` | the runtime every module imports |
  384. | `/__hl/web/client.js` | this package's browser half (other packages' halves are at `/__hl/<name>/client.js`) |
  385. | `/__hl/offline.js` | the optional browser state and durable queue, for an app declaring `offline` |
  386. | `/__hl/app.css` | the one stylesheet, built from the styles file and every component's `Style` |
  387. | `/__hl/emit` | the POST fallback for emits |
  388. | `/__hl/up` | an empty `204`: the probe a tab makes once a second while its socket waits to reconnect, so it is back within about a second of a restarted server (ticket #153; the backoff between socket attempts stops at 4 s) |
  389. | `/__hl/manifest.webmanifest` | the web app manifest, for an installable app |
  390. | `/__hl/sw.js`, `/__hl/web/worker.js` | the service worker's entry script and its compiled module, for an app with `offline` or `pushKey` |
  391. | `/__hl/upload` | a file of an emit, in parts (`POST` `{ name, type, size, q, n }` → `{ id, have }`, or `{ handled }` when the session handled emit `q` already; `POST ?id=&at=` one part → `{ have }`; `GET ?id=` → `{ have }`) |
  392. The page loads the modules and the stylesheet as `<url>?v=<hash>`, where the hash covers everything the build serves. A url with the current hash is sent with `Cache-Control: public, max-age=31536000, immutable`, and any other url with `no-cache`. A deploy therefore changes every url, and a tab that navigates into a newer build loads that page as a full document.
  393. An app's own `file` and `directory` routes keep the same url across deploys, so they answer with an `ETag` of the content and `Cache-Control: no-cache` (a route's own `Cache-Control` header replaces that). A request whose `If-None-Match` names the current tag gets a `304` with no body.
  394. ## Cloned row templates: measured, not adopted (ticket #68)
  395. Svelte clones one hoisted `<template>` per row or branch shape; hl:web builds a browser-created row element by element. Measured with `tests/browser/bench-web-rows.mjs` (headless Chrome, a clean page before every run, best of 5, ms, master c183052c):
  396. | case | ms |
  397. |---|---|
  398. | replace 1000 rows (li, 3 elements, an `if` inside) | 338 |
  399. | append 10 x 100 rows (same row) | 780 |
  400. | deep row, 20 elements x 300 rows | 7.5 |
  401. | shallow row, 2 elements x 1000 rows | 14 |
  402. | toggle an `if` branch 1000 times | 45 |
  403. DOM creation is not where the time goes: the CPU profile (`HL_BENCH_PROF=<case>`) puts `createElement`, `setAttribute` and `appendChild` together under 3% of the cheap cases and the dearer cases are bound by something else. A 20-element row costs 25 us per row in total, a 2-element row 14 us; cloning could not make either 1.2x faster, and the machinery that wires sites, events and marks onto a clone is the same code the walk runs today (a claim walk over the clone), so nothing is saved there either. No prototype was built: the bound from the profile is under 1.03x.
  404. What the profile does show: the 3-element row with an `if` costs 340 us, and 115 ms of its 340 is `rehome` -> `sitesOnto`, which scans the mount's WHOLE `m.sites` for every row built and copies each site it reads (value semantics), so a build of n rows is O(n x sites). The append case is worse (780 ms) for the same reason plus `updateRow` on the rows that stay. That is the cost to attack, not element creation.
  405. ### The fix that followed (ticket #68, second step)
  406. `sitesOnto` now reads `m.sites` from the end, stops at the first site older than the walk's, and writes `el` in place instead of copying each site. `rebindRow` decides once per row body whether it composes a child (nothing to take again if not) instead of copying the seed's tree for every row that stays, and `rowPaint` reads its paint entry in place (`paintEntry`) instead of copying the compiled table. Same bench, old (c183052c) vs new, best of 5, ms:
  407. | case | old | new | ratio |
  408. |---|---|---|---|
  409. | replace 1000 rows | 342.0 | 20.0 | 17.1x |
  410. | append 10 x 100 rows | 782.3 | 92.6 | 8.5x |
  411. | deep row 20 el x 300 | 8.4 | 7.6 | 1.1x |
  412. | shallow row 2 el x 1000 | 18.2 | 13.1 | 1.4x |
  413. | toggle if-branch x 1000 | 48.8 | 40.2 | 1.2x (noise: 0.98x to 1.2x across runs) |
  414. Typing in a routger chat (a copy of the app, 30 keystrokes, main-thread time) is unchanged at about 1.5 ms per key: a keystroke builds no rows. Gates: `HL_WEB_STRICT=1` framework browser test 398 ok, `tests/core-ast/web-tickets.mjs` 205 ok.
  415. ## Session rotation (W120)
  416. `session.rotate()` in a face that logs a session in (the handler takes `session`) mints a new session id when it returns,
  417. moves user/data/handled to it and deletes the old id (a planted cookie is anonymous). The REST carrier answers with
  418. `Set-Cookie`; over the socket the server pushes `{ t: 'rotate', token }` and the client POSTs `/__hl/rotate` (Origin-checked,
  419. one-shot token + the current cookie), whose answer sets the cookie. All live tabs of the session follow. See COMPONENTS.md.
  420. ## Security headers and cross-site requests
  421. Every answer carries `X-Content-Type-Options: nosniff`, `Referrer-Policy: strict-origin-when-cross-origin`,
  422. `X-Frame-Options: SAMEORIGIN` and `Content-Security-Policy: frame-ancestors 'self'` — pages, the 404, `/__hl/*`
  423. and the app's own routes. A header a route sets itself is left alone. The app adds or replaces any of them
  424. (and a script CSP, which is not a default because it would break apps) with `pageHeaders`; `null` removes one:
  425. ```hybriel
  426. pageHeaders = { 'Content-Security-Policy' = "default-src 'self'" 'X-Frame-Options' = null }
  427. ```
  428. `POST /__hl/emit`, `/__hl/upload` and the WebSocket upgrade refuse a cross-site caller: `Sec-Fetch-Site: cross-site`,
  429. or an `Origin` that is not the request's `Host` (or `X-Forwarded-Host`) nor listed in `trustedOrigins`. The first two
  430. answer 403; a socket is closed straight after its handshake. A request with no `Origin` (curl, another server) passes.
  431. **Behind a proxy on a non-443 port** (W123): nginx's `proxy_set_header Host $host;` drops the port while the browser's
  432. `Origin` keeps it (`https://h:8443` vs `Host: h`). A `Host` (or `X-Forwarded-Host`) WITHOUT a port is compared with the
  433. Origin by hostname only (cookies are not port-scoped); with a port it must match exactly, and an `X-Forwarded-Port`
  434. completes a portless one. Prefer `proxy_set_header Host $http_host;` (keeps the port), or send `X-Forwarded-Host` /
  435. `X-Forwarded-Port`; otherwise list the origin in `trustedOrigins`. A refused socket or emit logs one console warning
  436. naming Origin vs Host, and the client backs off (the reconnect delay resets only when the server answers a frame).

Branches

Latest commits

  • c21aff6bMerge branch 'records-hm55c' into mainTracker
  • 9ba258d3|||PR records: HM55b resultTracker
  • 64f2d300Merge branch 'records-hm55b2' into mainTracker
  • ae3b80dc|||PR records: HM55b briefTracker
  • 7ef3cb3bMerge branch 'records-st55' into mainTracker
  • fec2e080|||PR records: STATUS HM55Tracker
  • 8e174918Merge branch 'records-hm55b' into mainTracker
  • b1ecee57|||PR records: HM55 stateTracker
  • 28eab08cMerge branch 'records-hm55' into mainTracker
  • d3edaa05|||PR records: HM55 start, PROCEDURES.mdTracker
  • 3059f86cMerge branch 'records-design-rule' into mainTracker
  • 421a4809|||PR records: his-design rule (Apollo 2026-11-13)Tracker
  • d1390692Merge branch 'records-dp75b' into mainTracker
  • a4d1a7d2|||PR records: later steps checked, branch auditTracker
  • e070e16fMerge branch 'records-dp75' into mainTracker
  • 642b4fa8|||PR records: DP75 day62 live, AP62 briefTracker
  • bfc4ea4dMerge branch 'ap62' into mainTracker
  • 2c95ac46|||PR AP62: re-vendor Hybriel set day62 (source 70341ad2, bin a54f5f08)Tracker
  • b9c7c3c8Merge branch 'records-dp74' into mainTracker
  • 85cfb4ae|||PR records: AP61 day61, DP74 liveTracker