Browse Source

combine all service-worker scripts into a single file to try and ensure included scripts aren't lost

kb/add-usage-guide
Trent Larson 9 months ago
parent
commit
f517b09ed7
  1. 2
      .gitignore
  2. 6
      README.md
  3. 8
      project.task.yaml
  4. 2
      src/registerServiceWorker.ts
  5. 29
      sw_combine.js
  6. 29
      sw_scripts/additional-scripts.js
  7. 4
      sw_scripts/safari-notifications.js
  8. 21
      vue.config.js

2
.gitignore

@ -2,6 +2,8 @@
node_modules
/dist
signature.bin
# generated during `npm run build`
sw_scripts-combined.js
*.pem
verified.txt
myenv

6
README.md

@ -42,12 +42,6 @@ npm run lint
* `npm run build`
...to make sure the service worker scripts are in proper form. (It's only important if you changed something in that directory.)
* `cp sw_scripts/[ns]* dist/`
... to copy the contents of the `sw_scripts` folder to the `dist` folder - except additional_scripts.js.
* Get on the server and back up the time-safari folder.
* `rsync -azvu -e "ssh -i ~/.ssh/..." dist ubuntutest@test.timesafari.app:time-safari`

8
project.task.yaml

@ -1,17 +1,16 @@
tasks :
- 02 error passing control of a project to another user
- 08 notifications for feed - make them reliable :
- leverage different messaging platform?
- 01 release server & client for fix to project-editing
- .5 fix timeSafari.org cert renewals
- .2 anchor hash into BTC
- .1 add step 1 to onboarding hints to "install"
- 01 bookmarks for BVC
- 24 compelling UI for credential presentations
- discover who in my network has activity on a project
- 24 compelling UI for statistics (eg. World?)
- .5 stop from seeing an error on the first page when browser doesn't support service workers (which I've seen on iPhone; visible in Firefox private window)
@ -28,6 +27,7 @@ tasks :
- 24 make the contact browsing on the front page something that invites more action
- .2 list the "show more" contacts alphabetically
- .5 change server plan & project endpoints to use jwtId as identifier rather than rowid
- 16 edit offers & gives, or revoke allowing re-creation
- .1 When available in the server, give message for 'nonAmountGiven' on offers on ProjectsView page.

2
src/registerServiceWorker.ts

