Skip to content

feat: implement service worker caching and update build configuration - #303

Open
amitsinghsutara wants to merge 2 commits into
developfrom
AJ-742
Open

feat: implement service worker caching and update build configuration#303
amitsinghsutara wants to merge 2 commits into
developfrom
AJ-742

Conversation

@amitsinghsutara

@amitsinghsutara amitsinghsutara commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

Changes

  • implement service worker caching and update build configuration

Ref: AJ-742

Summary by CodeRabbit

  • New Features

    • Added improved service-worker update notifications with confirmation before reloading.
    • Added more reliable caching progress reporting during service-worker updates.
    • Added clearer logging when resource caching encounters errors.
  • Bug Fixes

    • Improved recovery when caching operations fail, ensuring updates can continue cleanly.
    • Streamlined service-worker update handling to avoid unnecessary activation and reload events.

@amitsinghsutara
amitsinghsutara requested a review from dz4va August 10, 2026 11:29
@amitsinghsutara amitsinghsutara self-assigned this Aug 10, 2026
@coderabbitai

coderabbitai Bot commented Aug 10, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The PR bundles the application and service worker separately, replaces direct Workbox registration with confirmation-mode update registration, delegates update notification to Workbox, and updates GDL asset caching with progress reporting and guaranteed lock cleanup.

Changes

Service worker update and caching flow

Layer / File(s) Summary
Service worker update integration
sw-src.ts
Typed Workbox imports and update notification replace runtime Workbox usage. Immediate activation remains enabled, and fetch failures are logged.
GDL asset caching progress
sw-src.ts
GDL asset caching uses typed collections, cacheUrlsWithProgress, per-item error logging, and finally blocks for lock reset.
Application and service-worker bundles
webpack.config.js, workbox-config.js
Webpack emits app.js and sw.js. Workbox uses dist/sw.js as its source.
Client update registration and messages
App.ts, src/Books/GdlBookRuntime.ts
Both clients register /sw.js in confirmation mode and handle only CachingProgress messages. App.lang and loading-handler parameters use updated types.

Estimated code review effort: 4 (Complex) | ~45 minutes

Possibly related PRs

Suggested reviewers: dz4va

Sequence Diagram(s)

