├── .eslintrc.cjs
├── .github
└── workflows
│ ├── ci.yml
│ └── publish.yml
├── .gitignore
├── .husky
└── pre-commit
├── .nvmrc
├── .prettierignore
├── CHANGELOG.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── babel.config.cjs
├── codecov.yml
├── examples
├── .gitkeep
└── my-astro-site
│ ├── .gitignore
│ ├── .vscode
│ ├── extensions.json
│ └── launch.json
│ ├── README.md
│ ├── astro.config.mjs
│ ├── package.json
│ ├── public
│ ├── favicon.svg
│ └── monstercat.png
│ ├── src
│ ├── env.d.ts
│ ├── images
│ │ └── banksy.webp
│ └── pages
│ │ └── index.astro
│ └── tsconfig.json
├── jest.config.cjs
├── package.json
├── pnpm-lock.yaml
├── pnpm-workspace.yaml
├── public.package.json
├── src
├── index.ts
├── noop-service-worker.js
└── service-worker.js.js
└── tsconfig.json
/.eslintrc.cjs:
--------------------------------------------------------------------------------
1 | // eslint-disable-next-line no-undef
2 | module.exports = {
3 | root: true,
4 | env: {
5 | node: true,
6 | es2020: true,
7 | },
8 | ignorePatterns: ["dist", "examples"],
9 | plugins: ["@typescript-eslint"],
10 | extends: [
11 | "eslint:recommended",
12 | "plugin:@typescript-eslint/recommended",
13 | "prettier",
14 | ],
15 | overrides: [
16 | {
17 | files: ["*.ts"],
18 | parser: "@typescript-eslint/parser",
19 | parserOptions: {
20 | // eslint-disable-next-line no-undef
21 | tsconfigRootDir: __dirname,
22 | project: ["./tsconfig.json"],
23 | },
24 | extends: [
25 | "plugin:@typescript-eslint/recommended-requiring-type-checking",
26 | ],
27 | rules: {
28 | "@typescript-eslint/prefer-nullish-coalescing": "error",
29 | "@typescript-eslint/no-unnecessary-condition": "error",
30 | "@typescript-eslint/prefer-optional-chain": "error",
31 | },
32 | },
33 | ],
34 | };
35 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 | on:
3 | push:
4 | branches:
5 | - main
6 | pull_request:
7 | jobs:
8 | ci:
9 | name: "Lint and Test"
10 | runs-on: ubuntu-latest
11 | steps:
12 | - uses: actions/checkout@v3
13 | - uses: pnpm/action-setup@v2
14 | - uses: actions/setup-node@v3
15 | with:
16 | node-version-file: ".nvmrc"
17 | cache: "pnpm"
18 | - run: pnpm install --frozen-lockfile
19 | - run: pnpm package:build
20 | - run: pnpm lint
21 | # - run: pnpm test:ci && pnpm codecov --token=$CODECOV_TOKEN
22 | # env:
23 | # CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
24 |
--------------------------------------------------------------------------------
/.github/workflows/publish.yml:
--------------------------------------------------------------------------------
1 | name: Publish NPM Package
2 | on:
3 | release:
4 | types: [created]
5 | jobs:
6 | build:
7 | runs-on: ubuntu-latest
8 | steps:
9 | - uses: actions/checkout@v3
10 | - uses: pnpm/action-setup@v2
11 | - uses: actions/setup-node@v3
12 | with:
13 | node-version-file: ".nvmrc"
14 | cache: "pnpm"
15 | registry-url: "https://registry.npmjs.org"
16 | - run: pnpm install --frozen-lockfile
17 | - run: pnpm package:build
18 | - run: (cp CHANGELOG.md README.md dist) && cd dist && npm publish
19 | env:
20 | NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
21 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | !**/dist/index.html
2 | **/dist/*
3 | coverage
4 | node_modules
5 | todo.txt
6 | tsconfig.tsbuildinfo
7 |
--------------------------------------------------------------------------------
/.husky/pre-commit:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 | . "$(dirname -- "$0")/_/husky.sh"
3 |
4 | pnpm lint:fix
5 |
--------------------------------------------------------------------------------
/.nvmrc:
--------------------------------------------------------------------------------
1 | 18.13
2 |
--------------------------------------------------------------------------------
/.prettierignore:
--------------------------------------------------------------------------------
1 | dist
2 | coverage
3 | pnpm-lock.yaml
4 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | ## 2.0.0
4 |
5 | - Fix `entryPoint` deprecation in Astro 4. This package now requires Astro v4 or later.
6 |
7 | ## 1.1.0
8 |
9 | - Adds support for [base](https://docs.astro.build/en/reference/configuration-reference/#base). Thanks @ntsd.
10 | - Fix Response warning for Astro v3 users: https://docs.astro.build/en/guides/upgrade-to/v3/#deprecated-returning-simple-object-in-endpoints.
11 |
12 | ## 1.0.0
13 |
14 | - astrojs-service-worker is now 1.0! This library will now follow [semantic versioning](https://docs.npmjs.com/about-semantic-versioning).
15 | - More Windows support fixes. Thanks @barbalex for the fix!
16 | - Cache images and other assets other than html/css/js. Thanks @squeezeboxhuf!
17 |
18 | ## 0.0.9
19 |
20 | - Add support for Windows.
21 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing 👫
2 |
3 | Thanks for helping make this project better!
4 |
5 | ## Report an Issue 🐛
6 |
7 | If you find a bug or want to discuss a new feature, please [create a new issue](https://github.com/tatethurston/astrojs-service-worker/issues). If you'd prefer to keep things private, feel free to [email me](mailto:tatethurston@gmail.com?subject=astrojs-service-worker).
8 |
9 | ## Contributing Code with Pull Requests 🎁
10 |
11 | Please create a [pull request](https://github.com/tatethurston/astrojs-service-worker/pulls). Expect a few iterations and some discussion before your pull request is merged. If you want to take things in a new direction, feel free to fork and iterate without hindrance!
12 |
13 | ## Code of Conduct 🧐
14 |
15 | My expectations for myself and others is to strive to build a diverse, inclusive, safe community.
16 |
17 | For more guidance, check out [thoughtbot's code of conduct](https://thoughtbot.com/open-source-code-of-conduct).
18 |
19 | ## Licensing 📃
20 |
21 | See the project's [MIT License](https://github.com/tatethurston/astrojs-service-worker/blob/main/LICENSE).
22 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2021 Tate Thurston
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Astro Service Worker
2 |
3 |
An Astro integration that generates a Service Worker. Powered by Workbox.
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 | ## What is this? 🧐
27 |
28 | A minimal wrapper around [Workbox](https://developers.google.com/web/tools/workbox) to quickly add a [service worker](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) to your [Astro](https://astro.build/) static site. Get precached pages and offline support out of the box.
29 |
30 | ## Installation & Usage 📦
31 |
32 | 1. Add this package to your project:
33 | - `npm install astrojs-service-worker` or `yarn add astrojs-service-worker`
34 | 2. Add `astrojs-service-worker` to your [astro.config.mjs](https://docs.astro.build/en/reference/configuration-reference/) integrations:
35 |
36 | ```diff
37 | import { defineConfig } from "astro/config";
38 | + import serviceWorker from "astrojs-service-worker";
39 |
40 | export default defineConfig({
41 | + integrations: [serviceWorker()],
42 | });
43 | ```
44 |
45 | 3. That's it! A service worker that precaches all of your build's static assets will be generated. Page navigations will be served from the service worker's cache instead of making network calls, speeding up your page views and enabling offline viewing 🙌.
46 |
47 | _Note that when running `astro dev` a no-op service worker is generated. Service workers interfere with hot module reloading (because they intercept the request for the updated asset), so this no-op service worker clears any existing workers for the page so hot module reloading works as expected._
48 |
49 | ## Verification 🤔
50 |
51 | 1. To view the production service worker, run `astro build && astro preview`.
52 | 2. The service worker must first install before it intercepts any traffic. You can view the status of the service worker in Chrome by opening the dev console, clicking the `Application` tab and then clicking the `Service Workers` tab.
53 | 3. Disable your internet connection and click around your site. Your pages will be served by the service worker. This is most obvious when you are disconnected from the internet, but even when users have an internet connection your pages will be served from the service worker and not from the network -- markedly speeding up page requests.
54 |
55 | ## API Overview 🛠
56 |
57 |
58 |
59 |
60 |
Name
61 |
Description
62 |
Type
63 |
64 |
65 |
66 |
67 |
68 |
registration.autoRegister
69 |
70 |
71 | Autoregister the service worker.
72 |
73 | If `false`, then the application must initialize the service worker by invoking `register`. Set this to `false` if you'd like to take control over when you service worker is initialized. You'll then need to add something like the following to your application:
74 |
75 | ```javascript
76 | if ("serviceWorker" in navigator) {
77 | navigator.serviceWorker.register("/service-worker.js");
78 | }
79 | ```
80 |
81 | Defaults to `true`. Recommended: `true`.
82 |
83 |
84 |
85 |
boolean | undefined
86 |
87 |
88 |
89 |
workbox
90 |
91 | Options passed to `worbox-build`. See all available configuration options [here](https://developer.chrome.com/docs/workbox/modules/workbox-build/)
92 |
93 | Defaults to `GenerateSW` which will generate a service worker.
94 |
95 | Note: `injectManifest` is not supported at this time. If you would like it to be supported, please [open an issue](https://github.com/tatethurston/astrojs-service-worker/issues/new")
96 |
97 |
98 |
InjectManifestOptions | GenerateSWOptions
99 |
100 |
101 |
102 |
103 | Example:
104 |
105 | ```diff
106 | import { defineConfig } from "astro/config";
107 | import serviceWorker from "astrojs-service-worker";
108 |
109 | export default defineConfig({
110 | integrations: [
111 | serviceWorker({
112 | + workbox: { inlineWorkboxRuntime: true }
113 | })
114 | ],
115 | });
116 | ```
117 |
118 | ## Common Service Worker Pitfalls ⚠️
119 |
120 | You must serve your application over HTTPS in production environments. [Service Workers must be served from the site's origin over HTTPS](https://developers.google.com/web/fundamentals/primers/service-workers).
121 |
122 | Some browsers special case `localhost`, so this may not be necessary during local development. HTTPS is _not_ handled by this library. You can use a reverse proxy like [Nginx](https://www.nginx.com/) or [Caddy](https://caddyserver.com/) if you want to setup HTTPS for local development.
123 |
124 | The service worker origin constraint means that service workers can not control pages on a different subdomain. Eg `mysite.com` can not be controlled by a service worker if that was served from a subdomain such as `mycdn.mysite.com`. To learn more about how service workers work in general, read [MDN's documentation](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API).
125 |
126 | ## Production Sites Using astrojs-service-woker
127 |
128 | My blog, [tatethurston.com](https://www.tatethurston.com/). You can use this site to get a sense of the capabilities enabled by this package. If you have any questions, feel free to [open an issue](https://github.com/tatethurston/astrojs-service-worker/issues/new).
129 |
130 | ## Contributing 👫
131 |
132 | PR's and issues welcomed! For more guidance check out [CONTRIBUTING.md](https://github.com/tatethurston/astrojs-service-worker/blob/main/CONTRIBUTING.md)
133 |
134 | ## Licensing 📃
135 |
136 | See the project's [MIT License](https://github.com/tatethurston/astrojs-service-worker/blob/main/LICENSE).
137 |
--------------------------------------------------------------------------------
/babel.config.cjs:
--------------------------------------------------------------------------------
1 | // eslint-disable-next-line no-undef
2 | module.exports = {
3 | presets: [
4 | ["@babel/preset-env", { targets: { node: "current" } }],
5 | "@babel/preset-typescript",
6 | ],
7 | };
8 |
--------------------------------------------------------------------------------
/codecov.yml:
--------------------------------------------------------------------------------
1 | coverage:
2 | status:
3 | project:
4 | default:
5 | target: auto
6 | threshold: 10%
7 |
--------------------------------------------------------------------------------
/examples/.gitkeep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tatethurston/astrojs-service-worker/77a8ef51e77d153fd8ea9340eb6911f4b6aa97b3/examples/.gitkeep
--------------------------------------------------------------------------------
/examples/my-astro-site/.gitignore:
--------------------------------------------------------------------------------
1 | # build output
2 | dist/
3 | # generated types
4 | .astro/
5 |
6 | # dependencies
7 | node_modules/
8 |
9 | # logs
10 | npm-debug.log*
11 | yarn-debug.log*
12 | yarn-error.log*
13 | pnpm-debug.log*
14 |
15 |
16 | # environment variables
17 | .env
18 | .env.production
19 |
20 | # macOS-specific files
21 | .DS_Store
22 |
--------------------------------------------------------------------------------
/examples/my-astro-site/.vscode/extensions.json:
--------------------------------------------------------------------------------
1 | {
2 | "recommendations": ["astro-build.astro-vscode"],
3 | "unwantedRecommendations": []
4 | }
5 |
--------------------------------------------------------------------------------
/examples/my-astro-site/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "0.2.0",
3 | "configurations": [
4 | {
5 | "command": "./node_modules/.bin/astro dev",
6 | "name": "Development server",
7 | "request": "launch",
8 | "type": "node-terminal"
9 | }
10 | ]
11 | }
12 |
--------------------------------------------------------------------------------
/examples/my-astro-site/README.md:
--------------------------------------------------------------------------------
1 | # Astro Starter Kit: Minimal
2 |
3 | ```
4 | npm create astro@latest -- --template minimal
5 | ```
6 |
7 | [](https://stackblitz.com/github/withastro/astro/tree/latest/examples/minimal)
8 | [](https://codesandbox.io/s/github/withastro/astro/tree/latest/examples/minimal)
9 |
10 | > 🧑🚀 **Seasoned astronaut?** Delete this file. Have fun!
11 |
12 | ## 🚀 Project Structure
13 |
14 | Inside of your Astro project, you'll see the following folders and files:
15 |
16 | ```
17 | /
18 | ├── public/
19 | ├── src/
20 | │ └── pages/
21 | │ └── index.astro
22 | └── package.json
23 | ```
24 |
25 | Astro looks for `.astro` or `.md` files in the `src/pages/` directory. Each page is exposed as a route based on its file name.
26 |
27 | There's nothing special about `src/components/`, but that's where we like to put any Astro/React/Vue/Svelte/Preact components.
28 |
29 | Any static assets, like images, can be placed in the `public/` directory.
30 |
31 | ## 🧞 Commands
32 |
33 | All commands are run from the root of the project, from a terminal:
34 |
35 | | Command | Action |
36 | | :--------------------- | :----------------------------------------------- |
37 | | `npm install` | Installs dependencies |
38 | | `npm run dev` | Starts local dev server at `localhost:3000` |
39 | | `npm run build` | Build your production site to `./dist/` |
40 | | `npm run preview` | Preview your build locally, before deploying |
41 | | `npm run astro ...` | Run CLI commands like `astro add`, `astro check` |
42 | | `npm run astro --help` | Get help using the Astro CLI |
43 |
44 | ## 👀 Want to learn more?
45 |
46 | Feel free to check [our documentation](https://docs.astro.build) or jump into our [Discord server](https://astro.build/chat).
47 |
--------------------------------------------------------------------------------
/examples/my-astro-site/astro.config.mjs:
--------------------------------------------------------------------------------
1 | import { defineConfig } from "astro/config";
2 | import serviceWorker from "astrojs-service-worker";
3 |
4 | export default defineConfig({
5 | integrations: [serviceWorker()],
6 | });
7 |
--------------------------------------------------------------------------------
/examples/my-astro-site/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@example/minimal",
3 | "type": "module",
4 | "version": "0.0.1",
5 | "private": true,
6 | "scripts": {
7 | "dev": "astro dev",
8 | "start": "astro dev",
9 | "build": "astro build",
10 | "preview": "astro preview",
11 | "astro": "astro"
12 | },
13 | "dependencies": {
14 | "astro": "^4.0.3"
15 | },
16 | "devDependencies": {
17 | "astrojs-service-worker": "*"
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/examples/my-astro-site/public/favicon.svg:
--------------------------------------------------------------------------------
1 |
14 |
--------------------------------------------------------------------------------
/examples/my-astro-site/public/monstercat.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tatethurston/astrojs-service-worker/77a8ef51e77d153fd8ea9340eb6911f4b6aa97b3/examples/my-astro-site/public/monstercat.png
--------------------------------------------------------------------------------
/examples/my-astro-site/src/env.d.ts:
--------------------------------------------------------------------------------
1 | ///
2 |
--------------------------------------------------------------------------------
/examples/my-astro-site/src/images/banksy.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tatethurston/astrojs-service-worker/77a8ef51e77d153fd8ea9340eb6911f4b6aa97b3/examples/my-astro-site/src/images/banksy.webp
--------------------------------------------------------------------------------
/examples/my-astro-site/src/pages/index.astro:
--------------------------------------------------------------------------------
1 | ---
2 | import banksy from '../images/banksy.webp';
3 | ---
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 | Astro
12 |
13 |
14 |
Astro
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/examples/my-astro-site/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "astro/tsconfigs/strictest"
3 | }
4 |
--------------------------------------------------------------------------------
/jest.config.cjs:
--------------------------------------------------------------------------------
1 | // eslint-disable-next-line no-undef
2 | module.exports = {
3 | clearMocks: true,
4 | coverageDirectory: "coverage",
5 | modulePathIgnorePatterns: ["dist"],
6 | // TS ESM imports are referenced with .js extensions, but jest will fail to find
7 | // the uncompiled file because it ends with .ts and is looking for .js.
8 | moduleNameMapper: {
9 | "(.+)\\.jsx?": "$1",
10 | },
11 | };
12 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "astrojs-service-worker-dev",
3 | "version": "0.0.1",
4 | "description": "An Astro integration to generate a Service Worker. Powered by Workbox.",
5 | "license": "MIT",
6 | "author": "Tate ",
7 | "repository": {
8 | "type": "git",
9 | "url": "https://github.com/tatethurston/astrojs-service-worker"
10 | },
11 | "scripts": {
12 | "build": "tsc",
13 | "clean": "rm -rf dist",
14 | "lint": "npm run typecheck && prettier --check . && prettier-package-json --list-different '{,example/,}package.json' && eslint .",
15 | "lint:fix": "prettier --write . && prettier-package-json --write '{,example/}package.json' && eslint --fix .",
16 | "package:build": "npm run clean && npm run build && npm run package:prune && npm run package:copy:files",
17 | "package:copy:files": "cp ./LICENSE ./README.md dist/ && cp ./public.package.json dist/package.json",
18 | "package:prune": "find dist -name test.* -delete",
19 | "prepare": "husky install",
20 | "test": "jest",
21 | "test:ci": "jest --coverage",
22 | "typecheck": "tsc --noEmit"
23 | },
24 | "dependencies": {
25 | "astro": "^4.0.3",
26 | "workbox-build": "^7.0.0"
27 | },
28 | "devDependencies": {
29 | "@astrojs/ts-plugin": "^1.3.1",
30 | "@babel/preset-env": "^7.23.5",
31 | "@babel/preset-typescript": "^7.23.3",
32 | "@types/jest": "^29.5.11",
33 | "@types/node": "^20.10.3",
34 | "@typescript-eslint/eslint-plugin": "^6.13.2",
35 | "@typescript-eslint/parser": "^6.13.2",
36 | "babel-loader": "^9.1.3",
37 | "codecov": "^3.8.3",
38 | "esbuild": "^0.19.8",
39 | "eslint": "^8.55.0",
40 | "eslint-config-prettier": "^9.1.0",
41 | "husky": "^8.0.3",
42 | "jest": "^29.7.0",
43 | "prettier": "^3.1.0",
44 | "prettier-package-json": "^2.8.0",
45 | "typescript": "^5.3.3"
46 | },
47 | "packageManager": "pnpm@8.11.0"
48 | }
49 |
--------------------------------------------------------------------------------
/pnpm-workspace.yaml:
--------------------------------------------------------------------------------
1 | packages:
2 | - "dist"
3 | - "examples/*"
4 |
--------------------------------------------------------------------------------
/public.package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "astrojs-service-worker",
3 | "version": "2.0.0",
4 | "description": "An Astro integration that generates a Service Worker. Powered by Workbox.",
5 | "license": "MIT",
6 | "author": "Tate ",
7 | "repository": {
8 | "type": "git",
9 | "url": "https://github.com/tatethurston/astrojs-service-worker"
10 | },
11 | "type": "module",
12 | "sideEffects": false,
13 | "types": "index.d.ts",
14 | "dependencies": {
15 | "workbox-build": "^6.5.4"
16 | },
17 | "peerDependencies": {
18 | "astro": ">=4.0.0"
19 | },
20 | "keywords": [
21 | "astro",
22 | "astrojs",
23 | "service worker",
24 | "offline",
25 | "astro-component",
26 | "performance"
27 | ],
28 | "main": "./index.js",
29 | "exports": {
30 | "./package.json": "./package.json",
31 | ".": {
32 | "default": "./index.js"
33 | }
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------
1 | import type { AstroIntegration } from "astro";
2 | import { join } from "node:path";
3 | import { fileURLToPath } from "node:url";
4 | import {
5 | generateSW,
6 | type GenerateSWOptions,
7 | type InjectManifestOptions,
8 | } from "workbox-build";
9 |
10 | export interface ServiceWorkerConfig {
11 | /**
12 | * Enable the service worker in local development.
13 | *
14 | * The service worker's precaching of static files will prevent hot module reloading during development.
15 | *
16 | * If `false` then the service worker will not be registered and any previously installed service workers will be cleared.
17 | *
18 | * Defaults to `false`. Recommended: `false` for general development, `true` when testing or debugging your application's service worker.
19 | */
20 | enableInDevelopment?: boolean;
21 | registration?: {
22 | /**
23 | * Autoregister the service worker.
24 | *
25 | * If `false`, then the application must initialize the service worker by invoking `register`. Set this to `false` if you'd like to take control over when you service worker is initialized. You'll then need to add something like the following to your application:
26 | *
27 | * ```javascript
28 | * import { Workbox } from 'workbox-window';
29 | *
30 | * if ('serviceWorker' in navigator) {
31 | * navigator.serviceWorker.register('/service-worker.js')
32 | * }
33 | * ```
34 | *
35 | * Defaults to `true`. Recommended: `true`.
36 | */
37 | autoRegister?: boolean;
38 | };
39 | /**
40 | * Options passed to `worbox-build`. See all available configuration options [here](https://developer.chrome.com/docs/workbox/modules/workbox-build/)
41 | *
42 | * Defaults to `GenerateSW` which will generate a service worker.
43 | */
44 | workbox?: InjectManifestOptions | GenerateSWOptions;
45 | }
46 |
47 | function isInjectManifest(
48 | workboxConfig: InjectManifestOptions | GenerateSWOptions | undefined,
49 | ): workboxConfig is InjectManifestOptions {
50 | return !!workboxConfig && "swSrc" in workboxConfig;
51 | }
52 |
53 | const PKG_NAME = "astrojs-service-worker";
54 |
55 | const createPlugin = (options: ServiceWorkerConfig = {}): AstroIntegration => {
56 | const SW_NAME = "service-worker.js";
57 |
58 | return {
59 | name: PKG_NAME,
60 | hooks: {
61 | "astro:config:setup": ({
62 | command,
63 | injectRoute,
64 | injectScript,
65 | config,
66 | }) => {
67 | const swPath = join(config.base, SW_NAME);
68 | const autoRegister = options.registration?.autoRegister ?? true;
69 | if (autoRegister) {
70 | injectScript(
71 | "head-inline",
72 | `\
73 | if ('serviceWorker' in navigator) {
74 | navigator.serviceWorker.register('${swPath}');
75 | }`,
76 | );
77 | }
78 | const enableInDevelopment = options.enableInDevelopment ?? false;
79 | const isDevelopment = command === "dev";
80 | if (!enableInDevelopment && isDevelopment) {
81 | injectRoute({
82 | pattern: swPath,
83 | entrypoint: fileURLToPath(
84 | new URL("./service-worker.js.js", import.meta.url),
85 | ),
86 | });
87 | }
88 | },
89 | "astro:build:done": async ({ dir }) => {
90 | if (isInjectManifest(options.workbox)) {
91 | console.error(
92 | "[astrojs-service-worker] injectManifest is not supported at this time. If you would like it to be supported, please open an issue at https://github.com/tatethurston/astrojs-service-worker/issues/new",
93 | );
94 | return;
95 | }
96 | const out = fileURLToPath(dir);
97 |
98 | const defaults = {
99 | cleanupOutdatedCaches: true,
100 | clientsClaim: true,
101 | globDirectory: out,
102 | globPatterns: ["**/*"],
103 | skipWaiting: true,
104 | sourcemap: false,
105 | swDest: join(out, SW_NAME),
106 | };
107 |
108 | try {
109 | await generateSW({
110 | ...defaults,
111 | ...options.workbox,
112 | });
113 | } catch (e) {
114 | console.error(e);
115 | }
116 | },
117 | },
118 | };
119 | };
120 |
121 | export default createPlugin;
122 |
--------------------------------------------------------------------------------
/src/noop-service-worker.js:
--------------------------------------------------------------------------------
1 | /* eslint-disable no-undef */
2 | self.addEventListener("install", () => {
3 | self.skipWaiting();
4 | });
5 |
6 | self.addEventListener("activate", (event) => {
7 | event.waitUntil(clients.claim());
8 | });
9 |
10 | console.info(
11 | "[astrojs-service-worker] This is a noop service worker for local development. This ensures that a previously installed service worker is ejected. Your configured service worker will be generated in production builds. If you want to inspect the production service worker locally, you can run `astro build` and then `astro preview`. Alternatively, you can opt into production service worker generation in local development by setting `serviceWorker.enableInDevelopment: true` in your astro.config.mjs. See https://github.com/tatethurston/astrojs-service-worker for configuration options.",
12 | );
13 |
--------------------------------------------------------------------------------
/src/service-worker.js.js:
--------------------------------------------------------------------------------
1 | import { readFile } from "node:fs/promises";
2 | import { fileURLToPath } from "node:url";
3 |
4 | export async function GET() {
5 | const sw = await readFile(
6 | // eslint-disable-next-line no-undef
7 | fileURLToPath(new URL("./noop-service-worker.js", import.meta.url)),
8 | {
9 | encoding: "utf8",
10 | },
11 | );
12 |
13 | const headers = new Headers();
14 | headers.append("content-type", "application/javascript;charset=utf-8");
15 | return new Response(sw, { headers });
16 | }
17 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "allowJs": true,
4 | "esModuleInterop": true,
5 | "forceConsistentCasingInFileNames": true,
6 | "isolatedModules": true,
7 | "module": "ESNext",
8 | "moduleResolution": "Node",
9 | "noEmitOnError": false,
10 | "outDir": "dist",
11 | "resolveJsonModule": true,
12 | "rootDir": "src",
13 | "skipLibCheck": true,
14 | "sourceMap": false,
15 | "strict": true,
16 | "declaration": true,
17 | "target": "ESNext",
18 | "plugins": [
19 | {
20 | "name": "@astrojs/ts-plugin"
21 | }
22 | ]
23 | },
24 | "include": ["src/**/*"]
25 | }
26 |
--------------------------------------------------------------------------------