Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
Boot on iOS 15.5 to 16.3: no regex lookbehind, Safari 15 build target, bundle syntax guard (P1)
Duarte Santos70a74ee7af2c
diff --git a/frontend/scripts/check-bundle-syntax.mjs b/frontend/scripts/check-bundle-syntax.mjsnew file mode 100644index 000000000..dc5dbddff--- /dev/null+++ b/frontend/scripts/check-bundle-syntax.mjs@@ -0,0 +1,108 @@+#!/usr/bin/env node+/* Can the oldest browser we ship to parse the bundle? The iOS app's deployment target is 15.5,+ * so its WebView is Safari 15.5, and one regex lookbehind (Safari 16.4) in one chunk was enough+ * for 1.4.2 to never get past the splash on iOS 15.5 to 16.3: the chunk fails to parse, the+ * module graph dies, React never mounts.+ *+ * vite.config.js already asks the transpiler for safari15 (build.target), but some syntax it+ * cannot lower (a lookbehind has no rewrite) and some it turns into a `new RegExp(...)` that dies+ * at load instead of at parse. This walks every built chunk and fails on what Safari 15.5 lacks:+ * - regex lookbehind, the v flag, duplicate group names, inline modifiers (literal or RegExp()),+ * - class static blocks, `using` declarations, import attributes,+ * - built-ins newer than 15.5 that a module would call unguarded (Object.groupBy and friends).+ *+ * Usage: node scripts/check-bundle-syntax.mjs [dist dir] (exit code 1 on any problem). */+import { existsSync, readdirSync, readFileSync } from 'node:fs'+import { dirname, join, resolve } from 'node:path'+import { fileURLToPath } from 'node:url'+import { parseAst } from 'vite'++// What a regex pattern uses, read the way the regex engine reads it: escapes skipped, and+// nothing inside a [...] class counts as a group.+export function regexFeatures(pattern, flags = '') {+ const found = []+ if (flags.includes('v')) found.push('regex v flag (Safari 17)')+ const names = new Set()+ let inClass = false+ for (let i = 0; i < pattern.length; i++) {+ const c = pattern[i]+ if (c === '\\') { i++; continue }+ if (inClass) { if (c === ']') inClass = false; continue }+ if (c === '[') { inClass = true; continue }+ if (c !== '(' || pattern[i + 1] !== '?') continue+ const rest = pattern.slice(i + 2)+ if (rest.startsWith('<=') || rest.startsWith('<!')) found.push('regex lookbehind (Safari 16.4)')+ else if (rest.startsWith('<')) {+ const name = /^<([^>]+)>/.exec(rest)?.[1]+ if (name && names.has(name)) found.push('regex duplicate group name (Safari 17)')+ if (name) names.add(name)+ } else if (/^[ims-]+:/.test(rest)) found.push('regex inline modifier (not in Safari 15)')+ }+ return [...new Set(found)]+}++// Built-ins a module could call at load. Safari 15.4 brought at(), findLast(), Object.hasOwn and+// structuredClone, so those are fine; these came later.+const NEWER_STATICS = {+ Object: ['groupBy'], Map: ['groupBy'], Array: ['fromAsync'], Promise: ['withResolvers', 'try'],+ URL: ['canParse', 'parse'], AbortSignal: ['any'],+}+const NEWER_METHODS = ['toSorted', 'toReversed', 'toSpliced', 'isWellFormed', 'toWellFormed']++const isRegExpCtor = n => n?.type === 'Identifier' && n.name === 'RegExp'+const str = n => (n?.type === 'Literal' && typeof n.value === 'string' ? n.value : null)++function walk(node, visit) {+ if (!node || typeof node.type !== 'string') return+ visit(node)+ for (const key in node) {+ const v = node[key]+ if (Array.isArray(v)) { for (const c of v) if (c && typeof c === 'object') walk(c, visit) }+ else if (v && typeof v === 'object' && typeof v.type === 'string') walk(v, visit)+ }+}++/** Every construct in this chunk that Safari 15.5 cannot run, as readable strings. */+export function unsupportedSyntax(code, file = 'chunk.js') {+ let ast+ try { ast = parseAst(code) } catch (e) { return [`${file}: does not parse (${e.message.split('\n')[0]})`] }+ const problems = []+ const at = (n, what) => {+ const line = code.slice(0, n.start).split('\n').length+ const snippet = code.slice(n.start, Math.min(n.end, n.start + 60)).replace(/\s+/g, ' ')+ problems.push(`${file}:${line}: ${what}: ${snippet}`)+ }+ walk(ast, n => {+ if (n.type === 'Literal' && n.regex) for (const f of regexFeatures(n.regex.pattern, n.regex.flags)) at(n, f)+ else if ((n.type === 'NewExpression' || n.type === 'CallExpression') && isRegExpCtor(n.callee)) {+ const pattern = str(n.arguments[0])+ if (pattern !== null) for (const f of regexFeatures(pattern, str(n.arguments[1]) || '')) at(n, f)+ } else if (n.type === 'StaticBlock') at(n, 'class static block (Safari 16.4)')+ else if (n.type === 'VariableDeclaration' && /using/.test(n.kind)) at(n, '`using` declaration')+ else if ((n.type === 'ImportExpression' && n.options) || n.attributes?.length) at(n, 'import attributes (Safari 17.2)')+ else if (n.type === 'MemberExpression' && !n.computed && n.property?.type === 'Identifier') {+ const obj = n.object?.type === 'Identifier' ? n.object.name : null+ if (obj && NEWER_STATICS[obj]?.includes(n.property.name)) at(n, `${obj}.${n.property.name} (newer than Safari 15.5)`)+ else if (NEWER_METHODS.includes(n.property.name)) at(n, `.${n.property.name}() (Safari 16)`)+ }+ })+ return problems+}++export function checkBundle(dist) {+ const assets = join(dist, 'assets')+ if (!existsSync(assets)) return [`${dist}: no assets/ (build first)`]+ return readdirSync(assets).filter(f => f.endsWith('.js'))+ .flatMap(f => unsupportedSyntax(readFileSync(join(assets, f), 'utf8'), `assets/${f}`))+}++if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ const dist = resolve(process.argv[2] || join(dirname(fileURLToPath(import.meta.url)), '..', 'dist'))+ const problems = checkBundle(dist)+ if (problems.length) {+ for (const p of problems) console.error('✗ ' + p)+ console.error(`\n${problems.length} construct(s) Safari 15.5 (the iOS deployment target) cannot run.`)+ process.exit(1)+ }+ console.log(`✓ ${dist}: every chunk runs on Safari 15.5`)+}diff --git a/frontend/scripts/check-bundle-syntax.test.mjs b/frontend/scripts/check-bundle-syntax.test.mjsnew file mode 100644index 000000000..b3a0e9b7e--- /dev/null+++ b/frontend/scripts/check-bundle-syntax.test.mjs@@ -0,0 +1,60 @@+/* check-bundle-syntax.mjs: 1.4.2 never got past the splash on iOS 15.5 to 16.3 because one chunk+ * held a regex lookbehind. The fixtures are what Safari 15.5 cannot run, and the last test builds+ * the real web bundle (a few seconds) and holds every chunk of it to that. */+import { describe, expect, it } from 'vitest'+import { execFileSync } from 'node:child_process'+import { mkdtempSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { dirname, join } from 'node:path'+import { fileURLToPath } from 'node:url'+import { checkBundle, regexFeatures, unsupportedSyntax } from './check-bundle-syntax.mjs'++const frontend = join(dirname(fileURLToPath(import.meta.url)), '..')++describe('regexFeatures', () => {+ it('finds a lookbehind, either kind', () => {+ expect(regexFeatures('^(?!-)[a-z0-9-]{1,63}(?<!-)$')).toEqual(['regex lookbehind (Safari 16.4)'])+ expect(regexFeatures('(?<=\\$)\\d+')).toEqual(['regex lookbehind (Safari 16.4)'])+ })+ it('leaves lookaheads, named groups and escaped or bracketed look-alikes alone', () => {+ for (const p of ['^(?!-)[a-z]+$', '(?=x)', '(?<year>\\d{4})-(?<m>\\d\\d)', '\\(?<=', '[(?<!]', '\\\\[(]?<!'])+ expect(regexFeatures(p), p).toEqual([])+ })+ it('finds the v flag, a group name used twice and inline modifiers', () => {+ expect(regexFeatures('[\\p{L}--a]', 'v')).toEqual(['regex v flag (Safari 17)'])+ expect(regexFeatures('(?<d>a)|(?<d>b)')).toEqual(['regex duplicate group name (Safari 17)'])+ expect(regexFeatures('(?i:abc)')).toEqual(['regex inline modifier (not in Safari 15)'])+ })+})++describe('unsupportedSyntax', () => {+ const kinds = code => unsupportedSyntax(code).map(p => p.split(': ')[1])+ it('flags a lookbehind in a literal and in a RegExp built from a string', () => {+ expect(kinds('const LABEL = /^(?!-)[a-z0-9-]{1,63}(?<!-)$/i')).toEqual(['regex lookbehind (Safari 16.4)'])+ expect(kinds('const r = new RegExp("(?<=a)b", "g"); RegExp("(?<!c)d")')).toEqual(['regex lookbehind (Safari 16.4)', 'regex lookbehind (Safari 16.4)'])+ })+ it('flags class static blocks, import attributes and built-ins newer than 15.5', () => {+ expect(kinds('class A { static { init() } }')).toEqual(['class static block (Safari 16.4)'])+ expect(kinds('import("./x.json", { with: { type: "json" } })')).toEqual(['import attributes (Safari 17.2)'])+ expect(kinds('Object.groupBy(xs, f); xs.toSorted(); Promise.withResolvers()')).toEqual([+ 'Object.groupBy (newer than Safari 15.5)', '.toSorted() (Safari 16)', 'Promise.withResolvers (newer than Safari 15.5)',+ ])+ })+ it('lets through what Safari 15.5 has: at(), Object.hasOwn, structuredClone, ??=, private fields, top-level await', () => {+ expect(kinds('class A { #x = 1; has(o) { return #x in o } }; a ??= [1].at(-1); Object.hasOwn(o, "k"); structuredClone(o); await 0; "(?<!-)"')).toEqual([])+ })+ it('says so when a chunk does not parse at all', () => {+ expect(unsupportedSyntax('const = 1', 'assets/x.js')[0]).toMatch(/^assets\/x\.js: does not parse/)+ })+})++describe('the built web bundle', () => {+ it('has nothing Safari 15.5, the iOS deployment target, cannot run', () => {+ const out = mkdtempSync(join(tmpdir(), 'og-bundle-syntax-'))+ try {+ execFileSync(process.execPath, [join(frontend, 'node_modules/vite/bin/vite.js'), 'build', '--outDir', out, '--emptyOutDir', '--logLevel', 'error'],+ { cwd: frontend, stdio: 'pipe', env: { ...process.env, NODE_ENV: 'production' } })+ expect(checkBundle(out)).toEqual([])+ } finally { rmSync(out, { recursive: true, force: true }) }+ }, 180_000)+})diff --git a/frontend/src/lib/media-refs.js b/frontend/src/lib/media-refs.jsindex 441263b72..0cead6ac4 100644--- a/frontend/src/lib/media-refs.js+++ b/frontend/src/lib/media-refs.js@@ -204,14 +204,18 @@ export function cleanUrl(raw) {return u.href.length <= MAX_URL ? u.href : null}-const LABEL = /^(?!-)[a-z0-9-]{1,63}(?<!-)$/i+// A label neither starts nor ends with a hyphen. The end is checked in code, not with a (?<!-)+// lookbehind: Safari only parses those from 16.4, and on iOS 15.5 to 16.3 that one literal kept+// the whole app on its splash (scripts/check-bundle-syntax.mjs now fails the build on it).+const LABEL = /^(?!-)[a-z0-9-]{1,63}$/i+const plausibleLabel = l => LABEL.test(l) && !l.endsWith('-')function plausibleHost(host) {if (host.startsWith('[') && host.endsWith(']')) return true // IPv6const h = host.replace(/\.$/, '').toLowerCase()if (h === 'localhost') return trueconst labels = h.split('.')// xn-- names are how the parser writes an international domain, so they pass as letters.- return labels.length >= 2 && labels.every(l => LABEL.test(l))+ return labels.length >= 2 && labels.every(plausibleLabel)}// Hosts whose pages are, in practice, a video: the card then says "Watch video" instead ofdiff --git a/frontend/src/lib/media-refs.test.js b/frontend/src/lib/media-refs.test.jsindex 137327718..d8c0b2085 100644--- a/frontend/src/lib/media-refs.test.js+++ b/frontend/src/lib/media-refs.test.js@@ -113,6 +113,16 @@ describe('cleanUrl', () => {expect(cleanUrl('https://example.com/' + 'a'.repeat(2020))).toBe('https://example.com/' + 'a'.repeat(2020))expect(cleanUrl('https://example.com/' + 'a'.repeat(2100))).toBeNull()})+ // The host check once used a regex lookbehind, which Safari before 16.4 cannot parse: same+ // rules without it, a label up to 63 characters that neither starts nor ends with a hyphen.+ it('checks each part of the host name for hyphens at either end and its length', () => {+ for (const u of ['https://my-gym.com', 'https://a-b-c.example.org', 'https://x.co', 'https://xn--bcher-kva.ch', `https://${'a'.repeat(63)}.com`]) {+ expect(cleanUrl(u), u).not.toBeNull()+ }+ for (const u of ['https://x-.com', 'https://-.com', 'https://my-gym-.com', 'https://a.b-', `https://${'a'.repeat(64)}.com`]) {+ expect(cleanUrl(u), u).toBeNull()+ }+ })it('refuses what does not parse', () => {expect(cleanUrl('https://exa mple.com')).toBeNull()expect(cleanUrl('https://')).toBeNull()diff --git a/frontend/vite.config.js b/frontend/vite.config.jsindex 77a53bbf4..07fe47b79 100644--- a/frontend/vite.config.js+++ b/frontend/vite.config.js@@ -116,7 +116,11 @@ export default defineConfig({} : {})}},- build: { chunkSizeWarningLimit: 1500 },+ // The iOS app's deployment target is 15.5 (ios/App), so its WebView is Safari 15.5, and the web+ // app follows the same floor. Vite's own default is Safari 16.4: syntax newer than 15.5 went out+ // unlowered and one regex lookbehind kept 1.4.2 on its splash there. What the transpiler cannot+ // lower, scripts/check-bundle-syntax.mjs catches (its test builds the bundle).+ build: { chunkSizeWarningLimit: 1500, target: ['safari15', 'chrome100', 'firefox100', 'edge100'] },// Gives happy-dom tests a working localStorage on Node 24+ (#733).test: { setupFiles: ['./src/test-setup.js'] }})