sequenceDiagram
  participant App
  participant registerServiceWorkerUpdates
  participant ServiceWorker
  participant cacheUrlsWithProgress
  participant BroadcastChannel
  App->>registerServiceWorkerUpdates: register /sw.js in confirm mode
  registerServiceWorkerUpdates->>ServiceWorker: connect to bundled worker
  App->>ServiceWorker: request GDL asset caching
  ServiceWorker->>cacheUrlsWithProgress: cache asset URLs
  cacheUrlsWithProgress->>BroadcastChannel: send CachingProgress
  BroadcastChannel->>App: forward caching progress
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 55.56% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Tests & Lint & Coverage ⚠️ Warning The PR adds no tests; its changed-file set has no test paths. package.json has no test, lint, or coverage script, and no coverage tooling or report exists, so required checks are unmet. Add automated tests for the service-worker and caching changes, configure test/lint/coverage commands, and demonstrate coverage of at least 70%.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is concise, descriptive, and accurately covers the service worker caching and build configuration changes.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch AJ-742

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@sw-src.js`:
- Around line 300-315: Update the caching flow around cacheUrlsWithProgress and
its onItemError callback to track failed URLs, and prevent CachingProgress from
reporting successful 100% completion when any asset failed. Send the established
failure or partial-cache status consumed by App.ts/GdlBookRuntime.ts so later
launches retry incomplete caches.
- Around line 4-7: Remove the unsupported exclude option from the
precacheAndRoute call in sw-src.js, and configure manifest generation in
workbox-config.js to omit lang/**/* via globIgnores or an equivalent manifest
transform.

In `@webpack.config.js`:
- Around line 27-31: Update the HtmlWebpackPlugin configuration to include only
the app entry in index.html, using chunks: ['app'] or excluding the sw chunk.
Ensure the emitted document no longer contains a script reference to sw.js while
preserving the existing app output.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 75d88aec-e37d-43ce-808a-6c1c0fa224a9

📥 Commits

Reviewing files that changed from the base of the PR and between 5c1e63f and 3297d02.

⛔ Files ignored due to path filters (23)
  • dist/app.js is excluded by !**/dist/**, !dist/**
  • dist/index.html is excluded by !**/dist/**, !dist/**
  • dist/src/Models/AudioElement.js is excluded by !**/dist/**, !dist/**
  • dist/src/Models/AudioElement.js.map is excluded by !**/dist/**, !**/*.map, !dist/**
  • dist/src/Models/AudioTimestamps.js is excluded by !**/dist/**, !dist/**
  • dist/src/Models/AudioTimestamps.js.map is excluded by !**/dist/**, !**/*.map, !dist/**
  • dist/src/Models/Book.js is excluded by !**/dist/**, !dist/**
  • dist/src/Models/Book.js.map is excluded by !**/dist/**, !**/*.map, !dist/**
  • dist/src/Models/ImageElement.js is excluded by !**/dist/**, !dist/**
  • dist/src/Models/ImageElement.js.map is excluded by !**/dist/**, !**/*.map, !dist/**
  • dist/src/Models/Models.js is excluded by !**/dist/**, !dist/**
  • dist/src/Models/Models.js.map is excluded by !**/dist/**, !**/*.map, !dist/**
  • dist/src/Models/Page.js is excluded by !**/dist/**, !dist/**
  • dist/src/Models/Page.js.map is excluded by !**/dist/**, !**/*.map, !dist/**
  • dist/src/Models/TextElement.js is excluded by !**/dist/**, !dist/**
  • dist/src/Models/TextElement.js.map is excluded by !**/dist/**, !**/*.map, !dist/**
  • dist/src/Models/WordTimestampElement.js is excluded by !**/dist/**, !dist/**
  • dist/src/Models/WordTimestampElement.js.map is excluded by !**/dist/**, !**/*.map, !dist/**
  • dist/src/PlayBackEngine/PlayBackEngine.js is excluded by !**/dist/**, !dist/**
  • dist/src/PlayBackEngine/PlayBackEngine.js.map is excluded by !**/dist/**, !**/*.map, !dist/**
  • dist/sw.js is excluded by !**/dist/**, !dist/**
  • package-lock.json is excluded by !**/package-lock.json, !**/*.json, !package-lock.json
  • package.json is excluded by !**/*.json
📒 Files selected for processing (6)
  • App.ts
  • src/Books/GdlBookRuntime.ts
  • sw-src.js
  • sw.js
  • webpack.config.js
  • workbox-config.js

Comment thread sw-src.js Outdated
Comment on lines 4 to 7
precacheAndRoute(self.__WB_MANIFEST, {
ignoreURLParametersMatching: [/^book/, /^cr_user_id/],
exclude: [/^lang\//],
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

tmp_dir="$(mktemp -d)"
trap 'rm -rf "$tmp_dir"' EXIT

(
  cd "$tmp_dir"
  npm pack workbox-precaching@7.4.1 --silent >/dev/null
  tar -xzf ./*.tgz
  rg -n -C 3 'PrecacheRouteOptions|ignoreURLParametersMatching|exclude' package
)

rg -n -C 3 'globPatterns|globIgnores|lang/' workbox-config.js

Repository: curiouslearning/CRWebPlayer

Length of output: 50384


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Repository files of interest:"
git ls-files | rg '(^|/)sw-src\.js$|(^|/)workbox-config\.js$|package\.json$'

echo
echo "sw-src.js lines 1-20 and 280-330:"
if [ -f sw-src.js ]; then
  sed -n '1,20p;280,330p' sw-src.js | cat -n
fi

echo
echo "workbox-config.js:"
if [ -f workbox-config.js ]; then
  sed -n '1,220p' workbox-config.js | cat -n
fi

echo
echo "package manager lock/workbox versions:"
for f in package-lock.json npm-shrinkwrap.json pnpm-lock.yaml yarn.lock; do
  if [ -f "$f" ]; then
    echo "--- $f ---"
    rg -n '"workbox-(inject-manifest|-cli|precaching)/?:"|workbox-(inject-manifest|cli|precaching)' "$f" | head -80
  fi
done

echo
echo "Search for lang exclusion configuration:"
rg -n -C 3 'globIgnores|globPatterns|exclude:|lang/\*|lang/' .

Repository: curiouslearning/CRWebPlayer

Length of output: 50384


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Repository files of interest:"
git ls-files | rg '(^|/)sw-src\.js$|(^|/)workbox-config\.js$|package\.json$'

echo
echo "sw-src.js lines 1-20 and 280-330:"
if [ -f sw-src.js ]; then
  sed -n '1,20p;280,330p' sw-src.js | cat -n
fi

echo
echo "workbox-config.js:"
if [ -f workbox-config.js ]; then
  sed -n '1,220p' workbox-config.js | cat -n
fi

echo
echo "package manager lock/workbox versions:"
for f in package-lock.json npm-shrinkwrap.json pnpm-lock.yaml yarn.lock; do
  if [ -f "$f" ]; then
    echo "--- $f ---"
    rg -n '"workbox-(inject-manifest|cli|precaching)/?:"|workbox-(inject-manifest|cli|precaching)' "$f" | head -80
  fi
done

echo
echo "Search for lang exclusion configuration:"
rg -n -C 3 'globIgnores|globPatterns|exclude:|lang/\*|lang/' .

Repository: curiouslearning/CRWebPlayer

Length of output: 50384


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Repository files of interest:"
git ls-files | rg '(^|/)sw-src\.js$|(^|/)workbox-config\.js$|(^|/)package\.json$'

echo
echo "sw-src.js lines 1-20 and 280-330:"
if [ -f sw-src.js ]; then
  sed -n '1,20p;280,330p' sw-src.js | cat -n
fi

echo
echo "workbox-config.js:"
if [ -f workbox-config.js ]; then
  sed -n '1,220p' workbox-config.js | cat -n
fi

echo
echo "Package manager lock/workbox versions:"
for f in package-lock.json npm-shrinkwrap.json pnpm-lock.yaml yarn.lock; do
  if [ -f "$f" ]; then
    echo "--- $f ---"
    rg -n '"workbox-(inject-manifest|cli|precaching)/?:"|workbox-(inject-manifest|cli|precaching)' "$f" | head -80
  fi
done

echo
echo "Search for lang exclusion configuration:"
rg -n -C 3 'globIgnores|globPatterns|exclude:|lang/\*|lang/' .

Repository: curiouslearning/CRWebPlayer

Length of output: 50384


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Repository files of interest:"
git ls-files | rg '(^|/)sw-src\.js$|(^|/)workbox-config\.js$|(^|/)package\.json$' || true

echo
echo "sw-src.js lines 1-20 and 280-330:"
if [ -f sw-src.js ]; then
  sed -n '1,20p;280,330p' sw-src.js | cat -n
fi

echo
echo "workbox-config.js:"
if [ -f workbox-config.js ]; then
  sed -n '1,220p' workbox-config.js | cat -n
fi

echo
echo "Package manager lock/workbox versions:"
for f in package-lock.json npm-shrinkwrap.json pnpm-lock.yaml yarn.lock; do
  if [ -f "$f" ]; then
    echo "--- $f ---"
    rg -n '"workbox-(inject-manifest|cli|precaching)/?:"|workbox-(inject-manifest|cli|precaching)' "$f" | head -80 || true
  fi
done

echo
echo "Search for lang exclusion configuration:"
rg -n -C 3 'globIgnores|globPatterns|exclude:|lang/\*|lang/' . || true

echo
echo "Type/interface check for PrecacheRouteOptions excluding exclude:"
tmp_dir="$(mktemp -d)"
trap 'rm -rf "$tmp_dir"' EXIT
(
  cd "$tmp_dir"
  npm pack workbox-precaching@7.4.1 --silent >/dev/null
  tar -xzf ./*.tgz
  rg -n 'interface PrecacheRouteOptions|function generateURLVariations|urlManipulation|exclude' package/_types.d.ts package/utils/generateURLVariations.js package/build/workbox-precaching.dev.js package/build/workbox-precaching.prod.js || true
)

Repository: curiouslearning/CRWebPlayer

Length of output: 50384


Move the lang/ exclusion to manifest generation.

exclude is not a precacheAndRoute option; it does not remove lang/ files from self.__WB_MANIFEST. Remove it from this call. Add "lang/**/*" to workbox-config.js globIgnores, or use a manifest transform to filter those entries.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@sw-src.js` around lines 4 - 7, Remove the unsupported exclude option from the
precacheAndRoute call in sw-src.js, and configure manifest generation in
workbox-config.js to omit lang/**/* via globIgnores or an equivalent manifest
transform.

