@oxy.so/app-preset 6.7.0 → 6.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -100,19 +100,41 @@ The app keeps its own `public/manifest.json` and icons. The step:
100
100
  app has no `public/sw.js`. An app with its own worker (web push) keeps it and
101
101
  opts in with `importScripts('/oxy-sw-base.js');` as its first line; until it
102
102
  does, the step warns. A worker that already answers `fetch` (Inbosh, Nilo)
103
- must not import it. `--no-sw` ships no worker.
103
+ must not import it. `--no-sw` ships no worker; `--remove-sw` retires one
104
+ shipped before (see Cleanup below).
105
+
106
+ `theme-color` comes from the manifest's `theme_color`, one tag. An app whose
107
+ startup colour is a light/dark pair (Bloom adopts one and owns it at runtime)
108
+ passes it instead: `oxy-web-pwa dist --theme-color=#f9f2f6,#100d11` (hex or a
109
+ colour name; a page that already has a `theme-color` keeps it).
104
110
 
105
111
  The base worker (`web/oxy-sw-base.js`, from Inbosh's) answers navigations
106
112
  network-first with the one `/index.html` shell as the offline fallback, and
107
113
  same-origin static files (`/_expo/`, `/assets/`, images, fonts, JS, CSS)
108
114
  stale-while-revalidate. It never stores or serves anything else: cross-origin
109
- requests (every Oxy API), non-GET, `/api/`, requests carrying `Authorization`,
110
- `credentials: 'include'` or `Range`, and `private`/`no-store` responses. Its
111
- cache name is a hash of the export, so each deploy installs a new worker and
112
- drops the old cache; the cache holds at most 150 entries.
113
-
114
- Serve `/sw.js` with `Cache-Control: no-cache` (`public/_headers`). `@oxy.so/doctor`
115
- 1.10.0+ warns (`web-not-installable`) about a web export without this step.
115
+ requests (every Oxy API), non-GET, `/api/`, requests carrying `Authorization`
116
+ or `Range`, and `private`/`no-store` responses.
117
+
118
+ **Updates.** `oxy-web-pwa` stamps `/oxy-sw-base.js` with a hash of the export,
119
+ so every deploy changes its bytes and the browser installs the new worker, which
120
+ takes over at once. The registration uses `updateViaCache: 'none'`, and a page
121
+ that returns to the foreground checks for an update at most once an hour (an
122
+ installed app can stay open for days without a navigation). App code is never
123
+ stale: navigations are network-first, so the next load runs the new deploy.
124
+
125
+ **Cleanup.** One cache, `oxy-sw-v1`, holds at most 150 entries, oldest dropped
126
+ first and the shell never. It is not renamed per deploy: hashed chunks never
127
+ collide, so a tab opened before a deploy can still lazy-load the chunks the
128
+ server has already dropped. `activate` deletes every other `oxy-sw-*` cache, so
129
+ bumping the name in the base worker clears old entries everywhere on the next
130
+ deploy. To take the worker away, build with `--remove-sw`: it ships a `/sw.js`
131
+ that deletes the Oxy caches and unregisters itself (shipping no `/sw.js` would
132
+ leave the old worker running, since a failed update check keeps it).
133
+
134
+ Serve `/sw.js` and `/oxy-sw-base.js` with `Cache-Control: no-cache` or
135
+ `max-age=0, must-revalidate` (Cloudflare's default for unhashed assets).
136
+ `@oxy.so/doctor` 1.10.0+ warns (`web-not-installable`) about a web export
137
+ without this step.
116
138
 
117
139
  ## Usage
118
140
 
@@ -5,14 +5,17 @@
5
5
  *
6
6
  * expo export --platform web --output-dir dist && oxy-web-pwa dist
7
7
  *
8
- * oxy-web-pwa [dist] [--no-sw]
8
+ * oxy-web-pwa [dist] [--no-sw | --remove-sw] [--theme-color=<light>,<dark>]
9
9
  *
10
10
  * `dist` defaults to `dist`. The step checks the exported manifest
11
11
  * (public/manifest.json) against what browsers need to offer installation,
12
12
  * adds the manifest link, theme colour, Apple tags and the worker registration
13
13
  * to every exported page that lacks them, and ships the Oxy base service
14
14
  * worker (`/oxy-sw-base.js`, plus `/sw.js` when the app has none).
15
- * `--no-sw` skips the worker.
15
+ * `--no-sw` skips the worker. `--remove-sw` ships a `/sw.js` that retires a
16
+ * worker shipped before (deletes its caches and unregisters it). `--theme-color=<light>,<dark>` writes the
17
+ * startup `theme-color` as a light/dark pair (the one Bloom adopts at runtime)
18
+ * instead of the manifest's single `theme_color`.
16
19
  *
17
20
  * Exits 0 when the export is installable, 1 when it is not, 2 on bad usage.
18
21
  * See README "Installable web apps".
@@ -20,15 +23,23 @@
20
23
  const { resolve } = require('node:path');
21
24
  const { PwaError, makeInstallable } = require('../web/pwa');
22
25
 
23
- const usage = 'oxy-web-pwa [dist] [--no-sw]';
26
+ const usage = 'oxy-web-pwa [dist] [--no-sw | --remove-sw] [--theme-color=<light>,<dark>]';
24
27
  const args = process.argv.slice(2);
25
28
  let dist = 'dist';
26
29
  let serviceWorker = true;
30
+ let removeServiceWorker = false;
31
+ let themeColors;
27
32
  for (const arg of args) {
28
33
  if (arg === '--help' || arg === '-h') {
29
34
  console.log(usage);
30
35
  process.exit(0);
31
36
  } else if (arg === '--no-sw') serviceWorker = false;
37
+ else if (arg === '--remove-sw') removeServiceWorker = true;
38
+ else if (arg.startsWith('--theme-color='))
39
+ themeColors = arg
40
+ .slice('--theme-color='.length)
41
+ .split(',')
42
+ .map((color) => color.trim());
32
43
  else if (arg.startsWith('-')) {
33
44
  console.error(`Unknown option ${arg}\n${usage}`);
34
45
  process.exit(2);
@@ -36,7 +47,11 @@ for (const arg of args) {
36
47
  }
37
48
 
38
49
  try {
39
- const result = makeInstallable(resolve(dist), { serviceWorker });
50
+ const result = makeInstallable(resolve(dist), {
51
+ serviceWorker,
52
+ removeServiceWorker,
53
+ themeColors,
54
+ });
40
55
  for (const warning of result.warnings) console.warn(`oxy-web-pwa: warning: ${warning}`);
41
56
  console.log(
42
57
  `oxy-web-pwa: ${result.manifest} is installable; ${result.updated.length} of ${result.pages} pages updated` +
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oxy.so/app-preset",
3
- "version": "6.7.0",
3
+ "version": "6.7.2",
4
4
  "description": "The Oxy distro of Expo — centralized Expo config plugin, Metro/Babel/ESLint factories, Tailwind base CSS and TypeScript bases shared by every Oxy app (Mention, Homiio, Allo, accounts, …). A zero-build package: apps replace copy-pasted config with a single dependency bump.",
5
5
  "main": "./app.plugin.js",
6
6
  "publishConfig": {
@@ -18,14 +18,27 @@
18
18
  * page that is still running it.
19
19
  * - Everything else is left to the browser, never stored and never served
20
20
  * from here: cross-origin requests (every Oxy API), non-GET, `/api/`, any
21
- * request carrying credentials, range requests and `no-store` responses.
21
+ * request carrying `Authorization`, range requests, and `private` or
22
+ * `no-store` responses. (`credentials` is no test: every navigation is
23
+ * `include`, and a same-origin request sends cookies either way.)
22
24
  * Private responses must never be cached by URL: Inbosh once served one
23
25
  * signed-in user's API response to the next.
24
26
  *
25
- * `__OXY_SW_VERSION__` is replaced by `oxy-web-pwa` with a hash of the export,
26
- * so the bytes change on every deploy and the browser installs the new worker
27
- * (imported scripts are compared byte for byte too). The cache is bounded and
28
- * old caches are dropped on `activate`.
27
+ * Updates. `__OXY_SW_VERSION__` is replaced by `oxy-web-pwa` with a hash of
28
+ * the export, so this file's bytes change on every deploy; the browser compares
29
+ * imported scripts byte for byte, so it installs the new worker, which takes
30
+ * over at once (`skipWaiting`, `clients.claim`). App code is never stale: a
31
+ * navigation is network-first, so the next load or reload runs the new deploy,
32
+ * and a page still running the old one keeps loading its own chunks.
33
+ *
34
+ * Cleanup. The cache name is fixed (`oxy-sw-v1`), not per deploy: hashed
35
+ * chunks never collide, so one cache holds both deploys and a tab opened
36
+ * before a deploy can still lazy-load the chunks it was built with (the server
37
+ * no longer has them). It holds at most 150 entries, oldest dropped first, the
38
+ * shell never. `activate` deletes every other `oxy-sw-*` cache, so bumping the
39
+ * name here (when a strategy changes what a cached entry means) clears old
40
+ * entries everywhere on the next deploy. `oxy-web-pwa --remove-sw` retires the
41
+ * worker and its caches entirely.
29
42
  */
30
43
  (() => {
31
44
  if (self.__oxySwBase) return;
@@ -33,7 +46,8 @@
33
46
 
34
47
  const VERSION = '__OXY_SW_VERSION__';
35
48
  const CACHE_PREFIX = 'oxy-sw-';
36
- const CACHE_NAME = `${CACHE_PREFIX}${VERSION}`;
49
+ const CACHE_NAME = `${CACHE_PREFIX}v1`;
50
+ self.__oxySwVersion = VERSION;
37
51
  const SHELL_KEY = '/index.html';
38
52
  const MAX_ENTRIES = 150;
39
53
  const STATIC_FILE = /\.(?:js|mjs|css|woff2?|ttf|otf|png|jpe?g|gif|svg|ico|webp|avif|wasm)$/i;
@@ -78,7 +92,6 @@
78
92
  if (url.origin !== self.location.origin) return null;
79
93
  if (url.pathname.startsWith('/api/')) return null;
80
94
  if (request.headers.has('authorization') || request.headers.has('range')) return null;
81
- if (request.credentials === 'include') return null;
82
95
  if (request.mode === 'navigate') return 'navigation';
83
96
  if (
84
97
  url.pathname.startsWith('/_expo/') ||
@@ -148,5 +161,5 @@
148
161
  else if (strategy === 'static') event.respondWith(staleWhileRevalidate(event));
149
162
  });
150
163
 
151
- self.__oxySwBaseInternals = { strategyFor, cacheable, CACHE_NAME, SHELL_KEY, MAX_ENTRIES };
164
+ self.__oxySwBaseInternals = { strategyFor, cacheable, trim, CACHE_NAME, SHELL_KEY, MAX_ENTRIES };
152
165
  })();
@@ -8,11 +8,27 @@
8
8
  * after `load` has often fired, and a `load` listener added then never runs,
9
9
  * so the page's state is checked first. Failure is silent: the app works
10
10
  * without a worker.
11
+ *
12
+ * Updates: `updateViaCache: 'none'` makes every update check fetch `/sw.js` and
13
+ * `/oxy-sw-base.js` past the HTTP cache. The browser checks on each navigation,
14
+ * but an installed app can stay open for days without one, so a page that
15
+ * comes back to the foreground checks too, at most once an hour.
11
16
  */
12
17
  (() => {
13
18
  if (!('serviceWorker' in navigator) || !window.isSecureContext) return;
19
+ const HOUR = 60 * 60 * 1000;
20
+ let checked = Date.now();
14
21
  const register = () => {
15
- navigator.serviceWorker.register('/sw.js').catch(() => {});
22
+ navigator.serviceWorker
23
+ .register('/sw.js', { updateViaCache: 'none' })
24
+ .then((registration) => {
25
+ document.addEventListener('visibilitychange', () => {
26
+ if (document.visibilityState !== 'visible' || Date.now() - checked < HOUR) return;
27
+ checked = Date.now();
28
+ registration.update().catch(() => {});
29
+ });
30
+ })
31
+ .catch(() => {});
16
32
  };
17
33
  if (document.readyState === 'complete') register();
18
34
  else window.addEventListener('load', register, { once: true });
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Written as `/sw.js` by `oxy-web-pwa --remove-sw`: retires this origin's
3
+ * worker. The browser installs it on the next update check (it differs from the
4
+ * worker it replaces), and on `activate` it deletes the Oxy caches and
5
+ * unregisters itself. It answers no `fetch`, so open pages go to the network
6
+ * at once (nothing reloads under the user) and the next load has no worker.
7
+ * Shipping no `/sw.js` at all would not do this: a failed update check leaves
8
+ * the old worker running.
9
+ */
10
+ self.addEventListener('install', () => self.skipWaiting());
11
+ self.addEventListener('activate', (event) => {
12
+ event.waitUntil(
13
+ (async () => {
14
+ for (const key of await caches.keys())
15
+ if (key.startsWith('oxy-sw-')) await caches.delete(key);
16
+ await self.registration.unregister();
17
+ })(),
18
+ );
19
+ });
package/web/pwa.js CHANGED
@@ -27,6 +27,7 @@ const REQUIRED_ICON_SIZES = ['192x192', '512x512'];
27
27
  const SKIPPED_DIRS = new Set(['_expo', 'assets', 'node_modules']);
28
28
  const SW_BASE = 'oxy-sw-base.js';
29
29
  const SW_REGISTER = 'oxy-sw-register.js';
30
+ const SW_REMOVE = 'oxy-sw-remove.js';
30
31
  const WEB_DIR = __dirname;
31
32
 
32
33
  class PwaError extends Error {}
@@ -124,8 +125,10 @@ function missingTags(document, wanted) {
124
125
  if (tag.kind === 'script' && scripts.has(tag.src)) continue;
125
126
  if (tag.kind === 'link')
126
127
  out.push(`<link rel="${tag.rel}" href="${escapeAttribute(tag.href)}" />`);
127
- if (tag.kind === 'meta')
128
- out.push(`<meta name="${tag.name}" content="${escapeAttribute(tag.content)}" />`);
128
+ if (tag.kind === 'meta') {
129
+ const media = tag.media ? ` media="${escapeAttribute(tag.media)}"` : '';
130
+ out.push(`<meta name="${tag.name}" content="${escapeAttribute(tag.content)}"${media} />`);
131
+ }
129
132
  if (tag.kind === 'script')
130
133
  out.push(`<script src="${escapeAttribute(tag.src)}" defer></script>`);
131
134
  }
@@ -147,12 +150,36 @@ function injectHead(html, wanted) {
147
150
  return `${html.slice(0, end)}${block}${html.slice(end)}`;
148
151
  }
149
152
 
150
- function wantedTags(manifestName, manifest, dist, { serviceWorker }) {
153
+ /**
154
+ * The startup `theme-color` tags: `--theme-color=<light>,<dark>` gives a pair
155
+ * scoped by `prefers-color-scheme` (what Bloom adopts and then owns at
156
+ * runtime); one colour, or none (the manifest's `theme_color`), gives one tag.
157
+ */
158
+ function themeColorTags(manifest, themeColors) {
159
+ const colors = themeColors?.length ? themeColors : [manifest.theme_color].filter(Boolean);
160
+ if (colors.length === 2)
161
+ return [
162
+ {
163
+ kind: 'meta',
164
+ name: 'theme-color',
165
+ content: colors[0],
166
+ media: '(prefers-color-scheme: light)',
167
+ },
168
+ {
169
+ kind: 'meta',
170
+ name: 'theme-color',
171
+ content: colors[1],
172
+ media: '(prefers-color-scheme: dark)',
173
+ },
174
+ ];
175
+ return colors.map((content) => ({ kind: 'meta', name: 'theme-color', content }));
176
+ }
177
+
178
+ function wantedTags(manifestName, manifest, dist, { serviceWorker, themeColors }) {
151
179
  const wanted = [{ kind: 'link', rel: 'manifest', href: `/${manifestName}` }];
152
180
  if (existsSync(join(dist, 'apple-touch-icon.png')))
153
181
  wanted.push({ kind: 'link', rel: 'apple-touch-icon', href: '/apple-touch-icon.png' });
154
- if (manifest.theme_color)
155
- wanted.push({ kind: 'meta', name: 'theme-color', content: manifest.theme_color });
182
+ wanted.push(...themeColorTags(manifest, themeColors));
156
183
  wanted.push({ kind: 'meta', name: 'mobile-web-app-capable', content: 'yes' });
157
184
  wanted.push({ kind: 'meta', name: 'apple-mobile-web-app-capable', content: 'yes' });
158
185
  const title = manifest.short_name || manifest.name;
@@ -177,7 +204,26 @@ importScripts('/${SW_BASE}');
177
204
  * Runs the whole step on `dist`. Throws PwaError on anything that leaves the
178
205
  * app uninstallable; returns what it did and any warnings.
179
206
  */
180
- function makeInstallable(dist, { serviceWorker = true } = {}) {
207
+ function makeInstallable(
208
+ dist,
209
+ { serviceWorker = true, removeServiceWorker = false, themeColors } = {},
210
+ ) {
211
+ if (removeServiceWorker && !serviceWorker)
212
+ throw new PwaError(
213
+ '--remove-sw and --no-sw cannot be combined; --remove-sw ships no worker either',
214
+ );
215
+ if (removeServiceWorker) serviceWorker = false;
216
+ if (themeColors !== undefined) {
217
+ const valid = /^(?:#[0-9a-f]{3,8}|[a-z]+|(?:rgb|hsl)a?\([^"<>]*\))$/i;
218
+ if (
219
+ themeColors.length < 1 ||
220
+ themeColors.length > 2 ||
221
+ !themeColors.every((c) => valid.test(c))
222
+ )
223
+ throw new PwaError(
224
+ `--theme-color takes one colour or <light>,<dark>; got ${JSON.stringify(themeColors.join(','))}`,
225
+ );
226
+ }
181
227
  if (!existsSync(dist) || !statSync(dist).isDirectory())
182
228
  throw new PwaError(`${dist} is not a directory; run expo export first`);
183
229
  const manifestName = findManifest(dist);
@@ -197,7 +243,7 @@ function makeInstallable(dist, { serviceWorker = true } = {}) {
197
243
 
198
244
  const pages = htmlFiles(dist);
199
245
  if (pages.length === 0) throw new PwaError(`${dist} has no HTML page`);
200
- const wanted = wantedTags(manifestName, manifest, dist, { serviceWorker });
246
+ const wanted = wantedTags(manifestName, manifest, dist, { serviceWorker, themeColors });
201
247
  const updated = [];
202
248
  for (const page of pages) {
203
249
  let next;
@@ -213,7 +259,14 @@ function makeInstallable(dist, { serviceWorker = true } = {}) {
213
259
  }
214
260
 
215
261
  let worker = null;
216
- if (serviceWorker) {
262
+ if (removeServiceWorker) {
263
+ if (existsSync(join(dist, 'sw.js')))
264
+ throw new PwaError(
265
+ '--remove-sw replaces /sw.js, but the app ships its own public/sw.js; drop its importScripts line instead',
266
+ );
267
+ writeFileSync(join(dist, 'sw.js'), readFileSync(join(WEB_DIR, SW_REMOVE)));
268
+ worker = 'removal (retires the worker and its caches)';
269
+ } else if (serviceWorker) {
217
270
  const version = exportVersion(pages);
218
271
  const base = readFileSync(join(WEB_DIR, SW_BASE), 'utf8').replace(
219
272
  /__OXY_SW_VERSION__/g,
@@ -244,4 +297,5 @@ module.exports = {
244
297
  wantedTags,
245
298
  SW_BASE,
246
299
  SW_REGISTER,
300
+ SW_REMOVE,
247
301
  };