@ -3,7 +3,7 @@
import { register } from "register-service-worker";
if (process.env.NODE_ENV === "production") {
register("/additional-scripts.js", {
register("/sw_scripts-combined.js", {
ready() {
console.log(
"App is being served from cache by a service worker.\n" +

29
sw_combine.js

@ -0,0 +1,29 @@
/**
* We've seen cases where the functions inside safari-notifications.js are not found.
* This is our attempt to ensure that all the functions are available.
*/
const fs = require("fs");
const path = require("path");
const swScriptsDir = path.resolve(__dirname, "sw_scripts");
const outputFile = path.resolve(__dirname, "sw_scripts-combined.js");
// Read all files in the sw_scripts directory
fs.readdir(swScriptsDir, (err, files) => {
if (err) {
console.error("Error reading directory:", err);
return;
}
// Combine files content into one script
const combinedContent = files
.filter((file) => path.extname(file) === ".js")
.map((file) => fs.readFileSync(path.join(swScriptsDir, file), "utf8"))
.join("\n");
// Write the combined content to the output file
fs.writeFileSync(outputFile, combinedContent, "utf8");
console.log("Service worker files combined.");
});

29
sw_scripts/additional-scripts.js

@ -1,5 +1,6 @@
/* eslint-env serviceworker */
/* global workbox */
/* eslint-disable *//* ... because old-browser-compatible files in this directory are combined into a single script during `npm run build` */
importScripts(
"https://storage.googleapis.com/workbox-cdn/releases/6.4.1/workbox-sw.js",
);
@ -7,7 +8,9 @@ importScripts(
function logConsoleAndDb(message, arg1, arg2) {
// in chrome://serviceworker-internals note that the arg1 and arg2 here will show as "[object Object]" in that page but will show as expandable objects in the console
console.log(`${new Date().toISOString()} ${message}`, arg1, arg2);
if (self.appendDailyLog) {
// appendDailyLog is injected at build time by the vue.config.js configureWebpack apply plugin
// eslint-disable-next-line no-undef
if (appendDailyLog) {
let fullMessage = `${new Date().toISOString()} ${message}`;
if (arg1) {
fullMessage += `\n${JSON.stringify(arg1)}`;
@ -15,25 +18,19 @@ function logConsoleAndDb(message, arg1, arg2) {
if (arg2) {
fullMessage += `\n${JSON.stringify(arg2)}`;
}
self.appendDailyLog(fullMessage);
// appendDailyLog is injected from safari-notifications.js at build time by the vue.config.js configureWebpack apply plugin
// eslint-disable-next-line no-undef
appendDailyLog(fullMessage);
} else {
// sometimes we get the error: "Uncaught TypeError: self.appendDailyLog is not a function"
// sometimes we get the error: "Uncaught TypeError: appendDailyLog is not a function"
console.log(
"Not logging to DB (often because self.appendDailyLog doesn't exist).",
"Not logging to DB (often because appendDailyLog doesn't exist).",
);
}
}
self.addEventListener("install", async (event) => {
console.log("Service worker got install event. Importing scripts...", event);
await importScripts(
"safari-notifications.js",
"nacl.js",
"noble-curves.js",
"noble-hashes.js",
);
// this should now be available
logConsoleAndDb("Service worker imported all scripts.");
self.addEventListener("install", async (/* event */) => {
logConsoleAndDb("Service worker finished installation.");
});
self.addEventListener("activate", (event) => {
@ -84,7 +81,9 @@ self.addEventListener("push", function (event) {
} else {
title = payload.title || "Update";
}
message = await self.getNotificationCount();
// getNotificationCount is injected from safari-notifications.js at build time by the vue.config.js configureWebpack apply plugin
// eslint-disable-next-line no-undef
message = await getNotificationCount();
}
if (message) {
const options = {

4
sw_scripts/safari-notifications.js

@ -547,8 +547,12 @@ async function getNotificationCount() {
newClaims++;
}
if (newClaims > 0) {
if (newClaims === 1) {
result = "There is 1 new activity on Time Safari";
} else {
result = `There are ${newClaims} new activities on Time Safari`;
}
}
const most_recent_notified = claims[0]["id"];
await setMostRecentNotified(most_recent_notified);
} else {

21
vue.config.js

@ -1,5 +1,6 @@
const { defineConfig } = require("@vue/cli-service");
const { gitDescribeSync } = require("git-describe");
const { exec } = require("child_process");
process.env.VUE_APP_GIT_HASH = gitDescribeSync().hash;
@ -10,6 +11,23 @@ module.exports = defineConfig({
experiments: {
topLevelAwait: true,
},
plugins: [
{
// Still don't know why this runs three times.
apply: (compiler) => {
compiler.hooks.beforeCompile.tap("BeforeCompile", () => {
// Execute combine-sw.js script
exec("node sw_combine.js", (error, stdout, stderr) => {
if (error || stderr) {
console.error("Service worker files error:", error || stderr);
} else {
console.log("Finished combining service worker files.", stdout);
}
});
});
},
},
],
},
pwa: {
iconPaths: {
@ -17,7 +35,8 @@ module.exports = defineConfig({
},
workboxPluginMode: "InjectManifest",
workboxOptions: {
swSrc: "./sw_scripts/additional-scripts.js",
// this script will be checked for linting (sw_scripts/* files generate about 1000 linting errors)
swSrc: "./sw_scripts-combined.js",
},
},
});

Loading…
Cancel
Save