gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit71a746cf71a746cflog: day48 livemre71a746cf/plugins/web/worker.hl

8.9 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. navigation(req, url) {
  72. let r = globalThis.__hlAttempt(() => { return fetch(req) })
  73. if (r.ok) {
  74. // a data-free page's copy is the anonymous one made at install, never the live render
  75. if (r.value.ok && kept(url.pathname) && !cfg.dataFree.includes(url.pathname)) { keep(url.pathname + url.search, r.value.clone()) }
  76. return r.value
  77. }
  78. let hit = globalThis.caches.match(url.pathname + url.search, { cacheName = cfg.cache })
  79. if (hit != null) { return hit }
  80. // A PAGE OF A KEPT COMPONENT THAT WAS NEVER LOADED AS A DOCUMENT (#124): any kept document
  81. // of the same component stands in — the page boots it with this url's parameters
  82. let like = standIn(url.pathname)
  83. if (like != null) { return like }
  84. // THE APP'S OWN FALLBACK (#120): a data-free page, kept once, instead of the bare notice
  85. if (cfg.fallback != null) {
  86. let fb = globalThis.caches.match(cfg.fallback, { cacheName = cfg.cache })
  87. if (fb != null) { return fb }
  88. }
  89. return unavailable(url.pathname)
  90. }
  91. // a kept document of the route's own component: this route's first, else another route's
  92. standIn(path) {
  93. let m = router.match(path)
  94. if (m == null || m.route.keep != true) { return null }
  95. let cache = globalThis.caches.open(cfg.cache)
  96. let other = null
  97. for (req of cache.keys()) {
  98. let o = router.match(new URL(req.url).pathname)
  99. if (o != null && o.route.keep == true && o.route.page == m.route.page) {
  100. if (o.index == m.index) { return cache.match(req) }
  101. if (other == null) { other = req }
  102. }
  103. }
  104. return other != null ? cache.match(other) : null
  105. }
  106. keep(key, res) {
  107. let cache = globalThis.caches.open(cfg.cache)
  108. cache.put(key, res)
  109. return null
  110. }
  111. // CACHE-FIRST for the shell. A miss still asks the network, so a worker installed
  112. // before an asset existed is not a permanent failure.
  113. cacheFirst(req, key) {
  114. let hit = globalThis.caches.match(key, { cacheName = cfg.cache })
  115. if (hit != null) { return hit }
  116. let r = globalThis.__hlAttempt(() => { return fetch(req) })
  117. if (r.ok) {
  118. if (r.value.ok) { keep(key, r.value.clone()) }
  119. return r.value
  120. }
  121. let R = globalThis.Response
  122. return new R('', { status = 503 statusText = 'Offline' })
  123. }
  124. // A MESSAGE FROM A PAGE. `keep`: a page the browser reached by a client-side
  125. // navigation was never a document request, so the client asks for it to be kept —
  126. // fetched here as the document it would be, if it is a page the allow-list names.
  127. message(data) {
  128. if (data != null && data.t == 'forget') { return forget(data.path) }
  129. if (data == null || data.t != 'keep' || !kept(data.path) || cfg.dataFree.includes(data.path)) { return null }
  130. let r = globalThis.__hlAttempt(() => { return fetch(data.path, { credentials = 'same-origin' headers = { 'Accept' = 'text/html' } }) })
  131. if (r.ok && r.value.ok) { keep(data.path, r.value) }
  132. return null
  133. }
  134. // THE USER CHANGED (#125): every kept document is another user's, so they all go; the
  135. // page that stands is fetched again as the new session sees it
  136. forget(path) {
  137. let cache = globalThis.caches.open(cfg.cache)
  138. for (req of cache.keys()) {
  139. let u = new URL(req.url)
  140. if (kept(u.pathname) && !cfg.dataFree.includes(u.pathname)) { cache.delete(req) }
  141. }
  142. if (path != null && kept(path) && !cfg.dataFree.includes(path)) {
  143. let r = globalThis.__hlAttempt(() => { return fetch(path, { credentials = 'same-origin' headers = { 'Accept' = 'text/html' } }) })
  144. if (r.ok && r.value.ok) { keep(path, r.value) }
  145. }
  146. return null
  147. }
  148. // A NOTIFICATION WAS CLICKED: the app's open window is focused, or one is opened at
  149. // the path the notification carries
  150. clicked(n) {
  151. n.close()
  152. let path = n.data != null && n.data.path != null ? n.data.path : '/'
  153. for (c of globalThis.clients.matchAll({ type = 'window' includeUncontrolled = true })) {
  154. if (c.focus != null) { return c.focus() }
  155. }
  156. return globalThis.clients.openWindow(path)
  157. }
  158. // A PUSH ARRIVED (#173): the payload is JSON text — `{ title, body, url, tag }` — and is shown as a
  159. // notification by this worker, whether or not any page is open. `url` is where a click goes (the
  160. // path rides in the notification's data, `clicked` reads it); a payload that is not JSON is
  161. // shown as the body of a notification titled with the page's origin host.
  162. pushed(text) {
  163. let r = globalThis.__hlAttempt(() => { return JSON.parse(text) })
  164. let p = r.ok && r.value != null && (r.value.title != null || r.value.body != null) ? r.value : { body = text; }
  165. let title = p.title != null ? p.title : globalThis.location.host
  166. let opts = { data = { path = p.url != null ? p.url : '/' }; }
  167. if (p.body != null) { opts.body = p.body }
  168. if (p.tag != null) { opts.tag = p.tag }
  169. if (p.icon != null) { opts.icon = p.icon }
  170. return globalThis.registration.showNotification(title, opts)
  171. }
  172. // A page this app does not carry offline. A DOCUMENT, so the tab shows something and
  173. // no navigation fails inside the browser; 503, so a probe can tell it from a page.
  174. unavailable(path) {
  175. let esc = path.replaceAll('&', '&amp;').replaceAll('<', '&lt;')
  176. 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>'
  177. let R = globalThis.Response
  178. return new R(body, { status = 503 headers = { 'Content-Type' = 'text/html; charset=utf-8' } })
  179. }

Branches

Latest commits

  • 71a746cflog: day48 livemre
  • bf568e14log: V48 mergedmre
  • 09955dedMerge v48: Hybriel set-day48, theme layouts ce4a0bamre
  • f2a2b0cevendor: Hybriel set-day48, theme layouts ce4a0bamre
  • 5d0834e7log: Apollo model rulemre
  • fe8e5bd5log: #25 sample, V48 missionmre
  • 8580c5d9log: theme fix from Atlasmre
  • 46823d93log: Apollo budget correctionmre
  • f6d32341log: Apollo on budget and #25 nextmre
  • d7184f53log: batch live, #25 evidencemre
  • 5e25e816log: W61 mergedmre
  • aafe330dTidy: drop evidence JSON (kept in scratch), collapse blank linesmre
  • aca1fda1Merge W61: theme from layouts 17e0f03, Views refer to Style rules (gitoria#37 #27)mre
  • 03cb650blog: W61 theme decisionmre
  • 248bce85Report final style gates, CSS mappings and 136 whole-image comparisonsmre
  • 153c344bRestore organization metadata exposed by the whole-image comparisonmre
  • 917a1465Update status gate assertions for the referenced state rulemre
  • 3cdb02c6Own settings feedback styles and explain connection-state classesmre
  • 00d5d6c4Reference code-entry styles and nest code-browser media and pseudosmre
  • 3c425eddReference PR content styles and explain dynamic state classesmre