gitoria

jukebox

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmain10f8a8c8Merge branch 'code-order' into mainJukeboxmain/plugins/web/worker.hl

13.4 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 = HlwRouter.navigationWait
  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. standby = noticeShell(url.pathname)
  110. if (standby != null) { return standby }
  111. return unavailable(url.pathname)
  112. }
  113. // A KEPT DOCUMENT LENDS ITS SHELL (#350), never its page. The client claims the
  114. // shell against this document, whose page markup is already replaced by the notice.
  115. // It never constructs the donor page or opens the state store. The cached copy stays intact.
  116. noticeShell(String path) {
  117. cache = globalThis.caches.open(cfg.cache)
  118. tag = 'id="hl-seed">'
  119. for (req of cache.keys()) {
  120. if (kept(new URL(req.url).pathname)) {
  121. res = cache.match(req)
  122. text = res.text()
  123. at = text.indexOf(tag)
  124. if (at >= 0) {
  125. start = at + tag.length
  126. end = text.indexOf('</script>', start)
  127. if (end > start) {
  128. seed = JSON.tryParse(text.slice(start, end))
  129. if (seed != null && seed.shell != null && seed.page != null) {
  130. // A path can contain '<'; it must remain JSON inside a script element.
  131. value = JSON.stringify(path).replaceAll('<', '\u003c')
  132. taggedHtml = text.slice(0, start + 1) + '"offlineNotice":' + value + ',' + text.slice(start + 1)
  133. body = noticeDocument(taggedHtml, seed, path)
  134. if (body == null) { continue }
  135. H = globalThis.Headers
  136. R = globalThis.Response
  137. headers = new H(res.headers)
  138. headers.delete('content-length')
  139. headers.delete('content-encoding')
  140. return new R(body, { status = 503 headers = headers })
  141. }
  142. }
  143. }
  144. }
  145. }
  146. return null
  147. }
  148. // The labelled page region is unambiguous even when the shell has its own if/for
  149. // regions or several parent levels. Replace it before sending any HTML to the tab.
  150. noticeDocument(String html, Hybrid seed, String path) {
  151. open = '<!--[hl:page-->'
  152. close = '<!--]hl:page-->'
  153. start = html.indexOf(open)
  154. if (start < 0) { return null }
  155. end = html.indexOf(close, start + open.length)
  156. if (end < 0) { return null }
  157. body = html.slice(0, start + open.length) + noticeMarkup(path) + html.slice(end)
  158. // seed.head holds appHead(), not headOf(): the donor's __title is not used.
  159. title = seed.head != null && seed.head.title != null ? seed.head.title : ''
  160. tag = '<title>' + noticeEscape(title) + '</title>'
  161. titleStart = body.indexOf('<title>')
  162. titleEnd = body.indexOf('</title>', titleStart)
  163. if (titleStart >= 0 && titleEnd >= 0) {
  164. return body.slice(0, titleStart) + tag + body.slice(titleEnd + 8)
  165. }
  166. return body.replace('</head>', tag + '</head>')
  167. }
  168. noticeEscape(String text) {
  169. return text.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
  170. }
  171. // The shell notice keeps the text of the original shell-less response.
  172. noticeMarkup(String path) {
  173. return '<main data-hl-offline="1" role="status"><h1>Unavailable offline</h1><p><code>' + noticeEscape(path) + '</code> is not one of the pages this app carries offline.</p><p><a href="/">Back to the start</a></p></main>'
  174. }
  175. // A DOCUMENT FROM THE CACHE SAYS SO (#342). It is as old as its visit, so the page must catch up when its
  176. // first socket opens: `"cached":true` goes first into the seed, and the client's first hello asks as a
  177. // reconnect does (`again`), which the server answers with the #143 resync. A document the network
  178. // rendered is never marked, so it never resyncs. The stored copy stays as it was.
  179. marked(res) {
  180. R = globalThis.Response
  181. H = globalThis.Headers
  182. tag = 'id="hl-seed">{'
  183. text = res.text()
  184. h = new H(res.headers)
  185. h.delete('content-length')
  186. h.delete('content-encoding')
  187. let out = text
  188. if (text.includes(tag) && !text.includes(tag + '}')) { out = text.replace(tag, tag + '"cached":true,') }
  189. return new R(out, { status = res.status statusText = res.statusText headers = h })
  190. }
  191. // a kept document of the route's own component: this route's first, else another route's
  192. standIn(path) {
  193. let m = router.match(path)
  194. if (m == null || m.route.keep != true) { return null }
  195. let cache = globalThis.caches.open(cfg.cache)
  196. let other = null
  197. for (req of cache.keys()) {
  198. let o = router.match(new URL(req.url).pathname)
  199. if (o != null && o.route.keep == true && o.route.page == m.route.page) {
  200. if (o.index == m.index) { return cache.match(req) }
  201. if (other == null) { other = req }
  202. }
  203. }
  204. return other != null ? cache.match(other) : null
  205. }
  206. keep(key, res) {
  207. let cache = globalThis.caches.open(cfg.cache)
  208. cache.put(key, res)
  209. return null
  210. }
  211. // CACHE-FIRST for the shell. A miss still asks the network, so a worker installed
  212. // before an asset existed is not a permanent failure.
  213. cacheFirst(req, key) {
  214. let hit = globalThis.caches.match(key, { cacheName = cfg.cache })
  215. if (hit != null) { return hit }
  216. let r = globalThis.__hlAttempt(() => { return fetch(req) })
  217. if (r.ok) {
  218. if (r.value.ok) { keep(key, r.value.clone()) }
  219. return r.value
  220. }
  221. let R = globalThis.Response
  222. return new R('', { status = 503 statusText = 'Offline' })
  223. }
  224. // A MESSAGE FROM A PAGE. `keep`: a page the browser reached by a client-side
  225. // navigation was never a document request, so the client asks for it to be kept —
  226. // fetched here as the document it would be, if it is a page the allow-list names.
  227. message(data) {
  228. if (data != null && data.t == 'forget') { return forget(data.path) }
  229. if (data == null || data.t != 'keep' || !kept(data.path) || cfg.dataFree.includes(data.path)) { return null }
  230. let r = globalThis.__hlAttempt(() => { return fetch(data.path, { credentials = 'same-origin' headers = { 'Accept' = 'text/html' } }) })
  231. if (r.ok && r.value.ok) { keep(data.path, r.value) }
  232. return null
  233. }
  234. // THE USER CHANGED (#125): every kept document is another user's, so they all go; the
  235. // page that stands is fetched again as the new session sees it
  236. forget(path) {
  237. let cache = globalThis.caches.open(cfg.cache)
  238. for (req of cache.keys()) {
  239. let u = new URL(req.url)
  240. if (kept(u.pathname) && !cfg.dataFree.includes(u.pathname)) { cache.delete(req) }
  241. }
  242. if (path != null && kept(path) && !cfg.dataFree.includes(path)) {
  243. let r = globalThis.__hlAttempt(() => { return fetch(path, { credentials = 'same-origin' headers = { 'Accept' = 'text/html' } }) })
  244. if (r.ok && r.value.ok) { keep(path, r.value) }
  245. }
  246. return null
  247. }
  248. // A NOTIFICATION WAS CLICKED: the app's open window is focused, or one is opened at
  249. // the path the notification carries
  250. clicked(n) {
  251. n.close()
  252. let path = n.data != null && n.data.path != null ? n.data.path : '/'
  253. for (c of globalThis.clients.matchAll({ type = 'window' includeUncontrolled = true })) {
  254. if (c.focus != null) { return c.focus() }
  255. }
  256. return globalThis.clients.openWindow(path)
  257. }
  258. // A PUSH ARRIVED (#173): the payload is JSON text — `{ title, body, url, tag }` — and is shown as a
  259. // notification by this worker, whether or not any page is open. `url` is where a click goes (the
  260. // path rides in the notification's data, `clicked` reads it); a payload that is not JSON is
  261. // shown as the body of a notification titled with the page's origin host.
  262. pushed(text) {
  263. let r = globalThis.__hlAttempt(() => { return JSON.parse(text) })
  264. let p = r.ok && r.value != null && (r.value.title != null || r.value.body != null) ? r.value : { body = text; }
  265. let title = p.title != null ? p.title : globalThis.location.host
  266. let opts = { data = { path = p.url != null ? p.url : '/' }; }
  267. if (p.body != null) { opts.body = p.body }
  268. if (p.tag != null) { opts.tag = p.tag }
  269. if (p.icon != null) { opts.icon = p.icon }
  270. return globalThis.registration.showNotification(title, opts)
  271. }
  272. // A page this app does not carry offline. A DOCUMENT, so the tab shows something and
  273. // no navigation fails inside the browser; 503, so a probe can tell it from a page.
  274. unavailable(path) {
  275. let esc = path.replaceAll('&', '&amp;').replaceAll('<', '&lt;')
  276. 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>'
  277. let R = globalThis.Response
  278. return new R(body, { status = 503 headers = { 'Content-Type' = 'text/html; charset=utf-8' } })
  279. }