Comment thread sw-src.js Outdated
Comment on lines 300 to 315
await cacheUrlsWithProgress(cache, bookAudioAndImageFiles, {
batchSize: 5,
delayBetweenBatchesMs: 100,
onProgress: async (progress) => {
const clients = await self.clients.matchAll();
if (clients.length > 0) {
await channel.postMessage({
command: "CachingProgress",
data: { progress: Math.round(progress), bookName: bookData.bookName },
});
}
},
onItemError: (url, error) => {
// Optional: log at a low level for debugging, but don't treat as a hard error.
console.log("Skipping missing or unreachable asset:", url);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n -C 8 'cacheUrlsWithProgress|onProgress|onItemError|CachingProgress' sw-src.js
rg -n -C 8 'CachingProgress|progressValue >= 100|localStorage\.setItem' App.ts src/Books/GdlBookRuntime.ts

tmp_dir="$(mktemp -d)"
trap 'rm -rf "$tmp_dir"' EXIT
(
  cd "$tmp_dir"
  npm pack `@curiouslearning/sw`@1.0.0 --silent >/dev/null
  tar -xzf ./*.tgz
  rg -n -C 8 'cacheUrlsWithProgress|onProgress|onItemError' package
)

Repository: curiouslearning/CRWebPlayer

Length of output: 41373


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the cached-book loading/skipping paths and all `localStorage.setItem(event.data.data.bookName, "true")` sites.
rg -n -C 9 'localStorage\.getItem|setItem\(event\.data\.data\.bookName|bookName|download_completed|readLanguageDataFromCacheAndNotifyAndroidApp|gdl|load.*book|loadBooks|Book' App.ts src src/Books src/Books/GdlBookRuntime.ts src/Books/*.ts 2>/dev/null || true

# Search for any other persistent markers or download-completed behavior near `localStorage.setItem(event.data.data.bookName, "true")`.
rg -n -C 7 'download_completed|CachingProgress|localStorage\.setItem\(event\.data\.data\.bookName|cached|loadBook|GdlBookRuntime' app src || true

Repository: curiouslearning/CRWebPlayer

Length of output: 50383


Do not mark incomplete caches as complete.

cacheUrlsWithProgress treats per-item failures as progress. If onItemError only logs, CachingProgress can still reach 100, then App.ts/GdlBookRuntime.ts skip the cache request on later launches. Track failed URLs and send a failure or partial-cache status instead of reporting 100% completion.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@sw-src.js` around lines 300 - 315, Update the caching flow around
cacheUrlsWithProgress and its onItemError callback to track failed URLs, and
prevent CachingProgress from reporting successful 100% completion when any asset
failed. Send the established failure or partial-cache status consumed by
App.ts/GdlBookRuntime.ts so later launches retry incomplete caches.

Comment thread webpack.config.js
Comment on lines 27 to +31
new HtmlWebpackPlugin({
title: 'Curious Reader',
template: 'index.html',
filename: 'index.html',

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

if [[ -f dist/index.html ]]; then
  rg -n 'src="[^"]*(app|sw)\.js"' dist/index.html
else
  echo "Build output is absent. Run the normal build locally, then verify that dist/index.html includes app.js but not sw.js."
fi

Repository: curiouslearning/CRWebPlayer

Length of output: 700


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'Files matching config templates:\n'
git ls-files | rg '(^|/)(webpack\.config\.js|workbox-config\.js|index\.html)$' || true

printf '\nwebpack.config.js:\n'
if [[ -f webpack.config.js ]]; then
  cat -n webpack.config.js
fi

printf '\nworkbox-config.js:\n'
if [[ -f workbox-config.js ]]; then
  cat -n workbox-config.js
fi

printf '\nindex.html head/body context:\n'
if [[ -f index.html ]]; then
  cat -n index.html
fi

printf '\nPackage versions:\n'
if [[ -f package.json ]]; then
  node - <<'JS'
const fs = require('fs');
const pkg = JSON.parse(fs.readFileSync('package.json','utf8'));
console.log(JSON.stringify({
  deps: pkg.dependencies,
  devDeps: pkg.devDependencies
}, null, 2));
JS
fi

Repository: curiouslearning/CRWebPlayer

Length of output: 4864


Exclude the service-worker entry from the emitted index.html.

webpack.config.js defines app and sw entries, and HtmlWebpackPlugin emits both as document scripts. Build output currently includes src="sw.js", which runs the pre-injection source worker in the page context while Workbox generates the registration worker at the root path /sw.js. Set chunks: ['app'] or excludeChunks: ['sw'] on HtmlWebpackPlugin to prevent executing service-worker code in the document.

Proposed fix
     new HtmlWebpackPlugin({
       title: 'Curious Reader',
       template: 'index.html',
       filename: 'index.html',
+      chunks: ['app'],
     }),
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
new HtmlWebpackPlugin({
title: 'Curious Reader',
template: 'index.html',
filename: 'index.html',
new HtmlWebpackPlugin({
title: 'Curious Reader',
template: 'index.html',
filename: 'index.html',
chunks: ['app'],
}),
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@webpack.config.js` around lines 27 - 31, Update the HtmlWebpackPlugin
configuration to include only the app entry in index.html, using chunks: ['app']
or excluding the sw chunk. Ensure the emitted document no longer contains a
script reference to sw.js while preserving the existing app output.

@miguelccodev miguelccodev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please make use of @curiouslearning/sw where applicable and integrate along side the updated workbox framework.

@miguelccodev

Copy link
Copy Markdown

Also, the tests to ensure functionality:

  • npm run build should succeed (or dist, depending on where your output is)
  • npx live-server ./build (or dist, depending on where your output is)
  • load app
  • apply changes
  • npm run build
  • it should work.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@sw-src.ts`:
- Around line 312-334: Update cacheBookAssets so its catch block posts a
terminal CachingError message through channel, including the book identity and
error details alongside the existing logging. In the consumers that currently
process CachingProgress, including App.ts handling and GdlBookRuntime, handle
CachingError by hiding the loading screen and exposing the established retry
path, while preserving normal progress behavior.
- Around line 9-12: Move the lang/ exclusion from the precacheAndRoute options
into Workbox manifest generation by adding the appropriate lang/**/* pattern to
globIgnores or an equivalent manifest transform. Remove the unsupported exclude
option and the as any cast from the precacheAndRoute call, preserving the
existing URL-parameter matching.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: c0984462-bcea-483d-b836-e764332ccc84

📥 Commits

Reviewing files that changed from the base of the PR and between 3297d02 and 1a11276.

⛔ Files ignored due to path filters (2)
  • dist/app.js is excluded by !**/dist/**, !dist/**
  • dist/sw.js is excluded by !**/dist/**, !dist/**
📒 Files selected for processing (6)
  • App.ts
  • src/Books/GdlBookRuntime.ts
  • sw-src.ts
  • sw.js
  • webpack.config.js
  • workbox-config.js
🚧 Files skipped from review as they are similar to previous changes (4)
  • workbox-config.js
  • App.ts
  • src/Books/GdlBookRuntime.ts
  • webpack.config.js

Comment thread sw-src.ts
Comment on lines +9 to +12
precacheAndRoute(self.__WB_MANIFEST, {
ignoreURLParametersMatching: [/^book/, /^cr_user_id/],
exclude: [/^lang\//],
});
} as any);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect where the precache manifest excludes language assets.
rg -n -C 4 'globIgnores|manifestTransforms|exclude|lang/' \
  sw-src.ts workbox-config.js webpack.config.js 2>/dev/null || true

Repository: curiouslearning/CRWebPlayer

Length of output: 1334


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- workbox-config.js ---'
cat -n workbox-config.js

printf '%s\n' '--- sw-src.ts ---'
cat -n sw-src.ts

printf '%s\n' '--- Workbox dependencies and precache API usage ---'
rg -n -C 3 '"workbox|workbox-webpack-plugin|precacheAndRoute|__WB_MANIFEST|globIgnores|manifestTransforms|lang/' \
  package.json package-lock.json yarn.lock pnpm-lock.yaml sw-src.ts webpack.config.js .github 2>/dev/null || true

printf '%s\n' '--- language asset paths ---'
rg -n -C 2 '(^|[/_ -])lang(/|[/_ -])|lang/' \
  --glob '!node_modules/**' --glob '!dist/**' --glob '!build/**' . 2>/dev/null | head -200 || true

Repository: curiouslearning/CRWebPlayer

Length of output: 38344


🌐 Web query:

Workbox 7.4.1 precacheAndRoute PrecacheRouteOptions exclude ignoreURLParametersMatching source

💡 Result:

In Workbox, including version 7.4.1, the precacheAndRoute method is a convenience function that registers a route to serve precached assets [1][2]. It accepts an optional second argument of type PrecacheRouteOptions, which allows you to customize how incoming requests are matched against your precache manifest [1][3]. The ignoreURLParametersMatching option is a property within PrecacheRouteOptions that accepts an array of Regular Expressions (RegExp[]) [1][3]. This configuration determines which search parameters should be ignored when matching a request URL against the entries in your precache [1][4]. By default, Workbox ignores parameters that match /^utm_/ (e.g., utm_source, utm_campaign), meaning requests with these parameters will be treated as matching the underlying precached asset without those parameters [4]. If you wish to customize or override this behavior, you can provide your own array of regex patterns [1][3]. For example, to ignore all URL parameters, you would configure it as follows [1][3]: import {precacheAndRoute} from 'workbox-precaching'; precacheAndRoute( [ {url: '/index.html', revision: '383676'}, //... other entries ], { // Ignore all URL parameters. ignoreURLParametersMatching: [/.*/], }); Other available options within PrecacheRouteOptions include: - cleanURLs (boolean): Whether to automatically check the cache for a URL with a.html extension if the original request does not match [3][4]. - directoryIndex (string): The filename to append when a request ends in a slash (default is index.html) [3][4]. - urlManipulation (function): A callback to perform custom URL transformations for matching [3][4].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
import json
from pathlib import Path

cfg = json.loads(Path("package.json").read_text())
print("workbox-precaching:", cfg.get("dependencies", {}).get("workbox-precaching"))
print("workbox-cli:", cfg.get("dependencies", {}).get("workbox-cli"))
print("globIgnores:", json.loads(Path("workbox-config.js").read_text().split("globIgnores:", 1)[1].split("]", 1)[0] + "]") if False else "inspect source above")
PY

printf '%s\n' '--- all config keys ---'
rg -n '^[[:space:]]*[A-Za-z][A-Za-z0-9]*[[:space:]]*:' workbox-config.js

printf '%s\n' '--- candidate language directories/files ---'
find . -path './node_modules' -prune -o -path './.git' -prune -o \( -type d -name 'lang' -o -type f -path '*/lang/*' \) -print

Repository: curiouslearning/CRWebPlayer

Length of output: 490


🌐 Web query:

site:github.com/GoogleChrome/workbox v7.4.1 addRoute.mjs PrecacheRouteOptions cleanURLs directoryIndex urlManipulation ignoreURLParametersMatching

💡 Result:

In Workbox v7.4.1 (and other versions), the PrecacheRouteOptions interface defines the configuration for how precached assets are matched against fetch requests [1][2]. These options are utilized by the addRoute.mjs module (and by extension, precacheAndRoute.mjs) to determine which URL variations to check in the precache when a fetch event occurs [3][4]. The configuration properties within PrecacheRouteOptions are: 1. cleanURLs (boolean, default: true): When enabled, if a request does not match directly, Workbox will attempt to find a match by appending.html to the end of the pathname [3][2]. 2. directoryIndex (string, default: index.html): If a request ends with a trailing slash (/), Workbox will attempt to find a match by appending the specified directoryIndex value to the pathname [3][2]. 3. ignoreURLParametersMatching (Array, default: [/^utm_/, /^fbclid$/]): This array contains regular expressions used to identify and remove search parameters from the request URL before attempting to match it against precached entries [3][2]. This ensures that common tracking parameters do not prevent a match [3]. 4. urlManipulation (function): This optional function allows developers to provide custom logic to generate alternative URLs [3][5]. It takes the request URL as input and should return an array of alternative URLs that Workbox will then attempt to match in the cache [6][2]. These options are processed by the internal generateURLVariations utility, which yields these potential variations for cache matching one at a time [6][2].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- package.json dependency section ---'
cat -n package.json | sed -n '1,45p'

printf '%s\n' '--- workbox config syntax and exclusions ---'
cat -n workbox-config.js
rg -n -C 3 'workbox|globDirectory|globPatterns|globIgnores|lang/' \
  package.json package-lock.json workbox-config.js webpack.config.js README.md .github 2>/dev/null || true

printf '%s\n' '--- tracked files that match the manifest patterns under lang ---'
git ls-files | awk '
  /^lang\// || /\/lang\// {
    if ($0 ~ /\.(wav|mp3|WAV|gif|png|webp|otf|jpg|js|json|css|html)$/) print
  }
