gitoria

notes

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit383cce23383cce23|||PR Prevent saved local edits from restoring deleted notesAtlas383cce23/plugins/web/worker.hl

10.6 KB

  1. // The framework's SERVICE WORKER (COMPONENTS §10, D38) — the offline shell. It exists
  2. // only for an app that declares `offline = [ … ]`: hl:web compiles this file like
  3. // client.hl, serves it at /__hl/web/worker.js, and registers the entry script
  4. // /__hl/sw.js, which imports it and constructs it ONCE with the table below.
  5. //
  6. // WHAT IS KEPT IS THE APP'S DECISION (D38). `precache` holds the shared shell —
  7. // the runtime, the client half, the stylesheet, every page module, the web app
  8. // manifest and its icons — plus the DOCUMENT of each param-free route whose
  9. // component the allow-list names. `routes` is the client's route table with
  10. // `keep` on the rows the allow-list names, so a param-bearing page (`/notes/:id`)
  11. // is kept when it is VISITED, and only then. Every other page is unavailable
  12. // offline, and says so.
  13. //
  14. // THREE RULES, the ones the old hl:web ran (mission 101):
  15. // · a NAVIGATION is network-first. The network is the truth while it answers,
  16. // and a fresh document for a kept page replaces the cached one on the way past;
  17. // the cache is what an outage falls back to.
  18. // · a precached asset is cache-first. Its url carries the build's hash, so a hit
  19. // cannot be stale.
  20. // · everything else goes to the network untouched: the emit channel, a function
  21. // route, an app's own file. The socket never reaches a worker at all.
  22. //
  23. // WHY THE ENTRY SCRIPT IS NOT THIS FILE. A worker must add its listeners while its
  24. // script is first evaluated, and a `fetch` listener must hand `respondWith` its
  25. // promise before the listener returns. Every call in this language is awaited, so
  26. // neither can be written here; /__hl/sw.js does exactly those two things and calls
  27. // the methods below for everything else (WebFramework.hl, `workerEntry`).
  28. import HlwRouter from './router.hl'
  29. cfgText = '' // the table, as JSON text (the one construction argument)
  30. cfg = JSON.parse(cfgText)
  31. router = new HlwRouter(routes = cfg.routes)
  32. // INSTALL: the shell into this build's cache, one url at a time — a single failed
  33. // url must not throw the whole install away and leave the app with no shell
  34. install() {
  35. let cache = globalThis.caches.open(cfg.cache)
  36. for (url of cfg.precache) {
  37. // a data-free page is fetched as nobody: its document carries no user's state (#120)
  38. let creds = cfg.dataFree.includes(url) ? 'omit' : 'same-origin'
  39. let r = globalThis.__hlAttempt(() => { return fetch(url, { cache = 'reload' credentials = creds }) })
  40. if (r.ok && r.value.ok) { cache.put(url, r.value) }
  41. }
  42. globalThis.skipWaiting()
  43. return null
  44. }
  45. // ACTIVATE: the cache name carries the build's hash, so every other hl cache is an
  46. // older deploy's. This worker then controls the pages that are already open.
  47. activate() {
  48. for (name of globalThis.caches.keys()) {
  49. if (name != cfg.cache && name.startsWith('hl-shell-')) { globalThis.caches.delete(name) }
  50. }
  51. globalThis.clients.claim()
  52. return null
  53. }
  54. // FETCH: what answers this request. Never null — the entry script hands the answer to
  55. // `respondWith` unread.
  56. answer(req) {
  57. if (cfg.shell == false) { return fetch(req) }
  58. if (req.method != 'GET') { return fetch(req) }
  59. let url = new URL(req.url)
  60. if (url.origin != globalThis.location.origin) { return fetch(req) }
  61. if (req.mode == 'navigate') { return navigation(req, url) }
  62. if (cfg.precache.includes(url.pathname + url.search)) { return cacheFirst(req, url.pathname + url.search) }
  63. return fetch(req)
  64. }
  65. // may the document at this path be kept? Only if the route that answers it is a page
  66. // the allow-list names — the whole of D38 in one predicate
  67. kept(path) {
  68. let m = router.match(path)
  69. return m != null && m.route.keep == true
  70. }
  71. // HOW LONG A NAVIGATION WAITS FOR THE NETWORK when a kept copy of the page exists (#340), in ms.
  72. // A silent connection (no answer, no refusal) would otherwise show nothing at all. After this the
  73. // copy is served and the fetch goes on in the background; if it succeeds it refreshes the copy
  74. // (the page already shown stays). A page with no copy, or not kept, waits for the network.
  75. navWait = 1500
  76. navigation(req, url) {
  77. path = url.pathname + url.search
  78. let copy = null
  79. if (kept(url.pathname)) {
  80. copy = globalThis.caches.match(path, { cacheName = cfg.cache })
  81. if (copy == null) { copy = standIn(url.pathname) }
  82. }
  83. let r = null
  84. if (copy != null) {
  85. r = globalThis.__hlWithin(() => { return fetch(req) }, navWait, (late) => {
  86. if (late.ok && late.value.ok && !cfg.dataFree.includes(url.pathname)) { keep(path, late.value.clone()) }
  87. return null
  88. })
  89. if (r.late == true) { return marked(copy) }
  90. } else {
  91. r = globalThis.__hlAttempt(() => { return fetch(req) })
  92. }
  93. if (r.ok) {
  94. // a data-free page's copy is the anonymous one made at install, never the live render
  95. if (r.value.ok && kept(url.pathname) && !cfg.dataFree.includes(url.pathname)) { keep(url.pathname + url.search, r.value.clone()) }
  96. return r.value
  97. }
  98. let hit = globalThis.caches.match(url.pathname + url.search, { cacheName = cfg.cache })
  99. if (hit != null) { return marked(hit) }
  100. // A PAGE OF A KEPT COMPONENT THAT WAS NEVER LOADED AS A DOCUMENT (#124): any kept document
  101. // of the same component stands in — the page boots it with this url's parameters
  102. let like = standIn(url.pathname)
  103. if (like != null) { return marked(like) }
  104. // THE APP'S OWN FALLBACK (#120): a data-free page, kept once, instead of the bare notice
  105. if (cfg.fallback != null) {
  106. let fb = globalThis.caches.match(cfg.fallback, { cacheName = cfg.cache })
  107. if (fb != null) { return fb }
  108. }
  109. return unavailable(url.pathname)
  110. }
  111. // A DOCUMENT FROM THE CACHE SAYS SO (#342). It is as old as its visit, so the page must catch up when its
  112. // first socket opens: `"cached":true` goes first into the seed, and the client's first hello asks as a
  113. // reconnect does (`again`), which the server answers with the #143 resync. A document the network
  114. // rendered is never marked, so it never resyncs. The stored copy stays as it was.
  115. marked(res) {
  116. R = globalThis.Response
  117. H = globalThis.Headers
  118. tag = 'id="hl-seed">{'
  119. text = res.text()
  120. h = new H(res.headers)
  121. h.delete('content-length')
  122. h.delete('content-encoding')
  123. let out = text
  124. if (text.includes(tag) && !text.includes(tag + '}')) { out = text.replace(tag, tag + '"cached":true,') }
  125. return new R(out, { status = res.status statusText = res.statusText headers = h })
  126. }
  127. // a kept document of the route's own component: this route's first, else another route's
  128. standIn(path) {
  129. let m = router.match(path)
  130. if (m == null || m.route.keep != true) { return null }
  131. let cache = globalThis.caches.open(cfg.cache)
  132. let other = null
  133. for (req of cache.keys()) {
  134. let o = router.match(new URL(req.url).pathname)
  135. if (o != null && o.route.keep == true && o.route.page == m.route.page) {
  136. if (o.index == m.index) { return cache.match(req) }
  137. if (other == null) { other = req }
  138. }
  139. }
  140. return other != null ? cache.match(other) : null
  141. }
  142. keep(key, res) {
  143. let cache = globalThis.caches.open(cfg.cache)
  144. cache.put(key, res)
  145. return null
  146. }
  147. // CACHE-FIRST for the shell. A miss still asks the network, so a worker installed
  148. // before an asset existed is not a permanent failure.
  149. cacheFirst(req, key) {
  150. let hit = globalThis.caches.match(key, { cacheName = cfg.cache })
  151. if (hit != null) { return hit }
  152. let r = globalThis.__hlAttempt(() => { return fetch(req) })
  153. if (r.ok) {
  154. if (r.value.ok) { keep(key, r.value.clone()) }
  155. return r.value
  156. }
  157. let R = globalThis.Response
  158. return new R('', { status = 503 statusText = 'Offline' })
  159. }
  160. // A MESSAGE FROM A PAGE. `keep`: a page the browser reached by a client-side
  161. // navigation was never a document request, so the client asks for it to be kept —
  162. // fetched here as the document it would be, if it is a page the allow-list names.
  163. message(data) {
  164. if (data != null && data.t == 'forget') { return forget(data.path) }
  165. if (data == null || data.t != 'keep' || !kept(data.path) || cfg.dataFree.includes(data.path)) { return null }
  166. let r = globalThis.__hlAttempt(() => { return fetch(data.path, { credentials = 'same-origin' headers = { 'Accept' = 'text/html' } }) })
  167. if (r.ok && r.value.ok) { keep(data.path, r.value) }
  168. return null
  169. }
  170. // THE USER CHANGED (#125): every kept document is another user's, so they all go; the
  171. // page that stands is fetched again as the new session sees it
  172. forget(path) {
  173. let cache = globalThis.caches.open(cfg.cache)
  174. for (req of cache.keys()) {
  175. let u = new URL(req.url)
  176. if (kept(u.pathname) && !cfg.dataFree.includes(u.pathname)) { cache.delete(req) }
  177. }
  178. if (path != null && kept(path) && !cfg.dataFree.includes(path)) {
  179. let r = globalThis.__hlAttempt(() => { return fetch(path, { credentials = 'same-origin' headers = { 'Accept' = 'text/html' } }) })
  180. if (r.ok && r.value.ok) { keep(path, r.value) }
  181. }
  182. return null
  183. }
  184. // A NOTIFICATION WAS CLICKED: the app's open window is focused, or one is opened at
  185. // the path the notification carries
  186. clicked(n) {
  187. n.close()
  188. let path = n.data != null && n.data.path != null ? n.data.path : '/'
  189. for (c of globalThis.clients.matchAll({ type = 'window' includeUncontrolled = true })) {
  190. if (c.focus != null) { return c.focus() }
  191. }
  192. return globalThis.clients.openWindow(path)
  193. }
  194. // A PUSH ARRIVED (#173): the payload is JSON text — `{ title, body, url, tag }` — and is shown as a
  195. // notification by this worker, whether or not any page is open. `url` is where a click goes (the
  196. // path rides in the notification's data, `clicked` reads it); a payload that is not JSON is
  197. // shown as the body of a notification titled with the page's origin host.
  198. pushed(text) {
  199. let r = globalThis.__hlAttempt(() => { return JSON.parse(text) })
  200. let p = r.ok && r.value != null && (r.value.title != null || r.value.body != null) ? r.value : { body = text; }
  201. let title = p.title != null ? p.title : globalThis.location.host
  202. let opts = { data = { path = p.url != null ? p.url : '/' }; }
  203. if (p.body != null) { opts.body = p.body }
  204. if (p.tag != null) { opts.tag = p.tag }
  205. if (p.icon != null) { opts.icon = p.icon }
  206. return globalThis.registration.showNotification(title, opts)
  207. }
  208. // A page this app does not carry offline. A DOCUMENT, so the tab shows something and
  209. // no navigation fails inside the browser; 503, so a probe can tell it from a page.
  210. unavailable(path) {
  211. let esc = path.replaceAll('&', '&amp;').replaceAll('<', '&lt;')
  212. 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>'
  213. let R = globalThis.Response
  214. return new R(body, { status = 503 headers = { 'Content-Type' = 'text/html; charset=utf-8' } })
  215. }

Branches

Latest commits

  • 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
  • 3de46dacnotes: the sign-in callback keeps the session it finds and signs it in (same cookie, nothing signed out; ident#28); security gate 73+5 failing → 78 passedmre