Branches

Latest commits

  • 10f8a8c8Merge branch 'code-order' into mainJukebox
  • 204fc828Merge branch 'day72' into mainJukebox
  • 95f5faae|||PR jukebox#7 Drop needless let declarationsmre
  • 33072bb5|||PR Record day72 gates and Chrome proofmre
  • 95f2cd73|||PR Use typed parent methods for screen playback and local server facesmre
  • 6422a020Sync media-player at 51c3818mre
  • b582ba1cVendor complete Hybriel day72 plugin setmre
  • 02dccbc9Merge branch 'records-1119' into mainJukebox
  • a39e1c23|||PR Records: missions 013-015, reconnect fix livemre
  • fc7db075Merge branch 'reconnect-retry' into mainJukebox
  • ac6f4c6fL2: plain declaration for a in pickedNextmre
  • 2f335086Review round 2: only an explicit queue pick drops pend (not the automatic advance); jb23 records every source changemre
  • 3eb6695fReview fixes: action generation, queue pick clears pend, Previous/Next retry the decided request, typed handlersmre
  • 7a53c0c2|||PR A tap lost to a dead socket plays after reconnect (mission 015)mre
  • 1f0cd77bMerge branch 'records-day41' into mainJukebox
  • 67be229f|||PR Records: day41 live (PR #4), mission 012, statusmre
  • 0bb027daconductor: caramboleyo is the user, not owner/creatorApollo
  • 04f5d9d5Merge branch 'day41' into mainJukebox
  • 8ed6da45|||PR README: media-player pin df9e7dfmre
  • d5d45fc3|||PR media-player df9e7df (repeat-one fix), sync pin and SOURCEmre