'

Repository: curiouslearning/CRWebPlayer

Length of output: 37048


Move the lang/ exclusion to manifest generation.

exclude is not a valid PrecacheRouteOptions member in Workbox 7.4.1. The as any cast hides this mismatch. Add lang/**/* to globIgnores or use a manifest transform, then remove the unsupported route option.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@sw-src.ts` around lines 9 - 12, Move the lang/ exclusion from the
precacheAndRoute options into Workbox manifest generation by adding the
appropriate lang/**/* pattern to globIgnores or an equivalent manifest
transform. Remove the unsupported exclude option and the as any cast from the
precacheAndRoute call, preserving the existing URL-parameter matching.

Comment thread sw-src.ts
Comment on lines +312 to 334
async function cacheBookAssets(bookData: any, bookAudioAndImageFiles: any) {
try {
const cache = await caches.open(bookData.bookName);
await cacheUrlsWithProgress(cache, bookAudioAndImageFiles, {
batchSize: 5,
delayBetweenBatchesMs: 100,
onProgress: async (progress) => {
const clients = await self.clients.matchAll();
if (clients.length > 0) {
channel.postMessage({
command: "CachingProgress",
data: { progress: Math.round(progress), bookName: bookData.bookName },
});
}
},
onItemError: (url, error) => {
// Optional: log at a low level for debugging, but don't treat as a hard error.
console.log("Skipping missing or unreachable asset:", url, error);
}
}

// Whether or not all files in the batch were cached successfully, count the batch as processed
// so that progress can eventually reach 100% even if some assets are missing.
cachingProgress += batch.length;

// Send progress update after each batch
const progress = Math.round((cachingProgress / bookAudioAndImageFiles.length) * 100);
const clients = await self.clients.matchAll();
if (clients.length > 0) {
await channel.postMessage({
command: "CachingProgress",
data: { progress, bookName: bookData.bookName },
});
}

// Introduce a small delay between batches
await new Promise((resolve) => setTimeout(resolve, 100));
});
} catch (error) {
console.error("Unhandled error in cacheBookAssets:", error);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Send a terminal failure message when caching fails.

If caches.open() or cacheUrlsWithProgress() fails, this catch only logs the error and resolves the cache request. App.ts:93-125 and src/Books/GdlBookRuntime.ts:12-54 set the loading screen visible before caching and process only CachingProgress. They cannot clear the loading screen or offer retry after this failure.

Post a terminal CachingError message from this catch. Update both consumers to hide the loading screen and show a retry path when they receive it.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@sw-src.ts` around lines 312 - 334, Update cacheBookAssets so its catch block
posts a terminal CachingError message through channel, including the book
identity and error details alongside the existing logging. In the consumers that
currently process CachingProgress, including App.ts handling and GdlBookRuntime,
handle CachingError by hiding the loading screen and exposing the established
retry path, while preserving normal progress behavior.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants