@oxy.so/app-preset 6.6.0 → 6.7.1

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
@@ -22,6 +22,7 @@ and JSON.
22
22
  | ESLint | `@oxy.so/app-preset/eslint` | `eslint-config-expo/flat` + `dist/*` ignore |
23
23
  | CSS base | `@oxy.so/app-preset/base.css` | Tailwind v4 + NativeWind + Bloom design-token imports + SDK `@source` globs |
24
24
  | tsconfig | `@oxy.so/app-preset/tsconfig/{base,frontend,backend}.json` | the shared strict/composite TypeScript bases |
25
+ | Installable web | `oxy-web-pwa dist` (bin) | a hand-written manifest link per app (lost under `output: 'single'`), its install checks and a copied service worker |
25
26
 
26
27
  ## Static web hydration on Expo 58
27
28
 
@@ -69,6 +70,55 @@ screenshots must show real chrome, and hydration must retain the same workspace
69
70
  DOM node without recoverable React errors. The package tests exercise real
70
71
  `prerender` and `hydrateRoot`; publication runs those gates too.
71
72
 
73
+ ## Installable web apps
74
+
75
+ With `web.output: 'single'` Expo exports its default SPA page and **ignores
76
+ `app/+html.tsx`**, so a `<link rel="manifest">` written there never reaches the
77
+ browser and the site cannot be installed: alia.onl served a valid manifest and
78
+ worker that no page linked. Run `oxy-web-pwa` on the export instead; it works
79
+ on the exported HTML, so `single` and `static` output are the same:
80
+
81
+ ```json
82
+ "build": "expo export --platform web --output-dir dist && oxy-web-pwa dist"
83
+ ```
84
+
85
+ The app keeps its own `public/manifest.json` and icons. The step:
86
+
87
+ - **fails the build** (exit 1) when the exported manifest is missing or a
88
+ browser would refuse it: no `name`/`short_name`, no `start_url`, a `display`
89
+ other than `standalone`/`fullscreen`/`minimal-ui`, no 192x192 or 512x512
90
+ icon, an icon the export does not contain, or `prefer_related_applications`.
91
+ A missing `maskable` icon, `theme_color` or `background_color` is a warning;
92
+ - adds to every exported page (`_expo/` and `assets/` excepted) whichever of
93
+ these it lacks, never touching one that is there: the manifest link,
94
+ `apple-touch-icon` (when `public/apple-touch-icon.png` exists), `theme-color`
95
+ (from the manifest), `mobile-web-app-capable`, `apple-mobile-web-app-capable`,
96
+ `apple-mobile-web-app-title`, and `<script src="/oxy-sw-register.js" defer>`
97
+ (a file, not inline, so no CSP needs an exception). Running it twice changes
98
+ nothing;
99
+ - ships the Oxy base service worker as `/oxy-sw-base.js`, and `/sw.js` when the
100
+ app has no `public/sw.js`. An app with its own worker (web push) keeps it and
101
+ opts in with `importScripts('/oxy-sw-base.js');` as its first line; until it
102
+ does, the step warns. A worker that already answers `fetch` (Inbosh, Nilo)
103
+ must not import it. `--no-sw` ships no worker.
104
+
105
+ `theme-color` comes from the manifest's `theme_color`, one tag. An app whose
106
+ startup colour is a light/dark pair (Bloom adopts one and owns it at runtime)
107
+ passes it instead: `oxy-web-pwa dist --theme-color=#f9f2f6,#100d11` (hex or a
108
+ colour name; a page that already has a `theme-color` keeps it).
109
+
110
+ The base worker (`web/oxy-sw-base.js`, from Inbosh's) answers navigations
111
+ network-first with the one `/index.html` shell as the offline fallback, and
112
+ same-origin static files (`/_expo/`, `/assets/`, images, fonts, JS, CSS)
113
+ stale-while-revalidate. It never stores or serves anything else: cross-origin
114
+ requests (every Oxy API), non-GET, `/api/`, requests carrying `Authorization`
115
+ or `Range`, and `private`/`no-store` responses. Its
116
+ cache name is a hash of the export, so each deploy installs a new worker and
117
+ drops the old cache; the cache holds at most 150 entries.
118
+
119
+ Serve `/sw.js` with `Cache-Control: no-cache` (`public/_headers`). `@oxy.so/doctor`
120
+ 1.10.0+ warns (`web-not-installable`) about a web export without this step.
121
+
72
122
  ## Usage
73
123
 
74
124
  ### 1. Config plugin (`app.config.js` / `app.json`)
@@ -514,6 +564,6 @@ the web host; native scroll remains owned by the native Screen/ScrollView.
514
564
 
515
565
  Configure this in the stylesheet, not only in a custom `+html.tsx`: Expo's
516
566
  `web.output="single"` export uses its default HTML and does not render that custom
517
- document. Static output must keep its script/style `headNodes` and `bodyNodes`.
567
+ document (the same trap that left apps uninstallable; see "Installable web apps"). Static output must keep its script/style `headNodes` and `bodyNodes`.
518
568
  The generated scaffold defaults to a bounded host. Changing the host permission
519
569
  is separate from choosing the scroll owner for each route.
@@ -0,0 +1,59 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * oxy-web-pwa: makes an Expo web export installable. Run it right after
4
+ * `expo export --platform web`, in the app's `build` script:
5
+ *
6
+ * expo export --platform web --output-dir dist && oxy-web-pwa dist
7
+ *
8
+ * oxy-web-pwa [dist] [--no-sw] [--theme-color=<light>,<dark>]
9
+ *
10
+ * `dist` defaults to `dist`. The step checks the exported manifest
11
+ * (public/manifest.json) against what browsers need to offer installation,
12
+ * adds the manifest link, theme colour, Apple tags and the worker registration
13
+ * to every exported page that lacks them, and ships the Oxy base service
14
+ * worker (`/oxy-sw-base.js`, plus `/sw.js` when the app has none).
15
+ * `--no-sw` skips the worker. `--theme-color=<light>,<dark>` writes the
16
+ * startup `theme-color` as a light/dark pair (the one Bloom adopts at runtime)
17
+ * instead of the manifest's single `theme_color`.
18
+ *
19
+ * Exits 0 when the export is installable, 1 when it is not, 2 on bad usage.
20
+ * See README "Installable web apps".
21
+ */
22
+ const { resolve } = require('node:path');
23
+ const { PwaError, makeInstallable } = require('../web/pwa');
24
+
25
+ const usage = 'oxy-web-pwa [dist] [--no-sw] [--theme-color=<light>,<dark>]';
26
+ const args = process.argv.slice(2);
27
+ let dist = 'dist';
28
+ let serviceWorker = true;
29
+ let themeColors;
30
+ for (const arg of args) {
31
+ if (arg === '--help' || arg === '-h') {
32
+ console.log(usage);
33
+ process.exit(0);
34
+ } else if (arg === '--no-sw') serviceWorker = false;
35
+ else if (arg.startsWith('--theme-color='))
36
+ themeColors = arg
37
+ .slice('--theme-color='.length)
38
+ .split(',')
39
+ .map((color) => color.trim());
40
+ else if (arg.startsWith('-')) {
41
+ console.error(`Unknown option ${arg}\n${usage}`);
42
+ process.exit(2);
43
+ } else dist = arg;
44
+ }
45
+
46
+ try {
47
+ const result = makeInstallable(resolve(dist), { serviceWorker, themeColors });
48
+ for (const warning of result.warnings) console.warn(`oxy-web-pwa: warning: ${warning}`);
49
+ console.log(
50
+ `oxy-web-pwa: ${result.manifest} is installable; ${result.updated.length} of ${result.pages} pages updated` +
51
+ (result.worker ? `; service worker: ${result.worker}` : '; no service worker'),
52
+ );
53
+ } catch (error) {
54
+ if (error instanceof PwaError) {
55
+ console.error(`oxy-web-pwa: ${error.message}`);
56
+ process.exit(1);
57
+ }
58
+ throw error;
59
+ }
package/package.json CHANGED
@@ -1,13 +1,14 @@
1
1
  {
2
2
  "name": "@oxy.so/app-preset",
3
- "version": "6.6.0",
3
+ "version": "6.7.1",
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": {
7
7
  "access": "public"
8
8
  },
9
9
  "bin": {
10
- "oxy-check-keychain-entitlements": "./bin/oxy-check-keychain-entitlements.js"
10
+ "oxy-check-keychain-entitlements": "./bin/oxy-check-keychain-entitlements.js",
11
+ "oxy-web-pwa": "./bin/oxy-web-pwa.js"
11
12
  },
12
13
  "exports": {
13
14
  ".": "./app.plugin.js",
@@ -16,6 +17,7 @@
16
17
  "./plugin/withOxyKeychain": "./plugin/withOxyKeychain.js",
17
18
  "./plugin/oxyKeychainGroups": "./plugin/oxyKeychainGroups.js",
18
19
  "./check-entitlements": "./bin/oxy-check-keychain-entitlements.js",
20
+ "./web-pwa": "./web/pwa.js",
19
21
  "./plugin/withOxyBuildProperties": "./plugin/withOxyBuildProperties.js",
20
22
  "./plugin/withOxyAndroidRelease": "./plugin/withOxyAndroidRelease.js",
21
23
  "./plugin/withOxyAndroidWebp": "./plugin/withOxyAndroidWebp.js",
@@ -41,6 +43,7 @@
41
43
  "build-id",
42
44
  "eslint",
43
45
  "certs",
46
+ "web",
44
47
  "css",
45
48
  "tsconfig",
46
49
  "README.md"
@@ -0,0 +1,153 @@
1
+ /**
2
+ * The Oxy base service worker: an offline app shell and a cache of this
3
+ * origin's public, content-hashed files, and nothing else.
4
+ *
5
+ * `oxy-web-pwa` copies this file into every Oxy web export as
6
+ * `/oxy-sw-base.js` and, when the app has no `public/sw.js`, writes a `/sw.js`
7
+ * that only imports it. An app with its own worker (web push) opts in with
8
+ * `importScripts('/oxy-sw-base.js');` as its first line. An app whose worker
9
+ * already answers `fetch` must not import it: the first `respondWith` wins.
10
+ *
11
+ * Strategies (ported from Inbosh's worker, which paid for each rule):
12
+ *
13
+ * - Navigation: network-first, so a deploy is visible on the next load. The
14
+ * one SPA shell is stored once under `/index.html` and served offline.
15
+ * - Same-origin static files (`/_expo/`, `/assets/`, images, fonts, JS, CSS):
16
+ * stale-while-revalidate. Metro hashes these names, so an entry is never
17
+ * stale in content, and chunks of the previous deploy stay loadable for a
18
+ * page that is still running it.
19
+ * - Everything else is left to the browser, never stored and never served
20
+ * from here: cross-origin requests (every Oxy API), non-GET, `/api/`, any
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.)
24
+ * Private responses must never be cached by URL: Inbosh once served one
25
+ * signed-in user's API response to the next.
26
+ *
27
+ * `__OXY_SW_VERSION__` is replaced by `oxy-web-pwa` with a hash of the export,
28
+ * so the bytes change on every deploy and the browser installs the new worker
29
+ * (imported scripts are compared byte for byte too). The cache is bounded and
30
+ * old caches are dropped on `activate`.
31
+ */
32
+ (() => {
33
+ if (self.__oxySwBase) return;
34
+ self.__oxySwBase = true;
35
+
36
+ const VERSION = '__OXY_SW_VERSION__';
37
+ const CACHE_PREFIX = 'oxy-sw-';
38
+ const CACHE_NAME = `${CACHE_PREFIX}${VERSION}`;
39
+ const SHELL_KEY = '/index.html';
40
+ const MAX_ENTRIES = 150;
41
+ const STATIC_FILE = /\.(?:js|mjs|css|woff2?|ttf|otf|png|jpe?g|gif|svg|ico|webp|avif|wasm)$/i;
42
+
43
+ const offline = () => new Response('Offline', { status: 503, statusText: 'Service Unavailable' });
44
+
45
+ self.addEventListener('install', (event) => {
46
+ event.waitUntil(
47
+ caches
48
+ .open(CACHE_NAME)
49
+ .then((cache) => cache.add(new Request(SHELL_KEY, { cache: 'reload' })))
50
+ .catch(() => {
51
+ // Non-fatal: the shell is stored on the first navigation instead.
52
+ }),
53
+ );
54
+ self.skipWaiting();
55
+ });
56
+
57
+ self.addEventListener('activate', (event) => {
58
+ event.waitUntil(
59
+ caches
60
+ .keys()
61
+ .then((keys) =>
62
+ Promise.all(
63
+ keys
64
+ .filter((key) => key.startsWith(CACHE_PREFIX) && key !== CACHE_NAME)
65
+ .map((key) => caches.delete(key)),
66
+ ),
67
+ )
68
+ .then(() => self.clients.claim()),
69
+ );
70
+ });
71
+
72
+ self.addEventListener('message', (event) => {
73
+ if (event.data && event.data.type === 'SKIP_WAITING') self.skipWaiting();
74
+ });
75
+
76
+ /** `'navigation'`, `'static'`, or `null` for a request this worker leaves alone. */
77
+ function strategyFor(request) {
78
+ if (request.method !== 'GET') return null;
79
+ const url = new URL(request.url);
80
+ if (url.origin !== self.location.origin) return null;
81
+ if (url.pathname.startsWith('/api/')) return null;
82
+ if (request.headers.has('authorization') || request.headers.has('range')) return null;
83
+ if (request.mode === 'navigate') return 'navigation';
84
+ if (
85
+ url.pathname.startsWith('/_expo/') ||
86
+ url.pathname.startsWith('/assets/') ||
87
+ STATIC_FILE.test(url.pathname)
88
+ )
89
+ return 'static';
90
+ return null;
91
+ }
92
+
93
+ /** Only a complete, same-origin, storable response is ever cached. */
94
+ function cacheable(response) {
95
+ if (!response?.ok || response.status !== 200 || response.type !== 'basic') return false;
96
+ const control = response.headers.get('cache-control') || '';
97
+ return !/no-store|private/i.test(control);
98
+ }
99
+
100
+ async function trim(cache) {
101
+ const keys = await cache.keys();
102
+ const excess = keys.length - MAX_ENTRIES;
103
+ for (let i = 0, dropped = 0; i < keys.length && dropped < excess; i++) {
104
+ if (new URL(keys[i].url).pathname === SHELL_KEY) continue;
105
+ await cache.delete(keys[i]);
106
+ dropped++;
107
+ }
108
+ }
109
+
110
+ async function navigation(request) {
111
+ try {
112
+ const response = await fetch(request);
113
+ if (
114
+ cacheable(response) &&
115
+ (response.headers.get('content-type') || '').includes('text/html')
116
+ ) {
117
+ const cache = await caches.open(CACHE_NAME);
118
+ await cache.put(SHELL_KEY, response.clone());
119
+ }
120
+ return response;
121
+ } catch {
122
+ const cache = await caches.open(CACHE_NAME);
123
+ return (await cache.match(SHELL_KEY)) || offline();
124
+ }
125
+ }
126
+
127
+ async function staleWhileRevalidate(event) {
128
+ const cache = await caches.open(CACHE_NAME);
129
+ const cached = await cache.match(event.request);
130
+ const network = fetch(event.request)
131
+ .then(async (response) => {
132
+ if (cacheable(response)) {
133
+ await cache.put(event.request, response.clone());
134
+ await trim(cache);
135
+ }
136
+ return response;
137
+ })
138
+ .catch(() => null);
139
+ if (cached) {
140
+ event.waitUntil(network);
141
+ return cached;
142
+ }
143
+ return (await network) || offline();
144
+ }
145
+
146
+ self.addEventListener('fetch', (event) => {
147
+ const strategy = strategyFor(event.request);
148
+ if (strategy === 'navigation') event.respondWith(navigation(event.request));
149
+ else if (strategy === 'static') event.respondWith(staleWhileRevalidate(event));
150
+ });
151
+
152
+ self.__oxySwBaseInternals = { strategyFor, cacheable, CACHE_NAME, SHELL_KEY, MAX_ENTRIES };
153
+ })();
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Registers the app's `/sw.js`. `oxy-web-pwa` copies this file into the web
3
+ * export and links it from every HTML page with `defer`, as a file and not an
4
+ * inline script so an app's CSP needs no exception.
5
+ *
6
+ * Registering a URL that is already registered is a no-op, so this coexists
7
+ * with an app that registers `/sw.js` itself (web push setup). An app hydrates
8
+ * after `load` has often fired, and a `load` listener added then never runs,
9
+ * so the page's state is checked first. Failure is silent: the app works
10
+ * without a worker.
11
+ */
12
+ (() => {
13
+ if (!('serviceWorker' in navigator) || !window.isSecureContext) return;
14
+ const register = () => {
15
+ navigator.serviceWorker.register('/sw.js').catch(() => {});
16
+ };
17
+ if (document.readyState === 'complete') register();
18
+ else window.addEventListener('load', register, { once: true });
19
+ })();
package/web/pwa.js ADDED
@@ -0,0 +1,284 @@
1
+ /**
2
+ * Makes an Expo web export installable: the work behind `oxy-web-pwa`.
3
+ *
4
+ * Why it exists: with `web.output: 'single'` Expo ignores `app/+html.tsx` and
5
+ * serves its default SPA template, so a `<link rel="manifest">` written there
6
+ * never reaches the browser and the app cannot be installed (alia.onl served a
7
+ * valid manifest and worker that no page linked). This step works on the
8
+ * exported HTML itself, so it is the same for `single` and `static` output.
9
+ *
10
+ * It validates the manifest against what browsers require to install, adds the
11
+ * missing head tags to every exported page (never touching one that is already
12
+ * there), and ships the Oxy base service worker.
13
+ */
14
+ const { createHash } = require('node:crypto');
15
+ const { existsSync, readFileSync, readdirSync, statSync, writeFileSync } = require('node:fs');
16
+ const { join, relative } = require('node:path');
17
+ const { parse } = require('parse5');
18
+
19
+ const MANIFEST_NAMES = ['manifest.json', 'manifest.webmanifest', 'site.webmanifest'];
20
+ const INSTALLABLE_DISPLAYS = new Set([
21
+ 'standalone',
22
+ 'fullscreen',
23
+ 'minimal-ui',
24
+ 'window-controls-overlay',
25
+ ]);
26
+ const REQUIRED_ICON_SIZES = ['192x192', '512x512'];
27
+ const SKIPPED_DIRS = new Set(['_expo', 'assets', 'node_modules']);
28
+ const SW_BASE = 'oxy-sw-base.js';
29
+ const SW_REGISTER = 'oxy-sw-register.js';
30
+ const WEB_DIR = __dirname;
31
+
32
+ class PwaError extends Error {}
33
+
34
+ function findManifest(dist) {
35
+ return MANIFEST_NAMES.find((name) => existsSync(join(dist, name))) ?? null;
36
+ }
37
+
38
+ /** Problems that stop a browser from offering to install the app; warnings do not. */
39
+ function validateManifest(manifest, dist) {
40
+ const errors = [];
41
+ const warnings = [];
42
+ if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) {
43
+ return { errors: ['the manifest is not a JSON object'], warnings };
44
+ }
45
+ if (!manifest.name && !manifest.short_name) errors.push('it has neither "name" nor "short_name"');
46
+ if (!manifest.start_url) errors.push('it has no "start_url"');
47
+ if (!INSTALLABLE_DISPLAYS.has(manifest.display))
48
+ errors.push(
49
+ `"display" is ${JSON.stringify(manifest.display)}; it must be one of ${[...INSTALLABLE_DISPLAYS].join(', ')}`,
50
+ );
51
+ if (manifest.prefer_related_applications === true)
52
+ errors.push(
53
+ '"prefer_related_applications" is true, which tells browsers not to offer the web app',
54
+ );
55
+
56
+ const icons = Array.isArray(manifest.icons) ? manifest.icons : [];
57
+ const sizes = new Set(icons.flatMap((icon) => String(icon.sizes ?? '').split(/\s+/)));
58
+ for (const size of REQUIRED_ICON_SIZES)
59
+ if (!sizes.has(size)) errors.push(`it has no ${size} icon`);
60
+ for (const icon of icons) {
61
+ if (typeof icon.src !== 'string' || !icon.src) {
62
+ errors.push('an icon has no "src"');
63
+ continue;
64
+ }
65
+ if (/^[a-z][a-z0-9+.-]*:/i.test(icon.src) || icon.src.startsWith('//')) continue;
66
+ const file = join(dist, decodeURIComponent(icon.src.split(/[?#]/)[0]).replace(/^\/+/, ''));
67
+ if (!existsSync(file)) errors.push(`icon ${icon.src} is not in the export`);
68
+ }
69
+ if (
70
+ !icons.some((icon) =>
71
+ String(icon.purpose ?? '')
72
+ .split(/\s+/)
73
+ .includes('maskable'),
74
+ )
75
+ )
76
+ warnings.push('it has no "maskable" icon, so Android shows the icon on a white disc');
77
+ if (!manifest.theme_color) warnings.push('it has no "theme_color"');
78
+ if (!manifest.background_color)
79
+ warnings.push('it has no "background_color" for the splash screen');
80
+ return { errors, warnings };
81
+ }
82
+
83
+ function htmlFiles(directory, root = directory) {
84
+ const files = [];
85
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
86
+ const path = join(directory, entry.name);
87
+ if (entry.isDirectory()) {
88
+ if (directory === root && SKIPPED_DIRS.has(entry.name)) continue;
89
+ files.push(...htmlFiles(path, root));
90
+ } else if (entry.isFile() && entry.name.endsWith('.html')) files.push(path);
91
+ }
92
+ return files.sort();
93
+ }
94
+
95
+ function walk(node, visit) {
96
+ visit(node);
97
+ for (const child of node.childNodes ?? []) walk(child, visit);
98
+ if (node.content) walk(node.content, visit);
99
+ }
100
+
101
+ function attrs(node) {
102
+ return Object.fromEntries((node.attrs ?? []).map(({ name, value }) => [name, value]));
103
+ }
104
+
105
+ const escapeAttribute = (value) =>
106
+ String(value).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;');
107
+
108
+ /** The tags `html` is missing, rendered as one string. */
109
+ function missingTags(document, wanted) {
110
+ const rels = new Set();
111
+ const metas = new Set();
112
+ const scripts = new Set();
113
+ walk(document, (node) => {
114
+ const a = attrs(node);
115
+ if (node.tagName === 'link' && a.rel)
116
+ for (const rel of a.rel.toLowerCase().split(/\s+/)) rels.add(rel);
117
+ if (node.tagName === 'meta' && a.name) metas.add(a.name.toLowerCase());
118
+ if (node.tagName === 'script' && a.src) scripts.add(a.src.split(/[?#]/)[0]);
119
+ });
120
+ const out = [];
121
+ for (const tag of wanted) {
122
+ if (tag.kind === 'link' && rels.has(tag.rel)) continue;
123
+ if (tag.kind === 'meta' && metas.has(tag.name)) continue;
124
+ if (tag.kind === 'script' && scripts.has(tag.src)) continue;
125
+ if (tag.kind === 'link')
126
+ out.push(`<link rel="${tag.rel}" href="${escapeAttribute(tag.href)}" />`);
127
+ if (tag.kind === 'meta') {
128
+ const media = tag.media ? ` media="${escapeAttribute(tag.media)}"` : '';
129
+ out.push(`<meta name="${tag.name}" content="${escapeAttribute(tag.content)}"${media} />`);
130
+ }
131
+ if (tag.kind === 'script')
132
+ out.push(`<script src="${escapeAttribute(tag.src)}" defer></script>`);
133
+ }
134
+ return out;
135
+ }
136
+
137
+ /** Adds the missing tags before `</head>`; returns the new HTML, or null when nothing was missing. */
138
+ function injectHead(html, wanted) {
139
+ const document = parse(html, { sourceCodeLocationInfo: true });
140
+ const tags = missingTags(document, wanted);
141
+ if (tags.length === 0) return null;
142
+ let head = null;
143
+ walk(document, (node) => {
144
+ if (!head && node.tagName === 'head') head = node;
145
+ });
146
+ const end = head?.sourceCodeLocation?.endTag?.startOffset;
147
+ if (end === undefined) throw new PwaError('the page has no </head>');
148
+ const block = `<!-- oxy-web-pwa -->${tags.join('')}`;
149
+ return `${html.slice(0, end)}${block}${html.slice(end)}`;
150
+ }
151
+
152
+ /**
153
+ * The startup `theme-color` tags: `--theme-color=<light>,<dark>` gives a pair
154
+ * scoped by `prefers-color-scheme` (what Bloom adopts and then owns at
155
+ * runtime); one colour, or none (the manifest's `theme_color`), gives one tag.
156
+ */
157
+ function themeColorTags(manifest, themeColors) {
158
+ const colors = themeColors?.length ? themeColors : [manifest.theme_color].filter(Boolean);
159
+ if (colors.length === 2)
160
+ return [
161
+ {
162
+ kind: 'meta',
163
+ name: 'theme-color',
164
+ content: colors[0],
165
+ media: '(prefers-color-scheme: light)',
166
+ },
167
+ {
168
+ kind: 'meta',
169
+ name: 'theme-color',
170
+ content: colors[1],
171
+ media: '(prefers-color-scheme: dark)',
172
+ },
173
+ ];
174
+ return colors.map((content) => ({ kind: 'meta', name: 'theme-color', content }));
175
+ }
176
+
177
+ function wantedTags(manifestName, manifest, dist, { serviceWorker, themeColors }) {
178
+ const wanted = [{ kind: 'link', rel: 'manifest', href: `/${manifestName}` }];
179
+ if (existsSync(join(dist, 'apple-touch-icon.png')))
180
+ wanted.push({ kind: 'link', rel: 'apple-touch-icon', href: '/apple-touch-icon.png' });
181
+ wanted.push(...themeColorTags(manifest, themeColors));
182
+ wanted.push({ kind: 'meta', name: 'mobile-web-app-capable', content: 'yes' });
183
+ wanted.push({ kind: 'meta', name: 'apple-mobile-web-app-capable', content: 'yes' });
184
+ const title = manifest.short_name || manifest.name;
185
+ if (title) wanted.push({ kind: 'meta', name: 'apple-mobile-web-app-title', content: title });
186
+ if (serviceWorker) wanted.push({ kind: 'script', src: `/${SW_REGISTER}` });
187
+ return wanted;
188
+ }
189
+
190
+ /** A hash of the export's pages, which name every content-hashed bundle: it changes on each deploy. */
191
+ function exportVersion(pages) {
192
+ const hash = createHash('sha256');
193
+ for (const page of pages) hash.update(readFileSync(page));
194
+ return hash.digest('hex').slice(0, 16);
195
+ }
196
+
197
+ const OWN_WORKER = `// Written by oxy-web-pwa (@oxy.so/app-preset): this app has no public/sw.js,
198
+ // so its worker is the Oxy base worker alone. Add public/sw.js to extend it.
199
+ importScripts('/${SW_BASE}');
200
+ `;
201
+
202
+ /**
203
+ * Runs the whole step on `dist`. Throws PwaError on anything that leaves the
204
+ * app uninstallable; returns what it did and any warnings.
205
+ */
206
+ function makeInstallable(dist, { serviceWorker = true, themeColors } = {}) {
207
+ if (themeColors !== undefined) {
208
+ const valid = /^(?:#[0-9a-f]{3,8}|[a-z]+|(?:rgb|hsl)a?\([^"<>]*\))$/i;
209
+ if (
210
+ themeColors.length < 1 ||
211
+ themeColors.length > 2 ||
212
+ !themeColors.every((c) => valid.test(c))
213
+ )
214
+ throw new PwaError(
215
+ `--theme-color takes one colour or <light>,<dark>; got ${JSON.stringify(themeColors.join(','))}`,
216
+ );
217
+ }
218
+ if (!existsSync(dist) || !statSync(dist).isDirectory())
219
+ throw new PwaError(`${dist} is not a directory; run expo export first`);
220
+ const manifestName = findManifest(dist);
221
+ if (!manifestName)
222
+ throw new PwaError(
223
+ `${dist} has no web app manifest (${MANIFEST_NAMES.join(', ')}); add public/manifest.json`,
224
+ );
225
+ let manifest;
226
+ try {
227
+ manifest = JSON.parse(readFileSync(join(dist, manifestName), 'utf8'));
228
+ } catch (error) {
229
+ throw new PwaError(`${manifestName} is not valid JSON: ${error.message}`);
230
+ }
231
+ const { errors, warnings } = validateManifest(manifest, dist);
232
+ if (errors.length > 0)
233
+ throw new PwaError(`${manifestName} cannot make the app installable: ${errors.join('; ')}`);
234
+
235
+ const pages = htmlFiles(dist);
236
+ if (pages.length === 0) throw new PwaError(`${dist} has no HTML page`);
237
+ const wanted = wantedTags(manifestName, manifest, dist, { serviceWorker, themeColors });
238
+ const updated = [];
239
+ for (const page of pages) {
240
+ let next;
241
+ try {
242
+ next = injectHead(readFileSync(page, 'utf8'), wanted);
243
+ } catch (error) {
244
+ throw new PwaError(`${relative(dist, page)}: ${error.message}`);
245
+ }
246
+ if (next !== null) {
247
+ writeFileSync(page, next);
248
+ updated.push(relative(dist, page));
249
+ }
250
+ }
251
+
252
+ let worker = null;
253
+ if (serviceWorker) {
254
+ const version = exportVersion(pages);
255
+ const base = readFileSync(join(WEB_DIR, SW_BASE), 'utf8').replace(
256
+ /__OXY_SW_VERSION__/g,
257
+ version,
258
+ );
259
+ writeFileSync(join(dist, SW_BASE), base);
260
+ writeFileSync(join(dist, SW_REGISTER), readFileSync(join(WEB_DIR, SW_REGISTER)));
261
+ if (existsSync(join(dist, 'sw.js'))) {
262
+ const own = readFileSync(join(dist, 'sw.js'), 'utf8');
263
+ worker = own.includes(SW_BASE) ? 'app (imports the base)' : 'app (does not import the base)';
264
+ if (!own.includes(SW_BASE))
265
+ warnings.push(
266
+ `sw.js does not import /${SW_BASE}, so it has no offline shell; add importScripts('/${SW_BASE}') unless it caches on its own`,
267
+ );
268
+ } else {
269
+ writeFileSync(join(dist, 'sw.js'), OWN_WORKER);
270
+ worker = 'base';
271
+ }
272
+ }
273
+ return { manifest: manifestName, pages: pages.length, updated, worker, warnings };
274
+ }
275
+
276
+ module.exports = {
277
+ PwaError,
278
+ makeInstallable,
279
+ validateManifest,
280
+ injectHead,
281
+ wantedTags,
282
+ SW_BASE,
283
+ SW_REGISTER,
284
+ };