gitoria

calendar

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitacb957cfacb957cfcalendar#12: Send a test notification on a subscribed device (one push in ~10 s, owner's own device), push gate part 4mreacb957cf/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

  • acb957cfcalendar#12: Send a test notification on a subscribed device (one push in ~10 s, owner's own device), push gate part 4mre
  • 0b222eb8tests: e2e-theme CDP port default from E2E_THEME_CDP_PORT (8756 unchanged)mre
  • 8b8a5abare-vendor Hybriel 6f8a0689 (int 6–11: streaming cursors, #203 index heal + close() fix, fd403 listDir/cursor fds, hl:time browser side, hl:web batches 5+6)mre
  • a69b27f9docker-compose: nofile 65536 (Hybriel int 6+ boot opened >1024 files in the tracker)mre
  • 1a97edfdcalendar mission 010: reminder rows at 390 px (the 7-column month grid no longer catches the reminder lists), gate checks, settings-shots, reportmre
  • 61b21404calendar mission 009: reminder times on hl:time in the browser (lib/push-plan.hl and the Intl code removed), DST gate tests/dst.mjs, E2E script, reportmre
  • 875353c1calendar mission 009: re-vendor Hybriel master 022a3ac1 (int 6 6b396322 hl:time browser side, int 7 65e8ec21; bin sha256 6e0f77d7, plugins whole)mre
  • ce16a4efdeploy: backup copies index files first and *.mpack data last (hot-copy skew, hybriel #203)mre
  • f490bc8cdeploy: Web Push gate tests/push.mjs (PUSH_GATE_PORT)mre
  • 3af29fc8calendar mission 008 (A8): report, README, LOG, push-shots.mjsmre
  • f91f3663calendar mission 008 (A8): push only asked of the browser when the app has the VAPID settings (pushAvailable); real-FCM E2E scripts (push-real-app.mjs, push-real.mjs)mre
  • bf571badcalendar mission 008 (A8): Turn off on this device (unsubscribes the browser, server drops the device, choice kept), subscribe/refresh when the app is shown again; push gate part 3mre
  • 50985708calendar mission 008 (A7): Web Push report, README, mission, LOGmre
  • ee318774calendar mission 008 (A7): push-real.mjs, push sent log linemre
  • ebda0fd1calendar mission 008 (A7): server-side reminder plan on hl:time (push-plan.hl; hl:time fromLocal in a browser static is refused: repro .scratch/hltime-client), push gate 9/9mre
  • d063dad3calendar mission 008 (A7): Web Push (WIP): lib/push.hl subscriptions + sender clock, faces calPushSave/calPushOff, button subscribes, VAPID tool, tests/push.mjs; instantOf on hl:timemre
  • cf175c80calendar mission 008 (A7): re-vendor Hybriel master 0e3c9830 (bin 9d957fed, plugins whole: hl:crypto Web Push primitives, hl:web sendPush)mre
  • 9bf3c38bcalendar mission 008: re-vendor Hybriel f9833544 (gates old = new); Web Push stopped: hl:crypto half missing on mastermre
  • 186f969bcalendar mission 007: signed-in gate for the first-pointer race (fails on 3c5604f), README theme section, reportmre
  • ba9b4955calendar mission 006: first pointer event no longer re-runs the month (stale overwrite race), gate check, e2e settings cleanup, reportmre