notes
All repositories: gitoria
10.6 KB
// The framework's SERVICE WORKER (COMPONENTS §10, D38) — the offline shell. It exists// only for an app that declares `offline = [ … ]`: hl:web compiles this file like// client.hl, serves it at /__hl/web/worker.js, and registers the entry script// /__hl/sw.js, which imports it and constructs it ONCE with the table below.//// WHAT IS KEPT IS THE APP'S DECISION (D38). `precache` holds the shared shell —// the runtime, the client half, the stylesheet, every page module, the web app// manifest and its icons — plus the DOCUMENT of each param-free route whose// component the allow-list names. `routes` is the client's route table with// `keep` on the rows the allow-list names, so a param-bearing page (`/notes/:id`)// is kept when it is VISITED, and only then. Every other page is unavailable// offline, and says so.//// THREE RULES, the ones the old hl:web ran (mission 101):// · a NAVIGATION is network-first. The network is the truth while it answers,// and a fresh document for a kept page replaces the cached one on the way past;// the cache is what an outage falls back to.// · a precached asset is cache-first. Its url carries the build's hash, so a hit// cannot be stale.// · everything else goes to the network untouched: the emit channel, a function// route, an app's own file. The socket never reaches a worker at all.//// WHY THE ENTRY SCRIPT IS NOT THIS FILE. A worker must add its listeners while its// script is first evaluated, and a `fetch` listener must hand `respondWith` its// promise before the listener returns. Every call in this language is awaited, so// neither can be written here; /__hl/sw.js does exactly those two things and calls// the methods below for everything else (WebFramework.hl, `workerEntry`).import HlwRouter from './router.hl'cfgText = '' // the table, as JSON text (the one construction argument)cfg = JSON.parse(cfgText)router = new HlwRouter(routes = cfg.routes)// INSTALL: the shell into this build's cache, one url at a time — a single failed// url must not throw the whole install away and leave the app with no shellinstall() {let cache = globalThis.caches.open(cfg.cache)for (url of cfg.precache) {// a data-free page is fetched as nobody: its document carries no user's state (#120)let creds = cfg.dataFree.includes(url) ? 'omit' : 'same-origin'let r = globalThis.__hlAttempt(() => { return fetch(url, { cache = 'reload' credentials = creds }) })if (r.ok && r.value.ok) { cache.put(url, r.value) }}globalThis.skipWaiting()return null}// ACTIVATE: the cache name carries the build's hash, so every other hl cache is an// older deploy's. This worker then controls the pages that are already open.activate() {for (name of globalThis.caches.keys()) {if (name != cfg.cache && name.startsWith('hl-shell-')) { globalThis.caches.delete(name) }}globalThis.clients.claim()return null}// FETCH: what answers this request. Never null — the entry script hands the answer to// `respondWith` unread.answer(req) {if (cfg.shell == false) { return fetch(req) }if (req.method != 'GET') { return fetch(req) }let url = new URL(req.url)if (url.origin != globalThis.location.origin) { return fetch(req) }if (req.mode == 'navigate') { return navigation(req, url) }if (cfg.precache.includes(url.pathname + url.search)) { return cacheFirst(req, url.pathname + url.search) }return fetch(req)}// may the document at this path be kept? Only if the route that answers it is a page// the allow-list names — the whole of D38 in one predicatekept(path) {let m = router.match(path)return m != null && m.route.keep == true}// HOW LONG A NAVIGATION WAITS FOR THE NETWORK when a kept copy of the page exists (#340), in ms.// A silent connection (no answer, no refusal) would otherwise show nothing at all. After this the// copy is served and the fetch goes on in the background; if it succeeds it refreshes the copy// (the page already shown stays). A page with no copy, or not kept, waits for the network.navWait = 1500navigation(req, url) {path = url.pathname + url.searchlet copy = nullif (kept(url.pathname)) {copy = globalThis.caches.match(path, { cacheName = cfg.cache })if (copy == null) { copy = standIn(url.pathname) }}let r = nullif (copy != null) {r = globalThis.__hlWithin(() => { return fetch(req) }, navWait, (late) => {if (late.ok && late.value.ok && !cfg.dataFree.includes(url.pathname)) { keep(path, late.value.clone()) }return null})if (r.late == true) { return marked(copy) }} else {r = globalThis.__hlAttempt(() => { return fetch(req) })}if (r.ok) {// a data-free page's copy is the anonymous one made at install, never the live renderif (r.value.ok && kept(url.pathname) && !cfg.dataFree.includes(url.pathname)) { keep(url.pathname + url.search, r.value.clone()) }return r.value}let hit = globalThis.caches.match(url.pathname + url.search, { cacheName = cfg.cache })if (hit != null) { return marked(hit) }// A PAGE OF A KEPT COMPONENT THAT WAS NEVER LOADED AS A DOCUMENT (#124): any kept document// of the same component stands in — the page boots it with this url's parameterslet like = standIn(url.pathname)if (like != null) { return marked(like) }// THE APP'S OWN FALLBACK (#120): a data-free page, kept once, instead of the bare noticeif (cfg.fallback != null) {let fb = globalThis.caches.match(cfg.fallback, { cacheName = cfg.cache })if (fb != null) { return fb }}return unavailable(url.pathname)}// A DOCUMENT FROM THE CACHE SAYS SO (#342). It is as old as its visit, so the page must catch up when its// first socket opens: `"cached":true` goes first into the seed, and the client's first hello asks as a// reconnect does (`again`), which the server answers with the #143 resync. A document the network// rendered is never marked, so it never resyncs. The stored copy stays as it was.marked(res) {R = globalThis.ResponseH = globalThis.Headerstag = 'id="hl-seed">{'text = res.text()h = new H(res.headers)h.delete('content-length')h.delete('content-encoding')let out = textif (text.includes(tag) && !text.includes(tag + '}')) { out = text.replace(tag, tag + '"cached":true,') }return new R(out, { status = res.status statusText = res.statusText headers = h })}// a kept document of the route's own component: this route's first, else another route'sstandIn(path) {let m = router.match(path)if (m == null || m.route.keep != true) { return null }let cache = globalThis.caches.open(cfg.cache)let other = nullfor (req of cache.keys()) {let o = router.match(new URL(req.url).pathname)if (o != null && o.route.keep == true && o.route.page == m.route.page) {if (o.index == m.index) { return cache.match(req) }if (other == null) { other = req }}}return other != null ? cache.match(other) : null}keep(key, res) {let cache = globalThis.caches.open(cfg.cache)cache.put(key, res)return null}// CACHE-FIRST for the shell. A miss still asks the network, so a worker installed// before an asset existed is not a permanent failure.cacheFirst(req, key) {let hit = globalThis.caches.match(key, { cacheName = cfg.cache })if (hit != null) { return hit }let r = globalThis.__hlAttempt(() => { return fetch(req) })if (r.ok) {if (r.value.ok) { keep(key, r.value.clone()) }return r.value}let R = globalThis.Responsereturn new R('', { status = 503 statusText = 'Offline' })}// A MESSAGE FROM A PAGE. `keep`: a page the browser reached by a client-side// navigation was never a document request, so the client asks for it to be kept —// fetched here as the document it would be, if it is a page the allow-list names.message(data) {if (data != null && data.t == 'forget') { return forget(data.path) }if (data == null || data.t != 'keep' || !kept(data.path) || cfg.dataFree.includes(data.path)) { return null }let r = globalThis.__hlAttempt(() => { return fetch(data.path, { credentials = 'same-origin' headers = { 'Accept' = 'text/html' } }) })if (r.ok && r.value.ok) { keep(data.path, r.value) }return null}// THE USER CHANGED (#125): every kept document is another user's, so they all go; the// page that stands is fetched again as the new session sees itforget(path) {let cache = globalThis.caches.open(cfg.cache)for (req of cache.keys()) {let u = new URL(req.url)if (kept(u.pathname) && !cfg.dataFree.includes(u.pathname)) { cache.delete(req) }}if (path != null && kept(path) && !cfg.dataFree.includes(path)) {let r = globalThis.__hlAttempt(() => { return fetch(path, { credentials = 'same-origin' headers = { 'Accept' = 'text/html' } }) })if (r.ok && r.value.ok) { keep(path, r.value) }}return null}// A NOTIFICATION WAS CLICKED: the app's open window is focused, or one is opened at// the path the notification carriesclicked(n) {n.close()let path = n.data != null && n.data.path != null ? n.data.path : '/'for (c of globalThis.clients.matchAll({ type = 'window' includeUncontrolled = true })) {if (c.focus != null) { return c.focus() }}return globalThis.clients.openWindow(path)}// A PUSH ARRIVED (#173): the payload is JSON text — `{ title, body, url, tag }` — and is shown as a// notification by this worker, whether or not any page is open. `url` is where a click goes (the// path rides in the notification's data, `clicked` reads it); a payload that is not JSON is// shown as the body of a notification titled with the page's origin host.pushed(text) {let r = globalThis.__hlAttempt(() => { return JSON.parse(text) })let p = r.ok && r.value != null && (r.value.title != null || r.value.body != null) ? r.value : { body = text; }let title = p.title != null ? p.title : globalThis.location.hostlet opts = { data = { path = p.url != null ? p.url : '/' }; }if (p.body != null) { opts.body = p.body }if (p.tag != null) { opts.tag = p.tag }if (p.icon != null) { opts.icon = p.icon }return globalThis.registration.showNotification(title, opts)}// A page this app does not carry offline. A DOCUMENT, so the tab shows something and// no navigation fails inside the browser; 503, so a probe can tell it from a page.unavailable(path) {let esc = path.replaceAll('&', '&').replaceAll('<', '<')let body = '<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Offline</title><link rel="stylesheet" href="' + cfg.css + '"></head><body><main data-hl-offline="1"><h1>Unavailable offline</h1><p><code>' + esc + '</code> is not one of the pages this app carries offline.</p><p><a href="/">Back to the start</a></p></main></body></html>'let R = globalThis.Responsereturn new R(body, { status = 503 headers = { 'Content-Type' = 'text/html; charset=utf-8' } })}
Branches
- hl-standard
- hl-standard-2
- mainmain branch
- notes-pr7-kunibert
- notes13-day61
- notes17-ghost-note
- notes9-no-poll
- vendor-day56
- vendor-day59
- w7
Latest commits
- ae1075b2Preserve rejected drafts during note ID adoptionAtlas
- 383cce23|||PR Prevent saved local edits from restoring deleted notesAtlas
- 99ca1cf6Merge branch 'vendor-day56' into mainAtlas
- 649cef37|||PR Vendor Hybriel day56Atlas
- aadd0abcMerge branch 'hl-standard-2' into mainAtlas
- 52ffac9f|||PR Keyboard and reload checks for the notes gate (HL-STANDARD F21, F5)Atlas
- 617ee8c0Merge branch 'hl-standard' into mainAtlas
- 452458ee|||PR Type the function parameters of notes' own .hl files (HL-STANDARD L10)Atlas
- 23758cd6Re-vendor complete Hybriel plugins and runtime to day44mre
- 5d7cc700Backup tar: --hard-dereference, so mpackdb sidecars are never stored as hard links (Tracker's finding)mre
- 3e07b1cfVendor complete Hybriel day39 plugin sources and librariesmre
- d7366702Check session cookie flags after login and assert anonymous GET stays cookielessmre
- 16bc8fd8Re-vendor Hybriel day38b with the mpackdb store-open race fixmre
- d860dc2dnotes#12: the markup names its own rules instead of hand-written class strings: the selected row is `aria-current="page"` (the list-first theme rule styles it, no class), the delete question is `Style.pAsk` and follows its own `open` attribute (bound to `asking`), the error line is `Style.pMessage` (body once in lib/looks.hl, rule in notes.hl, main.hl and loginfailed.hl). The CSS declarations are the same, only selectors changed (.ask -> p.ask, .ask.open -> p.ask[open], .message -> p.message); the pages look the same (AE 0 at 4 sizes). main.hl's selectorClass in/out stays (login.js reads it).mre
- 2e7f8664notes#13: the list and back links pass the note key from the loop (emit pick(e, r.key)) instead of writing data-note into the View and reading it back with getAttribute; the two window.history.replaceState calls and the identcode e.target.value read stay (hl:web has no replace-navigation, a bound hidden input is not adopted on a script's change event), see NO13 reportmre
- 4dc98282notes#15: a deleted note made in this tab leaves the list at once (the delete now removes this tab's edit under every key the row has: local id, server id); gate: browser.mjs notes#15 section, red on the old codemre
- e4e7402fnotes#11: plain declarations instead of let for variables never reassigned (components/notes.hl 3, lib/jsoncheck.hl 5, lib/util.hl 2, tools/migrate-short-ids.hl 8)mre
- 27b6a09enotes#8: Style blocks in the nested form (note-list, note-editor, .ask with their children nested, :empty as a nested pseudo-class); the same CSS rules, the pages look the samemre
- 71a9538bnotes: B27W report, log linemre
- 78ba0073notes: an ident access key (Authorization: Bearer idt_…) reads and writes its identity's notes through /api/me and /api/notes; gate tests/ident-access-notes.mjs (ident#27)mre