tempest-react-sdk 0.8.0 → 0.9.0
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 +4 -4
- package/bin/lib/openapi/generate.mjs +259 -0
- package/bin/lib/openapi/generate.test.mjs +129 -0
- package/bin/lib/openapi/load.mjs +24 -0
- package/bin/lib/openapi/schema-to-zod.mjs +123 -0
- package/bin/lib/openapi/schema-to-zod.test.mjs +81 -0
- package/bin/tempest.mjs +84 -2
- package/dist/sw.cjs +1 -1
- package/dist/sw.cjs.map +1 -1
- package/dist/sw.d.ts +130 -0
- package/dist/sw.js +327 -61
- package/dist/sw.js.map +1 -1
- package/dist/tempest-react-sdk.cjs +3 -3
- package/dist/tempest-react-sdk.d.ts +130 -0
- package/dist/tempest-react-sdk.js +36 -32
- package/dist/vite.cjs +3 -1
- package/dist/vite.cjs.map +1 -1
- package/dist/vite.d.ts +136 -0
- package/dist/vite.js +253 -34
- package/dist/vite.js.map +1 -1
- package/package.json +1 -1
- package/template-pwa/index.html +1 -1
- package/template-pwa/package.json +3 -0
- package/template-pwa/public/manifest.webmanifest +6 -6
- package/template-pwa/src/main.tsx +17 -24
- package/template-pwa/src/sw.ts +44 -9
- package/template-pwa/vite.config.ts +21 -0
- package/template-pwa/public/icon-maskable.svg +0 -4
package/bin/tempest.mjs
CHANGED
|
@@ -8,8 +8,11 @@
|
|
|
8
8
|
// tempest --help | --version
|
|
9
9
|
import { spawnSync } from "node:child_process";
|
|
10
10
|
import { existsSync, readFileSync } from "node:fs";
|
|
11
|
-
import {
|
|
11
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
12
|
+
import { dirname, join, resolve } from "node:path";
|
|
12
13
|
import { fileURLToPath } from "node:url";
|
|
14
|
+
import { generate } from "./lib/openapi/generate.mjs";
|
|
15
|
+
import { loadSpec } from "./lib/openapi/load.mjs";
|
|
13
16
|
|
|
14
17
|
const ROOT = process.cwd();
|
|
15
18
|
const SELF_DIR = resolve(fileURLToPath(import.meta.url), "..");
|
|
@@ -234,6 +237,70 @@ function format(paths) {
|
|
|
234
237
|
return run(requireBin("prettier"), ["--write", ...(paths.length ? paths : ["."])]);
|
|
235
238
|
}
|
|
236
239
|
|
|
240
|
+
// -------------------------------------------------------------- gen api ----
|
|
241
|
+
|
|
242
|
+
/** Parse `--out <dir>` from the argv tail. */
|
|
243
|
+
function parseOut(args, fallback) {
|
|
244
|
+
const i = args.indexOf("--out");
|
|
245
|
+
return i >= 0 && args[i + 1] ? args[i + 1] : fallback;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* `tempest gen api <url|file> [--out src/api]` — generate Zod schemas, TS types
|
|
250
|
+
* and a service class per route-group from an OpenAPI spec.
|
|
251
|
+
*/
|
|
252
|
+
async function genApi(args) {
|
|
253
|
+
const source = args.find((a) => !a.startsWith("--") && a !== "api");
|
|
254
|
+
if (!source) {
|
|
255
|
+
console.error(
|
|
256
|
+
`${c.red}✗ Missing OpenAPI source.${c.reset} Usage: tempest gen api <url|file> [--out src/api]`,
|
|
257
|
+
);
|
|
258
|
+
return 1;
|
|
259
|
+
}
|
|
260
|
+
const outDir = resolve(ROOT, parseOut(args, "src/api"));
|
|
261
|
+
console.log(`${c.dim}→ loading ${source}${c.reset}`);
|
|
262
|
+
const doc = await loadSpec(source);
|
|
263
|
+
const { files, tags } = generate(doc);
|
|
264
|
+
|
|
265
|
+
for (const [rel, contents] of Object.entries(files)) {
|
|
266
|
+
const dest = join(outDir, rel);
|
|
267
|
+
await mkdir(dirname(dest), { recursive: true });
|
|
268
|
+
await writeFile(dest, contents);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
console.log(
|
|
272
|
+
`\n${c.green}✓ Generated${c.reset} ${Object.keys(files).length} files for ${tags.length} route group(s): ${c.bold}${tags.join(", ")}${c.reset}`,
|
|
273
|
+
);
|
|
274
|
+
console.log(` ${c.dim}out: ${outDir}${c.reset}`);
|
|
275
|
+
const prettier = localBin("prettier");
|
|
276
|
+
if (prettier) {
|
|
277
|
+
console.log(`${c.dim}→ prettier --write ${parseOut(args, "src/api")}${c.reset}`);
|
|
278
|
+
run(prettier, ["--write", parseOut(args, "src/api")]);
|
|
279
|
+
}
|
|
280
|
+
console.log(`\n${c.dim}Inject an ApiClient into a service:${c.reset}`);
|
|
281
|
+
console.log(` import { createApiClient } from "tempest-react-sdk";`);
|
|
282
|
+
if (tags[0]) {
|
|
283
|
+
const cls = tags[0].replace(/[^a-zA-Z0-9]+(.)?/g, (_, ch) => (ch ? ch.toUpperCase() : ""));
|
|
284
|
+
const Cls = cls.charAt(0).toUpperCase() + cls.slice(1) + "Service";
|
|
285
|
+
console.log(` import { ${Cls} } from "@/api/${tags[0].toLowerCase()}";`);
|
|
286
|
+
console.log(
|
|
287
|
+
` const svc = new ${Cls}(createApiClient({ baseURL: import.meta.env.VITE_API_URL }));`,
|
|
288
|
+
);
|
|
289
|
+
}
|
|
290
|
+
return 0;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function gen(args) {
|
|
294
|
+
const what = args[0];
|
|
295
|
+
if (what !== "api") {
|
|
296
|
+
console.error(
|
|
297
|
+
`${c.red}✗ Unknown gen target: ${what ?? "(none)"}${c.reset} — only \`gen api\` is supported.`,
|
|
298
|
+
);
|
|
299
|
+
return 1;
|
|
300
|
+
}
|
|
301
|
+
return genApi(args.slice(1));
|
|
302
|
+
}
|
|
303
|
+
|
|
237
304
|
// ------------------------------------------------------------------ main ----
|
|
238
305
|
|
|
239
306
|
function usage() {
|
|
@@ -248,6 +315,8 @@ ${c.bold}Commands${c.reset}
|
|
|
248
315
|
${c.bold}lint${c.reset} [paths] Run ESLint (report only)
|
|
249
316
|
${c.bold}fix${c.reset} [paths] ESLint --fix (sort imports, remove unused, tidy whitespace) + Prettier
|
|
250
317
|
${c.bold}format${c.reset} [paths] Prettier --write
|
|
318
|
+
${c.bold}gen api${c.reset} <src> Generate Zod schemas + types + service classes from an OpenAPI spec
|
|
319
|
+
(e.g. tempest gen api http://127.0.0.1:8000/openapi.json --out src/api)
|
|
251
320
|
|
|
252
321
|
${c.bold}Options${c.reset}
|
|
253
322
|
-h, --help Show this help
|
|
@@ -271,6 +340,7 @@ const commands = {
|
|
|
271
340
|
lint: () => lint(rest),
|
|
272
341
|
fix: () => fix(rest),
|
|
273
342
|
format: () => format(rest),
|
|
343
|
+
gen: () => gen(rest),
|
|
274
344
|
};
|
|
275
345
|
|
|
276
346
|
if (!commands[cmd]) {
|
|
@@ -279,4 +349,16 @@ if (!commands[cmd]) {
|
|
|
279
349
|
process.exit(1);
|
|
280
350
|
}
|
|
281
351
|
|
|
282
|
-
|
|
352
|
+
const result = commands[cmd]();
|
|
353
|
+
if (result instanceof Promise) {
|
|
354
|
+
result
|
|
355
|
+
.then((code) => process.exit(code))
|
|
356
|
+
.catch((err) => {
|
|
357
|
+
console.error(
|
|
358
|
+
`${c.red}✗ ${err instanceof Error ? err.message : String(err)}${c.reset}`,
|
|
359
|
+
);
|
|
360
|
+
process.exit(1);
|
|
361
|
+
});
|
|
362
|
+
} else {
|
|
363
|
+
process.exit(result);
|
|
364
|
+
}
|
package/dist/sw.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});async function
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});async function W(t){if(typeof navigator>"u"||!("serviceWorker"in navigator))return null;try{const e=await navigator.serviceWorker.register(t.url,{scope:t.scope});return e.active&&t.onReady?.(e),e.addEventListener("updatefound",()=>{const a=e.installing;a&&a.addEventListener("statechange",()=>{a.state==="installed"&&navigator.serviceWorker.controller&&t.onUpdate?.(a,e)})}),e}catch(e){return t.onError?.(e),null}}function L(t){t.postMessage({type:"SKIP_WAITING"})}async function N(){if(typeof navigator>"u"||!("serviceWorker"in navigator))return 0;const t=await navigator.serviceWorker.getRegistrations();let e=0;for(const a of t)await a.unregister()&&(e+=1);return e}function w(){return globalThis}function P(t={}){const e=w(),{defaultTitle:a="Notificação",defaultIcon:n,defaultBadge:c,transform:i}=t;e.addEventListener("push",r=>{if(!r.data)return;let s;try{s=r.data.json()}catch{s={title:a,body:r.data.text()}}const o=i?i(s):s;if(!o)return;const l=o.title??a,u={body:o.body,icon:o.icon??n,badge:o.badge??c,image:o.image,tag:o.tag,data:{url:o.url??"/",...o.data??{}}};r.waitUntil(e.registration.showNotification(l,u))})}function T(t={}){const e=w(),a=t.resolveUrl??(n=>{if(typeof n=="string")return n;if(n&&typeof n=="object"&&"url"in n){const c=n.url;return typeof c=="string"?c:"/"}return"/"});e.addEventListener("notificationclick",n=>{n.notification.close();const c=a(n.notification.data);n.waitUntil((async()=>{const i=await e.clients.matchAll({type:"window",includeUncontrolled:!0});for(const r of i)if(r.url.includes(c))return r.focus();return e.clients.openWindow(c)})())})}function U(){const t=w();t.addEventListener("message",e=>{e.data?.type==="SKIP_WAITING"&&t.skipWaiting()})}function v(){return globalThis}let h="";const p=new Set;function R(t,e){if(!e)return!1;const a=t.headers.get("date");return a?(Date.now()-new Date(a).getTime())/1e3>e:!1}async function g(t,e){if(!e)return;const a=await caches.open(t),n=await a.keys();if(!(n.length<=e))for(const c of n.slice(0,n.length-e))await a.delete(c)}async function x(t,e){const a=await caches.open(e.cacheName),n=await a.match(t);if(n&&!R(n,e.maxAgeSeconds))return n;const c=await fetch(t);return c.ok&&(await a.put(t,c.clone()),await g(e.cacheName,e.maxEntries)),c}async function A(t,e){const a=await caches.open(e.cacheName),n=(async()=>{const i=await fetch(t);return i.ok&&(await a.put(t,i.clone()),await g(e.cacheName,e.maxEntries)),i})(),c=(e.networkTimeoutSeconds??0)*1e3;try{if(c>0){const i=new Promise((r,s)=>setTimeout(()=>s(new Error("network-timeout")),c));return await Promise.race([n,i])}return await n}catch{const i=await a.match(t);if(i)return i;throw new Error("network-first: no network and no cache")}}async function $(t,e){const a=await caches.open(e.cacheName),n=await a.match(t),c=fetch(t).then(async r=>(r.ok&&(await a.put(t,r.clone()),await g(e.cacheName,e.maxEntries)),r)).catch(()=>{});if(n&&!R(n,e.maxAgeSeconds))return n;const i=await c;if(i)return i;if(n)return n;throw new Error("stale-while-revalidate: no network and no cache")}function y(t,e){switch(e.strategy){case"cache-first":return x(t,e);case"network-first":return A(t,e);case"stale-while-revalidate":return $(t,e)}}function D(t,e,a){return typeof t.match=="function"?t.match(e,a):t.match.test(e.href)}async function S(t,e){const a=t.headers.get("range");if(!a)return e;const n=/^bytes=(\d*)-(\d*)$/.exec(a.trim());if(!n||n[1]===""&&n[2]==="")return new Response(null,{status:416,statusText:"Range Not Satisfiable"});const c=await e.clone().arrayBuffer(),i=c.byteLength;let r,s;if(n[1]===""){const u=Number(n[2]);r=Math.max(0,i-u),s=i-1}else r=Number(n[1]),s=n[2]===""?i-1:Math.min(Number(n[2]),i-1);if(r>s||r>=i)return new Response(null,{status:416,statusText:"Range Not Satisfiable",headers:{"Content-Range":`bytes */${i}`}});const o=c.slice(r,s+1),l=new Headers(e.headers);return l.set("Content-Range",`bytes ${r}-${s}/${i}`),l.set("Content-Length",String(o.byteLength)),l.set("Accept-Ranges","bytes"),new Response(o,{status:206,statusText:"Partial Content",headers:l})}function C(t){v().addEventListener("fetch",a=>{const n=a.request;if(n.method!=="GET")return;const c=new URL(n.url),i=t.find(r=>D(r,c,n));if(i){if(i.rangeRequests&&n.headers.has("range")){const r=new Request(n.url,{headers:H(n.headers),credentials:n.credentials,mode:n.mode==="navigate"?"same-origin":n.mode});a.respondWith(y(r,i).then(s=>S(n,s)));return}a.respondWith(y(n,i))}})}function H(t){const e=new Headers(t);return e.delete("range"),e}function j(t={}){const e=v(),{manifestUrl:a="/precache-manifest.json",cacheName:n="tempest-precache",navigateFallback:c="/index.html",navigateFallbackDenylist:i=[],skipWaiting:r=!0}=t;e.addEventListener("install",s=>{s.waitUntil((async()=>{const l=await(await fetch(a,{cache:"no-cache"})).json();h=`${n}-${l.version}`,await(await caches.open(h)).addAll(l.urls);for(const f of l.urls)p.add(new URL(f,e.location.origin).pathname);r&&await e.skipWaiting()})())}),e.addEventListener("activate",s=>{s.waitUntil((async()=>{const o=await caches.keys();await Promise.all(o.filter(l=>l.startsWith(`${n}-`)&&l!==h).map(l=>caches.delete(l))),await e.clients.claim()})())}),e.addEventListener("fetch",s=>{const o=s.request;if(o.method!=="GET")return;const l=new URL(o.url);if(l.origin===e.location.origin){if(o.mode==="navigate"){if(i.some(u=>u.test(l.pathname)))return;s.respondWith((async()=>{try{return await fetch(o)}catch{const f=await(await caches.open(h)).match(c);if(f)return f;throw new Error("offline and no cached app shell")}})());return}p.has(l.pathname)&&s.respondWith((async()=>await(await caches.open(h)).match(o)??fetch(o))())}})}function I(){return globalThis}const d="requests";function m(t){return new Promise((e,a)=>{const n=indexedDB.open(t,1);n.onupgradeneeded=()=>{n.result.createObjectStore(d,{keyPath:"id",autoIncrement:!0})},n.onsuccess=()=>e(n.result),n.onerror=()=>a(n.error)})}function E(t){return new Promise((e,a)=>{t.oncomplete=()=>e(),t.onerror=()=>a(t.error),t.onabort=()=>a(t.error)})}async function M(t,e){const a=await m(t),n=a.transaction(d,"readwrite");n.objectStore(d).add(e),await E(n),a.close()}async function q(t){const e=await m(t),a=e.transaction(d,"readonly"),n=await new Promise((c,i)=>{const r=a.objectStore(d).getAll();r.onsuccess=()=>c(r.result),r.onerror=()=>i(r.error)});return e.close(),n}async function k(t,e){const a=await m(t),n=a.transaction(d,"readwrite");n.objectStore(d).delete(e),await E(n),a.close()}async function B(t,e){const a=await t.clone().arrayBuffer();return{url:t.url,method:t.method,headers:[...t.headers.entries()],body:a.byteLength>0?a:null,timestamp:e}}function G(t){return new Request(t.url,{method:t.method,headers:t.headers,body:t.body??void 0})}async function b(t,e,a){const n=await q(t);let c=0;for(const i of n)if(i.id!==void 0){if(a-i.timestamp>e){await k(t,i.id);continue}try{const r=await fetch(G(i));r.ok||r.status>=400&&r.status<500?await k(t,i.id):c+=1}catch{c+=1}}if(c>0)throw new Error(`background-sync: ${c} request(s) still pending`)}function F(t,e,a){return t?typeof t=="function"?t(e,a):t.test(e.href):!0}function O(t={}){const e=I(),{match:a,queueName:n="tempest-bg-sync",maxRetentionMinutes:c=1440}=t,i=c*60*1e3;e.addEventListener("fetch",r=>{const s=r.request;if(s.method==="GET"||s.method==="HEAD")return;const o=new URL(s.url);F(a,o,s)&&r.respondWith(fetch(s.clone()).catch(async l=>{const u=await B(s,Date.now());await M(n,u);try{await e.registration.sync?.register(n)}catch{}throw l}))}),e.addEventListener("sync",r=>{r.tag===n&&r.waitUntil(b(n,i,Date.now()))}),e.addEventListener("fetch",r=>{e.registration.sync||r.request.method==="GET"&&r.waitUntil(b(n,i,Date.now()).catch(()=>{}))})}exports.createPartialResponse=S;exports.installBackgroundSync=O;exports.installNotificationClickHandler=T;exports.installPrecache=j;exports.installPushHandler=P;exports.installRuntimeCache=C;exports.installSkipWaitingListener=U;exports.registerServiceWorker=W;exports.skipWaiting=L;exports.unregisterAllServiceWorkers=N;
|
|
2
2
|
//# sourceMappingURL=sw.cjs.map
|
package/dist/sw.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sw.cjs","sources":["../src/sw/register-service-worker.ts","../src/sw/create-push-handler.ts"],"sourcesContent":["export interface RegisterServiceWorkerOptions {\n /** Public URL of the compiled service worker file (e.g. `/sw.js`). */\n url: string;\n /** SW scope (default: SW directory). */\n scope?: string;\n /** Called once the registration is active. */\n onReady?: (registration: ServiceWorkerRegistration) => void;\n /**\n * Called when a new worker has finished installing while another worker\n * still controls the page. The host app typically prompts the user to\n * reload and then calls {@link skipWaiting} on the returned worker.\n */\n onUpdate?: (waiting: ServiceWorker, registration: ServiceWorkerRegistration) => void;\n /** Called on registration failure. */\n onError?: (error: unknown) => void;\n}\n\n/**\n * Register a service worker with consistent update-detection wiring.\n *\n * Skips silently when the runtime has no `serviceWorker` support. The host\n * app keeps full control over the SW file — this helper only handles the\n * boilerplate around `register()` and `updatefound`.\n *\n * @returns The registration when it succeeds, or `null` when unsupported.\n */\nexport async function registerServiceWorker(\n options: RegisterServiceWorkerOptions,\n): Promise<ServiceWorkerRegistration | null> {\n if (typeof navigator === \"undefined\" || !(\"serviceWorker\" in navigator)) {\n return null;\n }\n\n try {\n const registration = await navigator.serviceWorker.register(options.url, {\n scope: options.scope,\n });\n\n if (registration.active) options.onReady?.(registration);\n\n registration.addEventListener(\"updatefound\", () => {\n const installing = registration.installing;\n if (!installing) return;\n installing.addEventListener(\"statechange\", () => {\n if (installing.state === \"installed\" && navigator.serviceWorker.controller) {\n options.onUpdate?.(installing, registration);\n }\n });\n });\n\n return registration;\n } catch (error) {\n options.onError?.(error);\n return null;\n }\n}\n\n/**\n * Tell a waiting worker to activate immediately. Pair with `onUpdate` to roll\n * out updates after the user confirms a reload prompt.\n */\nexport function skipWaiting(worker: ServiceWorker): void {\n worker.postMessage({ type: \"SKIP_WAITING\" });\n}\n\n/**\n * Unregister all registered service workers for this origin.\n *\n * @returns Number of workers that were unregistered.\n */\nexport async function unregisterAllServiceWorkers(): Promise<number> {\n if (typeof navigator === \"undefined\" || !(\"serviceWorker\" in navigator)) return 0;\n const registrations = await navigator.serviceWorker.getRegistrations();\n let count = 0;\n for (const registration of registrations) {\n const result = await registration.unregister();\n if (result) count += 1;\n }\n return count;\n}\n","/**\n * Service-worker context helpers for handling `push` and `notificationclick`\n * events. Import these inside your own `sw.ts` — they expect to run in the\n * service-worker global scope, not in the main thread.\n *\n * @example\n * /// <reference lib=\"webworker\" />\n * import { installPushHandler, installNotificationClickHandler } from \"tempest-react-sdk\";\n *\n * installPushHandler({ defaultIcon: \"/icons/Logo.png\" });\n * installNotificationClickHandler();\n */\n\ninterface SwGlobal {\n registration: {\n showNotification(title: string, options?: NotificationOptions): Promise<void>;\n };\n clients: {\n matchAll(options: { type: \"window\"; includeUncontrolled?: boolean }): Promise<\n {\n url: string;\n focused: boolean;\n focus(): Promise<unknown>;\n navigate(url: string): Promise<unknown>;\n }[]\n >;\n openWindow(url: string): Promise<unknown>;\n };\n addEventListener(\n type: \"push\",\n listener: (event: {\n data: { json(): unknown; text(): string } | null;\n waitUntil(promise: Promise<unknown>): void;\n }) => void,\n ): void;\n addEventListener(\n type: \"notificationclick\",\n listener: (event: {\n notification: { close(): void; data?: unknown };\n waitUntil(promise: Promise<unknown>): void;\n }) => void,\n ): void;\n skipWaiting(): Promise<void>;\n}\n\nfunction getSwScope(): SwGlobal {\n return globalThis as unknown as SwGlobal;\n}\n\nexport interface PushPayload {\n title?: string;\n body?: string;\n icon?: string;\n badge?: string;\n image?: string;\n tag?: string;\n url?: string;\n /** Arbitrary extra data forwarded to `event.notification.data`. */\n data?: Record<string, unknown>;\n}\n\nexport interface InstallPushHandlerOptions {\n /** Title used when the payload omits one. */\n defaultTitle?: string;\n /** Icon used when the payload omits one. */\n defaultIcon?: string;\n /** Badge image (mobile). */\n defaultBadge?: string;\n /**\n * Transform the raw payload before showing the notification. Return `null`\n * to suppress the notification entirely (e.g. silent pings).\n */\n transform?: (payload: PushPayload) => PushPayload | null;\n}\n\n/**\n * Install a `push` event listener that parses the payload as JSON (with a\n * plain-text fallback) and shows a notification.\n */\nexport function installPushHandler(options: InstallPushHandlerOptions = {}): void {\n const sw = getSwScope();\n const { defaultTitle = \"Notificação\", defaultIcon, defaultBadge, transform } = options;\n\n sw.addEventListener(\"push\", (event) => {\n if (!event.data) return;\n\n let raw: PushPayload;\n try {\n raw = event.data.json() as PushPayload;\n } catch {\n raw = { title: defaultTitle, body: event.data.text() };\n }\n\n const payload = transform ? transform(raw) : raw;\n if (!payload) return;\n\n const title = payload.title ?? defaultTitle;\n const notification: NotificationOptions & { image?: string } = {\n body: payload.body,\n icon: payload.icon ?? defaultIcon,\n badge: payload.badge ?? defaultBadge,\n image: payload.image,\n tag: payload.tag,\n data: { url: payload.url ?? \"/\", ...(payload.data ?? {}) },\n };\n\n event.waitUntil(sw.registration.showNotification(title, notification));\n });\n}\n\nexport interface InstallNotificationClickHandlerOptions {\n /** Resolve the destination URL from the notification data. Default: `data.url`. */\n resolveUrl?: (data: unknown) => string;\n}\n\n/**\n * Install a `notificationclick` handler that focuses an existing client when\n * possible and falls back to opening a new window.\n */\nexport function installNotificationClickHandler(\n options: InstallNotificationClickHandlerOptions = {},\n): void {\n const sw = getSwScope();\n const resolveUrl =\n options.resolveUrl ??\n ((data: unknown) => {\n if (typeof data === \"string\") return data;\n if (data && typeof data === \"object\" && \"url\" in data) {\n const url = (data as Record<string, unknown>).url;\n return typeof url === \"string\" ? url : \"/\";\n }\n return \"/\";\n });\n\n sw.addEventListener(\"notificationclick\", (event) => {\n event.notification.close();\n const target = resolveUrl(event.notification.data);\n\n event.waitUntil(\n (async () => {\n const clients = await sw.clients.matchAll({\n type: \"window\",\n includeUncontrolled: true,\n });\n for (const client of clients) {\n if (client.url.includes(target)) {\n return client.focus();\n }\n }\n return sw.clients.openWindow(target);\n })(),\n );\n });\n}\n\n/**\n * Install a `message` listener that activates a waiting worker when the host\n * app sends `{ type: \"SKIP_WAITING\" }`.\n */\nexport function installSkipWaitingListener(): void {\n const sw = getSwScope() as SwGlobal & {\n addEventListener(\n type: \"message\",\n listener: (event: { data?: { type?: string } }) => void,\n ): void;\n };\n sw.addEventListener(\"message\", (event) => {\n if (event.data?.type === \"SKIP_WAITING\") {\n void sw.skipWaiting();\n }\n });\n}\n"],"names":["registerServiceWorker","options","registration","installing","error","skipWaiting","worker","unregisterAllServiceWorkers","registrations","count","getSwScope","installPushHandler","sw","defaultTitle","defaultIcon","defaultBadge","transform","event","raw","payload","title","notification","installNotificationClickHandler","resolveUrl","data","url","target","clients","client","installSkipWaitingListener"],"mappings":"gFA0BA,eAAsBA,EAClBC,EACyC,CACzC,GAAI,OAAO,UAAc,KAAe,EAAE,kBAAmB,WACzD,OAAO,KAGX,GAAI,CACA,MAAMC,EAAe,MAAM,UAAU,cAAc,SAASD,EAAQ,IAAK,CACrE,MAAOA,EAAQ,KAAA,CAClB,EAED,OAAIC,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,IAAKA,EAAQ,KAAO,IAAK,GAAIA,EAAQ,MAAQ,CAAA,CAAC,CAAG,EAG7DF,EAAM,UAAUL,EAAG,aAAa,iBAAiBQ,EAAOC,CAAY,CAAC,CACzE,CAAC,CACL,CAWO,SAASC,EACZrB,EAAkD,GAC9C,CACJ,MAAMW,EAAKF,EAAA,EACLa,EACFtB,EAAQ,aACNuB,GAAkB,CAChB,GAAI,OAAOA,GAAS,SAAU,OAAOA,EACrC,GAAIA,GAAQ,OAAOA,GAAS,UAAY,QAASA,EAAM,CACnD,MAAMC,EAAOD,EAAiC,IAC9C,OAAO,OAAOC,GAAQ,SAAWA,EAAM,GAC3C,CACA,MAAO,GACX,GAEJb,EAAG,iBAAiB,oBAAsBK,GAAU,CAChDA,EAAM,aAAa,MAAA,EACnB,MAAMS,EAASH,EAAWN,EAAM,aAAa,IAAI,EAEjDA,EAAM,WACD,SAAY,CACT,MAAMU,EAAU,MAAMf,EAAG,QAAQ,SAAS,CACtC,KAAM,SACN,oBAAqB,EAAA,CACxB,EACD,UAAWgB,KAAUD,EACjB,GAAIC,EAAO,IAAI,SAASF,CAAM,EAC1B,OAAOE,EAAO,MAAA,EAGtB,OAAOhB,EAAG,QAAQ,WAAWc,CAAM,CACvC,GAAA,CAAG,CAEX,CAAC,CACL,CAMO,SAASG,GAAmC,CAC/C,MAAMjB,EAAKF,EAAA,EAMXE,EAAG,iBAAiB,UAAYK,GAAU,CAClCA,EAAM,MAAM,OAAS,gBAChBL,EAAG,YAAA,CAEhB,CAAC,CACL"}
|
|
1
|
+
{"version":3,"file":"sw.cjs","sources":["../src/sw/register-service-worker.ts","../src/sw/create-push-handler.ts","../src/sw/cache.ts","../src/sw/background-sync.ts"],"sourcesContent":["export interface RegisterServiceWorkerOptions {\n /** Public URL of the compiled service worker file (e.g. `/sw.js`). */\n url: string;\n /** SW scope (default: SW directory). */\n scope?: string;\n /** Called once the registration is active. */\n onReady?: (registration: ServiceWorkerRegistration) => void;\n /**\n * Called when a new worker has finished installing while another worker\n * still controls the page. The host app typically prompts the user to\n * reload and then calls {@link skipWaiting} on the returned worker.\n */\n onUpdate?: (waiting: ServiceWorker, registration: ServiceWorkerRegistration) => void;\n /** Called on registration failure. */\n onError?: (error: unknown) => void;\n}\n\n/**\n * Register a service worker with consistent update-detection wiring.\n *\n * Skips silently when the runtime has no `serviceWorker` support. The host\n * app keeps full control over the SW file — this helper only handles the\n * boilerplate around `register()` and `updatefound`.\n *\n * @returns The registration when it succeeds, or `null` when unsupported.\n */\nexport async function registerServiceWorker(\n options: RegisterServiceWorkerOptions,\n): Promise<ServiceWorkerRegistration | null> {\n if (typeof navigator === \"undefined\" || !(\"serviceWorker\" in navigator)) {\n return null;\n }\n\n try {\n const registration = await navigator.serviceWorker.register(options.url, {\n scope: options.scope,\n });\n\n if (registration.active) options.onReady?.(registration);\n\n registration.addEventListener(\"updatefound\", () => {\n const installing = registration.installing;\n if (!installing) return;\n installing.addEventListener(\"statechange\", () => {\n if (installing.state === \"installed\" && navigator.serviceWorker.controller) {\n options.onUpdate?.(installing, registration);\n }\n });\n });\n\n return registration;\n } catch (error) {\n options.onError?.(error);\n return null;\n }\n}\n\n/**\n * Tell a waiting worker to activate immediately. Pair with `onUpdate` to roll\n * out updates after the user confirms a reload prompt.\n */\nexport function skipWaiting(worker: ServiceWorker): void {\n worker.postMessage({ type: \"SKIP_WAITING\" });\n}\n\n/**\n * Unregister all registered service workers for this origin.\n *\n * @returns Number of workers that were unregistered.\n */\nexport async function unregisterAllServiceWorkers(): Promise<number> {\n if (typeof navigator === \"undefined\" || !(\"serviceWorker\" in navigator)) return 0;\n const registrations = await navigator.serviceWorker.getRegistrations();\n let count = 0;\n for (const registration of registrations) {\n const result = await registration.unregister();\n if (result) count += 1;\n }\n return count;\n}\n","/**\n * Service-worker context helpers for handling `push` and `notificationclick`\n * events. Import these inside your own `sw.ts` — they expect to run in the\n * service-worker global scope, not in the main thread.\n *\n * @example\n * /// <reference lib=\"webworker\" />\n * import { installPushHandler, installNotificationClickHandler } from \"tempest-react-sdk\";\n *\n * installPushHandler({ defaultIcon: \"/icons/Logo.png\" });\n * installNotificationClickHandler();\n */\n\ninterface SwGlobal {\n registration: {\n showNotification(title: string, options?: NotificationOptions): Promise<void>;\n };\n clients: {\n matchAll(options: { type: \"window\"; includeUncontrolled?: boolean }): Promise<\n {\n url: string;\n focused: boolean;\n focus(): Promise<unknown>;\n navigate(url: string): Promise<unknown>;\n }[]\n >;\n openWindow(url: string): Promise<unknown>;\n };\n addEventListener(\n type: \"push\",\n listener: (event: {\n data: { json(): unknown; text(): string } | null;\n waitUntil(promise: Promise<unknown>): void;\n }) => void,\n ): void;\n addEventListener(\n type: \"notificationclick\",\n listener: (event: {\n notification: { close(): void; data?: unknown };\n waitUntil(promise: Promise<unknown>): void;\n }) => void,\n ): void;\n skipWaiting(): Promise<void>;\n}\n\nfunction getSwScope(): SwGlobal {\n return globalThis as unknown as SwGlobal;\n}\n\nexport interface PushPayload {\n title?: string;\n body?: string;\n icon?: string;\n badge?: string;\n image?: string;\n tag?: string;\n url?: string;\n /** Arbitrary extra data forwarded to `event.notification.data`. */\n data?: Record<string, unknown>;\n}\n\nexport interface InstallPushHandlerOptions {\n /** Title used when the payload omits one. */\n defaultTitle?: string;\n /** Icon used when the payload omits one. */\n defaultIcon?: string;\n /** Badge image (mobile). */\n defaultBadge?: string;\n /**\n * Transform the raw payload before showing the notification. Return `null`\n * to suppress the notification entirely (e.g. silent pings).\n */\n transform?: (payload: PushPayload) => PushPayload | null;\n}\n\n/**\n * Install a `push` event listener that parses the payload as JSON (with a\n * plain-text fallback) and shows a notification.\n */\nexport function installPushHandler(options: InstallPushHandlerOptions = {}): void {\n const sw = getSwScope();\n const { defaultTitle = \"Notificação\", defaultIcon, defaultBadge, transform } = options;\n\n sw.addEventListener(\"push\", (event) => {\n if (!event.data) return;\n\n let raw: PushPayload;\n try {\n raw = event.data.json() as PushPayload;\n } catch {\n raw = { title: defaultTitle, body: event.data.text() };\n }\n\n const payload = transform ? transform(raw) : raw;\n if (!payload) return;\n\n const title = payload.title ?? defaultTitle;\n const notification: NotificationOptions & { image?: string } = {\n body: payload.body,\n icon: payload.icon ?? defaultIcon,\n badge: payload.badge ?? defaultBadge,\n image: payload.image,\n tag: payload.tag,\n data: { url: payload.url ?? \"/\", ...(payload.data ?? {}) },\n };\n\n event.waitUntil(sw.registration.showNotification(title, notification));\n });\n}\n\nexport interface InstallNotificationClickHandlerOptions {\n /** Resolve the destination URL from the notification data. Default: `data.url`. */\n resolveUrl?: (data: unknown) => string;\n}\n\n/**\n * Install a `notificationclick` handler that focuses an existing client when\n * possible and falls back to opening a new window.\n */\nexport function installNotificationClickHandler(\n options: InstallNotificationClickHandlerOptions = {},\n): void {\n const sw = getSwScope();\n const resolveUrl =\n options.resolveUrl ??\n ((data: unknown) => {\n if (typeof data === \"string\") return data;\n if (data && typeof data === \"object\" && \"url\" in data) {\n const url = (data as Record<string, unknown>).url;\n return typeof url === \"string\" ? url : \"/\";\n }\n return \"/\";\n });\n\n sw.addEventListener(\"notificationclick\", (event) => {\n event.notification.close();\n const target = resolveUrl(event.notification.data);\n\n event.waitUntil(\n (async () => {\n const clients = await sw.clients.matchAll({\n type: \"window\",\n includeUncontrolled: true,\n });\n for (const client of clients) {\n if (client.url.includes(target)) {\n return client.focus();\n }\n }\n return sw.clients.openWindow(target);\n })(),\n );\n });\n}\n\n/**\n * Install a `message` listener that activates a waiting worker when the host\n * app sends `{ type: \"SKIP_WAITING\" }`.\n */\nexport function installSkipWaitingListener(): void {\n const sw = getSwScope() as SwGlobal & {\n addEventListener(\n type: \"message\",\n listener: (event: { data?: { type?: string } }) => void,\n ): void;\n };\n sw.addEventListener(\"message\", (event) => {\n if (event.data?.type === \"SKIP_WAITING\") {\n void sw.skipWaiting();\n }\n });\n}\n","/**\n * Service-worker caching helpers — a small, dependency-free subset of what\n * Workbox provides: precaching of the build's app shell (so the app launches\n * offline) plus runtime caching strategies for fonts, APIs and images.\n *\n * Import these inside your own `sw.ts`. They run in the service-worker global\n * scope, not the main thread. Pair `installPrecache` with the\n * `tempestPwaManifest()` Vite plugin (from `tempest-react-sdk/vite`), which\n * emits the `precache-manifest.json` this reads at install time.\n *\n * @example\n * /// <reference lib=\"webworker\" />\n * import { installRuntimeCache, installPrecache } from \"tempest-react-sdk/sw\";\n *\n * // Register specific routes FIRST so they win over the precache catch-all.\n * installRuntimeCache([\n * { match: /\\/api\\//, strategy: \"network-first\", cacheName: \"api\", maxAgeSeconds: 300 },\n * ]);\n * installPrecache();\n */\n\n/** Minimal shape of the events we touch, to avoid pulling in `lib.webworker`. */\ninterface ExtendableEventLike {\n waitUntil(promise: Promise<unknown>): void;\n}\n\ninterface FetchEventLike extends ExtendableEventLike {\n request: Request;\n respondWith(response: Response | Promise<Response>): void;\n}\n\ninterface CacheSwGlobal {\n addEventListener(type: \"install\", listener: (event: ExtendableEventLike) => void): void;\n addEventListener(type: \"activate\", listener: (event: ExtendableEventLike) => void): void;\n addEventListener(type: \"fetch\", listener: (event: FetchEventLike) => void): void;\n clients: { claim(): Promise<void> };\n skipWaiting(): Promise<void>;\n location: { origin: string };\n}\n\nfunction getSwScope(): CacheSwGlobal {\n return globalThis as unknown as CacheSwGlobal;\n}\n\n/** Caching strategy for a runtime route. Mirrors the common Workbox trio. */\nexport type RuntimeStrategy = \"cache-first\" | \"network-first\" | \"stale-while-revalidate\";\n\n/** A single runtime-caching rule, matched against each `GET` request. */\nexport interface RuntimeRoute {\n /** A `RegExp` tested against the full URL, or a predicate over the parsed URL. */\n match: RegExp | ((url: URL, request: Request) => boolean);\n /** How to resolve a match. */\n strategy: RuntimeStrategy;\n /** Cache bucket name for this route. */\n cacheName: string;\n /** Trim the cache to at most this many entries (FIFO) after each write. */\n maxEntries?: number;\n /** Treat a cached response older than this (seconds) as a miss. */\n maxAgeSeconds?: number;\n /** For `network-first`: fall back to cache after this timeout (seconds). */\n networkTimeoutSeconds?: number;\n /**\n * Serve HTTP `Range` requests (206 Partial Content) by slicing the cached\n * full response. Enable for audio/video so seeking works offline. The full\n * resource is cached once (the `Range` header is stripped before caching).\n */\n rangeRequests?: boolean;\n}\n\n/** Options for {@link installPrecache}. */\nexport interface InstallPrecacheOptions {\n /** URL of the manifest emitted by `tempestPwaManifest()`. Default `/precache-manifest.json`. */\n manifestUrl?: string;\n /** Cache name prefix; the manifest `version` is appended. Default `tempest-precache`. */\n cacheName?: string;\n /** App-shell document served for navigation requests offline. Default `/index.html`. */\n navigateFallback?: string;\n /** Navigation paths that should NOT use the fallback (e.g. `[/^\\/api\\//]`). */\n navigateFallbackDenylist?: RegExp[];\n /** Activate the new worker immediately after precaching. Default `true`. */\n skipWaiting?: boolean;\n}\n\ninterface PrecacheManifest {\n version: string;\n urls: string[];\n}\n\nlet precacheName = \"\";\nconst precachedPaths = new Set<string>();\n\n/** Whether a cached response has aged past `maxAgeSeconds` (best-effort, via `Date`). */\nfunction isExpired(response: Response, maxAgeSeconds?: number): boolean {\n if (!maxAgeSeconds) return false;\n const dateHeader = response.headers.get(\"date\");\n if (!dateHeader) return false;\n const age = (Date.now() - new Date(dateHeader).getTime()) / 1000;\n return age > maxAgeSeconds;\n}\n\n/** Drop oldest entries until the cache holds at most `maxEntries`. */\nasync function trimCache(cacheName: string, maxEntries?: number): Promise<void> {\n if (!maxEntries) return;\n const cache = await caches.open(cacheName);\n const keys = await cache.keys();\n if (keys.length <= maxEntries) return;\n for (const key of keys.slice(0, keys.length - maxEntries)) {\n await cache.delete(key);\n }\n}\n\nasync function cacheFirst(request: Request, route: RuntimeRoute): Promise<Response> {\n const cache = await caches.open(route.cacheName);\n const cached = await cache.match(request);\n if (cached && !isExpired(cached, route.maxAgeSeconds)) return cached;\n\n const response = await fetch(request);\n if (response.ok) {\n await cache.put(request, response.clone());\n await trimCache(route.cacheName, route.maxEntries);\n }\n return response;\n}\n\nasync function networkFirst(request: Request, route: RuntimeRoute): Promise<Response> {\n const cache = await caches.open(route.cacheName);\n\n const network = (async (): Promise<Response> => {\n const response = await fetch(request);\n if (response.ok) {\n await cache.put(request, response.clone());\n await trimCache(route.cacheName, route.maxEntries);\n }\n return response;\n })();\n\n const timeoutMs = (route.networkTimeoutSeconds ?? 0) * 1000;\n try {\n if (timeoutMs > 0) {\n const timeout = new Promise<never>((_, reject) =>\n setTimeout(() => reject(new Error(\"network-timeout\")), timeoutMs),\n );\n return await Promise.race([network, timeout]);\n }\n return await network;\n } catch {\n const cached = await cache.match(request);\n if (cached) return cached;\n throw new Error(\"network-first: no network and no cache\");\n }\n}\n\nasync function staleWhileRevalidate(request: Request, route: RuntimeRoute): Promise<Response> {\n const cache = await caches.open(route.cacheName);\n const cached = await cache.match(request);\n\n const network = fetch(request)\n .then(async (response) => {\n if (response.ok) {\n await cache.put(request, response.clone());\n await trimCache(route.cacheName, route.maxEntries);\n }\n return response;\n })\n .catch(() => undefined);\n\n if (cached && !isExpired(cached, route.maxAgeSeconds)) return cached;\n const response = await network;\n if (response) return response;\n if (cached) return cached;\n throw new Error(\"stale-while-revalidate: no network and no cache\");\n}\n\nfunction runRoute(request: Request, route: RuntimeRoute): Promise<Response> {\n switch (route.strategy) {\n case \"cache-first\":\n return cacheFirst(request, route);\n case \"network-first\":\n return networkFirst(request, route);\n case \"stale-while-revalidate\":\n return staleWhileRevalidate(request, route);\n }\n}\n\nfunction routeMatches(route: RuntimeRoute, url: URL, request: Request): boolean {\n return typeof route.match === \"function\"\n ? route.match(url, request)\n : route.match.test(url.href);\n}\n\n/**\n * Build a `206 Partial Content` response from a full one for an HTTP `Range`\n * request. Supports `bytes=start-end`, open-ended `bytes=start-` and suffix\n * `bytes=-suffixLength`. Returns the original response when there is no usable\n * `Range` header, or a `416` when the range is unsatisfiable.\n *\n * @param request The incoming request (its `Range` header drives the slice).\n * @param response The full (200) response to slice.\n */\nexport async function createPartialResponse(\n request: Request,\n response: Response,\n): Promise<Response> {\n const rangeHeader = request.headers.get(\"range\");\n if (!rangeHeader) return response;\n\n const match = /^bytes=(\\d*)-(\\d*)$/.exec(rangeHeader.trim());\n if (!match || (match[1] === \"\" && match[2] === \"\")) {\n return new Response(null, { status: 416, statusText: \"Range Not Satisfiable\" });\n }\n\n const buffer = await response.clone().arrayBuffer();\n const total = buffer.byteLength;\n\n let start: number;\n let end: number;\n if (match[1] === \"\") {\n // Suffix range: last N bytes.\n const suffix = Number(match[2]);\n start = Math.max(0, total - suffix);\n end = total - 1;\n } else {\n start = Number(match[1]);\n end = match[2] === \"\" ? total - 1 : Math.min(Number(match[2]), total - 1);\n }\n\n if (start > end || start >= total) {\n return new Response(null, {\n status: 416,\n statusText: \"Range Not Satisfiable\",\n headers: { \"Content-Range\": `bytes */${total}` },\n });\n }\n\n const slice = buffer.slice(start, end + 1);\n const headers = new Headers(response.headers);\n headers.set(\"Content-Range\", `bytes ${start}-${end}/${total}`);\n headers.set(\"Content-Length\", String(slice.byteLength));\n headers.set(\"Accept-Ranges\", \"bytes\");\n\n return new Response(slice, {\n status: 206,\n statusText: \"Partial Content\",\n headers,\n });\n}\n\n/**\n * Install a `fetch` handler that resolves matching `GET` requests with the\n * given runtime strategies. Non-matching requests are left untouched (no\n * `respondWith`), so a later {@link installPrecache} can handle them.\n *\n * Register this BEFORE `installPrecache` so specific routes win over the\n * precache catch-all.\n *\n * @param routes Ordered rules; the first whose `match` passes handles the request.\n */\nexport function installRuntimeCache(routes: RuntimeRoute[]): void {\n const sw = getSwScope();\n sw.addEventListener(\"fetch\", (event) => {\n const request = event.request;\n if (request.method !== \"GET\") return;\n\n const url = new URL(request.url);\n const route = routes.find((candidate) => routeMatches(candidate, url, request));\n if (!route) return;\n\n if (route.rangeRequests && request.headers.has(\"range\")) {\n // Cache/serve the FULL resource once (no Range), then slice it.\n const full = new Request(request.url, {\n headers: stripRange(request.headers),\n credentials: request.credentials,\n mode: request.mode === \"navigate\" ? \"same-origin\" : request.mode,\n });\n event.respondWith(\n runRoute(full, route).then((response) => createPartialResponse(request, response)),\n );\n return;\n }\n\n event.respondWith(runRoute(request, route));\n });\n}\n\n/** Copy headers without the `Range` header (so the cached entry is the full file). */\nfunction stripRange(headers: Headers): Headers {\n const out = new Headers(headers);\n out.delete(\"range\");\n return out;\n}\n\n/**\n * Precache the app shell at `install` and serve it offline:\n * - reads `precache-manifest.json` (emitted by `tempestPwaManifest()`),\n * - caches every listed URL under a versioned cache,\n * - on `activate`, deletes stale precache versions and claims open clients,\n * - on `fetch`, serves precached assets cache-first and falls back to the\n * `navigateFallback` document for offline navigations (SPA routing).\n *\n * Same-origin only. Register this LAST, after any {@link installRuntimeCache}.\n */\nexport function installPrecache(options: InstallPrecacheOptions = {}): void {\n const sw = getSwScope();\n const {\n manifestUrl = \"/precache-manifest.json\",\n cacheName = \"tempest-precache\",\n navigateFallback = \"/index.html\",\n navigateFallbackDenylist = [],\n skipWaiting = true,\n } = options;\n\n sw.addEventListener(\"install\", (event) => {\n event.waitUntil(\n (async () => {\n const response = await fetch(manifestUrl, { cache: \"no-cache\" });\n const manifest = (await response.json()) as PrecacheManifest;\n precacheName = `${cacheName}-${manifest.version}`;\n\n const cache = await caches.open(precacheName);\n await cache.addAll(manifest.urls);\n for (const url of manifest.urls) {\n precachedPaths.add(new URL(url, sw.location.origin).pathname);\n }\n if (skipWaiting) await sw.skipWaiting();\n })(),\n );\n });\n\n sw.addEventListener(\"activate\", (event) => {\n event.waitUntil(\n (async () => {\n const keys = await caches.keys();\n await Promise.all(\n keys\n .filter((key) => key.startsWith(`${cacheName}-`) && key !== precacheName)\n .map((key) => caches.delete(key)),\n );\n await sw.clients.claim();\n })(),\n );\n });\n\n sw.addEventListener(\"fetch\", (event) => {\n const request = event.request;\n if (request.method !== \"GET\") return;\n\n const url = new URL(request.url);\n if (url.origin !== sw.location.origin) return;\n\n // SPA navigations: serve the cached app shell when offline.\n if (request.mode === \"navigate\") {\n if (navigateFallbackDenylist.some((re) => re.test(url.pathname))) return;\n event.respondWith(\n (async () => {\n try {\n return await fetch(request);\n } catch {\n const cache = await caches.open(precacheName);\n const shell = await cache.match(navigateFallback);\n if (shell) return shell;\n throw new Error(\"offline and no cached app shell\");\n }\n })(),\n );\n return;\n }\n\n // Precached static assets: cache-first.\n if (precachedPaths.has(url.pathname)) {\n event.respondWith(\n (async () => {\n const cache = await caches.open(precacheName);\n const cached = await cache.match(request);\n return cached ?? fetch(request);\n })(),\n );\n }\n });\n}\n","/**\n * Background-sync helper: queue failed mutating requests (POST/PUT/PATCH/DELETE)\n * while offline and replay them when connectivity returns. A dependency-free\n * take on Workbox's `BackgroundSyncPlugin`, backed by a tiny IndexedDB queue.\n *\n * Import inside your `sw.ts`. Uses the Background Sync API (`registration.sync`)\n * when available, and also replays opportunistically on the next request as a\n * fallback for browsers without it (e.g. Safari).\n *\n * @example\n * import { installBackgroundSync } from \"tempest-react-sdk/sw\";\n *\n * installBackgroundSync({ match: (url) => url.pathname.startsWith(\"/api/\") });\n */\n\ninterface SyncEventLike {\n tag: string;\n waitUntil(promise: Promise<unknown>): void;\n}\n\ninterface BgFetchEventLike {\n request: Request;\n respondWith(response: Response | Promise<Response>): void;\n waitUntil(promise: Promise<unknown>): void;\n}\n\ninterface BgSwGlobal {\n registration: { sync?: { register(tag: string): Promise<void> } };\n addEventListener(type: \"sync\", listener: (event: SyncEventLike) => void): void;\n addEventListener(type: \"fetch\", listener: (event: BgFetchEventLike) => void): void;\n}\n\nfunction getSwScope(): BgSwGlobal {\n return globalThis as unknown as BgSwGlobal;\n}\n\n/** A serialized request stored in the queue. */\ninterface QueuedRequest {\n id?: number;\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n timestamp: number;\n}\n\n/** Options for {@link installBackgroundSync}. */\nexport interface InstallBackgroundSyncOptions {\n /**\n * Which requests to queue on failure. A `RegExp` against the URL or a\n * predicate. Only non-`GET` requests are ever considered. Default: all\n * non-`GET` requests.\n */\n match?: RegExp | ((url: URL, request: Request) => boolean);\n /** IndexedDB database name, also used as the sync tag. Default `tempest-bg-sync`. */\n queueName?: string;\n /** Drop queued requests older than this (minutes) on replay. Default `1440` (24h). */\n maxRetentionMinutes?: number;\n}\n\nconst STORE = \"requests\";\n\nfunction openQueueDb(name: string): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const request = indexedDB.open(name, 1);\n request.onupgradeneeded = () => {\n request.result.createObjectStore(STORE, { keyPath: \"id\", autoIncrement: true });\n };\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n });\n}\n\nfunction txDone(tx: IDBTransaction): Promise<void> {\n return new Promise((resolve, reject) => {\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n tx.onabort = () => reject(tx.error);\n });\n}\n\nasync function enqueue(name: string, entry: QueuedRequest): Promise<void> {\n const db = await openQueueDb(name);\n const tx = db.transaction(STORE, \"readwrite\");\n tx.objectStore(STORE).add(entry);\n await txDone(tx);\n db.close();\n}\n\nasync function readAll(name: string): Promise<QueuedRequest[]> {\n const db = await openQueueDb(name);\n const tx = db.transaction(STORE, \"readonly\");\n const all = await new Promise<QueuedRequest[]>((resolve, reject) => {\n const req = tx.objectStore(STORE).getAll();\n req.onsuccess = () => resolve(req.result as QueuedRequest[]);\n req.onerror = () => reject(req.error);\n });\n db.close();\n return all;\n}\n\nasync function remove(name: string, id: number): Promise<void> {\n const db = await openQueueDb(name);\n const tx = db.transaction(STORE, \"readwrite\");\n tx.objectStore(STORE).delete(id);\n await txDone(tx);\n db.close();\n}\n\nasync function serializeRequest(request: Request, timestamp: number): Promise<QueuedRequest> {\n const buffer = await request.clone().arrayBuffer();\n return {\n url: request.url,\n method: request.method,\n headers: [...request.headers.entries()],\n body: buffer.byteLength > 0 ? buffer : null,\n timestamp,\n };\n}\n\nfunction deserializeRequest(entry: QueuedRequest): Request {\n return new Request(entry.url, {\n method: entry.method,\n headers: entry.headers,\n body: entry.body ?? undefined,\n });\n}\n\n/**\n * Replay every queued request once. Successful (or stale) entries are removed;\n * entries that fail again are kept for the next attempt. Throws if any entry\n * still fails, so a `sync` handler keeps the sync pending.\n */\nasync function replayQueue(name: string, maxRetentionMs: number, now: number): Promise<void> {\n const entries = await readAll(name);\n let pending = 0;\n\n for (const entry of entries) {\n if (entry.id === undefined) continue;\n if (now - entry.timestamp > maxRetentionMs) {\n await remove(name, entry.id);\n continue;\n }\n try {\n const response = await fetch(deserializeRequest(entry));\n if (response.ok || (response.status >= 400 && response.status < 500)) {\n // 2xx = done; 4xx = client error that won't fix itself → drop it.\n await remove(name, entry.id);\n } else {\n pending += 1;\n }\n } catch {\n pending += 1;\n }\n }\n\n if (pending > 0) throw new Error(`background-sync: ${pending} request(s) still pending`);\n}\n\nfunction matches(\n match: InstallBackgroundSyncOptions[\"match\"],\n url: URL,\n request: Request,\n): boolean {\n if (!match) return true;\n return typeof match === \"function\" ? match(url, request) : match.test(url.href);\n}\n\n/**\n * Install the background-sync queue: on a failed mutating request, the request\n * is serialized to IndexedDB and a sync is registered; the original fetch still\n * rejects (so your app can show an offline state), and the request is replayed\n * later when the network returns.\n */\nexport function installBackgroundSync(options: InstallBackgroundSyncOptions = {}): void {\n const sw = getSwScope();\n const { match, queueName = \"tempest-bg-sync\", maxRetentionMinutes = 1440 } = options;\n const maxRetentionMs = maxRetentionMinutes * 60 * 1000;\n\n sw.addEventListener(\"fetch\", (event) => {\n const request = event.request;\n if (request.method === \"GET\" || request.method === \"HEAD\") return;\n\n const url = new URL(request.url);\n if (!matches(match, url, request)) return;\n\n event.respondWith(\n fetch(request.clone()).catch(async (error) => {\n const entry = await serializeRequest(request, Date.now());\n await enqueue(queueName, entry);\n try {\n await sw.registration.sync?.register(queueName);\n } catch {\n // Background Sync API unavailable — opportunistic replay covers it.\n }\n throw error;\n }),\n );\n });\n\n sw.addEventListener(\"sync\", (event) => {\n if (event.tag !== queueName) return;\n event.waitUntil(replayQueue(queueName, maxRetentionMs, Date.now()));\n });\n\n // Fallback for browsers without the Background Sync API: whenever a GET\n // succeeds (a sign we're online), drain the queue opportunistically.\n sw.addEventListener(\"fetch\", (event) => {\n if (sw.registration.sync) return; // native sync will handle it\n if (event.request.method !== \"GET\") return;\n event.waitUntil(replayQueue(queueName, maxRetentionMs, Date.now()).catch(() => undefined));\n });\n}\n"],"names":["registerServiceWorker","options","registration","installing","error","skipWaiting","worker","unregisterAllServiceWorkers","registrations","count","getSwScope","installPushHandler","sw","defaultTitle","defaultIcon","defaultBadge","transform","event","raw","payload","title","notification","installNotificationClickHandler","resolveUrl","data","url","target","clients","client","installSkipWaitingListener","precacheName","precachedPaths","isExpired","response","maxAgeSeconds","dateHeader","trimCache","cacheName","maxEntries","cache","keys","key","cacheFirst","request","route","cached","networkFirst","network","timeoutMs","timeout","_","reject","staleWhileRevalidate","runRoute","routeMatches","createPartialResponse","rangeHeader","match","buffer","total","start","end","suffix","slice","headers","installRuntimeCache","routes","candidate","full","stripRange","out","installPrecache","manifestUrl","navigateFallback","navigateFallbackDenylist","manifest","re","shell","STORE","openQueueDb","name","resolve","txDone","tx","enqueue","entry","db","readAll","all","req","remove","id","serializeRequest","timestamp","deserializeRequest","replayQueue","maxRetentionMs","now","entries","pending","matches","installBackgroundSync","queueName","maxRetentionMinutes"],"mappings":"gFA0BA,eAAsBA,EAClBC,EACyC,CACzC,GAAI,OAAO,UAAc,KAAe,EAAE,kBAAmB,WACzD,OAAO,KAGX,GAAI,CACA,MAAMC,EAAe,MAAM,UAAU,cAAc,SAASD,EAAQ,IAAK,CACrE,MAAOA,EAAQ,KAAA,CAClB,EAED,OAAIC,EAAa,QAAQD,EAAQ,UAAUC,CAAY,EAEvDA,EAAa,iBAAiB,cAAe,IAAM,CAC/C,MAAMC,EAAaD,EAAa,WAC3BC,GACLA,EAAW,iBAAiB,cAAe,IAAM,CACzCA,EAAW,QAAU,aAAe,UAAU,cAAc,YAC5DF,EAAQ,WAAWE,EAAYD,CAAY,CAEnD,CAAC,CACL,CAAC,EAEMA,CACX,OAASE,EAAO,CACZ,OAAAH,EAAQ,UAAUG,CAAK,EAChB,IACX,CACJ,CAMO,SAASC,EAAYC,EAA6B,CACrDA,EAAO,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rF,EAAM,UAAU8E,EAAYO,EAAWN,EAAgB,KAAK,IAAA,CAAK,CAAC,CACtE,CAAC,EAIDpF,EAAG,iBAAiB,QAAUK,GAAU,CAChCL,EAAG,aAAa,MAChBK,EAAM,QAAQ,SAAW,OAC7BA,EAAM,UAAU8E,EAAYO,EAAWN,EAAgB,KAAK,KAAK,EAAE,MAAM,IAAA,EAAe,CAAC,CAC7F,CAAC,CACL"}
|
package/dist/sw.d.ts
CHANGED
|
@@ -1,3 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Build a `206 Partial Content` response from a full one for an HTTP `Range`
|
|
3
|
+
* request. Supports `bytes=start-end`, open-ended `bytes=start-` and suffix
|
|
4
|
+
* `bytes=-suffixLength`. Returns the original response when there is no usable
|
|
5
|
+
* `Range` header, or a `416` when the range is unsatisfiable.
|
|
6
|
+
*
|
|
7
|
+
* @param request The incoming request (its `Range` header drives the slice).
|
|
8
|
+
* @param response The full (200) response to slice.
|
|
9
|
+
*/
|
|
10
|
+
export declare function createPartialResponse(request: Request, response: Response): Promise<Response>;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Install the background-sync queue: on a failed mutating request, the request
|
|
14
|
+
* is serialized to IndexedDB and a sync is registered; the original fetch still
|
|
15
|
+
* rejects (so your app can show an offline state), and the request is replayed
|
|
16
|
+
* later when the network returns.
|
|
17
|
+
*/
|
|
18
|
+
export declare function installBackgroundSync(options?: InstallBackgroundSyncOptions): void;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Background-sync helper: queue failed mutating requests (POST/PUT/PATCH/DELETE)
|
|
22
|
+
* while offline and replay them when connectivity returns. A dependency-free
|
|
23
|
+
* take on Workbox's `BackgroundSyncPlugin`, backed by a tiny IndexedDB queue.
|
|
24
|
+
*
|
|
25
|
+
* Import inside your `sw.ts`. Uses the Background Sync API (`registration.sync`)
|
|
26
|
+
* when available, and also replays opportunistically on the next request as a
|
|
27
|
+
* fallback for browsers without it (e.g. Safari).
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* import { installBackgroundSync } from "tempest-react-sdk/sw";
|
|
31
|
+
*
|
|
32
|
+
* installBackgroundSync({ match: (url) => url.pathname.startsWith("/api/") });
|
|
33
|
+
*/
|
|
34
|
+
/** Options for {@link installBackgroundSync}. */
|
|
35
|
+
export declare interface InstallBackgroundSyncOptions {
|
|
36
|
+
/**
|
|
37
|
+
* Which requests to queue on failure. A `RegExp` against the URL or a
|
|
38
|
+
* predicate. Only non-`GET` requests are ever considered. Default: all
|
|
39
|
+
* non-`GET` requests.
|
|
40
|
+
*/
|
|
41
|
+
match?: RegExp | ((url: URL, request: Request) => boolean);
|
|
42
|
+
/** IndexedDB database name, also used as the sync tag. Default `tempest-bg-sync`. */
|
|
43
|
+
queueName?: string;
|
|
44
|
+
/** Drop queued requests older than this (minutes) on replay. Default `1440` (24h). */
|
|
45
|
+
maxRetentionMinutes?: number;
|
|
46
|
+
}
|
|
47
|
+
|
|
1
48
|
/**
|
|
2
49
|
* Install a `notificationclick` handler that focuses an existing client when
|
|
3
50
|
* possible and falls back to opening a new window.
|
|
@@ -9,6 +56,32 @@ export declare interface InstallNotificationClickHandlerOptions {
|
|
|
9
56
|
resolveUrl?: (data: unknown) => string;
|
|
10
57
|
}
|
|
11
58
|
|
|
59
|
+
/**
|
|
60
|
+
* Precache the app shell at `install` and serve it offline:
|
|
61
|
+
* - reads `precache-manifest.json` (emitted by `tempestPwaManifest()`),
|
|
62
|
+
* - caches every listed URL under a versioned cache,
|
|
63
|
+
* - on `activate`, deletes stale precache versions and claims open clients,
|
|
64
|
+
* - on `fetch`, serves precached assets cache-first and falls back to the
|
|
65
|
+
* `navigateFallback` document for offline navigations (SPA routing).
|
|
66
|
+
*
|
|
67
|
+
* Same-origin only. Register this LAST, after any {@link installRuntimeCache}.
|
|
68
|
+
*/
|
|
69
|
+
export declare function installPrecache(options?: InstallPrecacheOptions): void;
|
|
70
|
+
|
|
71
|
+
/** Options for {@link installPrecache}. */
|
|
72
|
+
export declare interface InstallPrecacheOptions {
|
|
73
|
+
/** URL of the manifest emitted by `tempestPwaManifest()`. Default `/precache-manifest.json`. */
|
|
74
|
+
manifestUrl?: string;
|
|
75
|
+
/** Cache name prefix; the manifest `version` is appended. Default `tempest-precache`. */
|
|
76
|
+
cacheName?: string;
|
|
77
|
+
/** App-shell document served for navigation requests offline. Default `/index.html`. */
|
|
78
|
+
navigateFallback?: string;
|
|
79
|
+
/** Navigation paths that should NOT use the fallback (e.g. `[/^\/api\//]`). */
|
|
80
|
+
navigateFallbackDenylist?: RegExp[];
|
|
81
|
+
/** Activate the new worker immediately after precaching. Default `true`. */
|
|
82
|
+
skipWaiting?: boolean;
|
|
83
|
+
}
|
|
84
|
+
|
|
12
85
|
/**
|
|
13
86
|
* Install a `push` event listener that parses the payload as JSON (with a
|
|
14
87
|
* plain-text fallback) and shows a notification.
|
|
@@ -29,6 +102,18 @@ export declare interface InstallPushHandlerOptions {
|
|
|
29
102
|
transform?: (payload: PushPayload) => PushPayload | null;
|
|
30
103
|
}
|
|
31
104
|
|
|
105
|
+
/**
|
|
106
|
+
* Install a `fetch` handler that resolves matching `GET` requests with the
|
|
107
|
+
* given runtime strategies. Non-matching requests are left untouched (no
|
|
108
|
+
* `respondWith`), so a later {@link installPrecache} can handle them.
|
|
109
|
+
*
|
|
110
|
+
* Register this BEFORE `installPrecache` so specific routes win over the
|
|
111
|
+
* precache catch-all.
|
|
112
|
+
*
|
|
113
|
+
* @param routes Ordered rules; the first whose `match` passes handles the request.
|
|
114
|
+
*/
|
|
115
|
+
export declare function installRuntimeCache(routes: RuntimeRoute[]): void;
|
|
116
|
+
|
|
32
117
|
/**
|
|
33
118
|
* Install a `message` listener that activates a waiting worker when the host
|
|
34
119
|
* app sends `{ type: "SKIP_WAITING" }`.
|
|
@@ -87,6 +172,51 @@ export declare interface RegisterServiceWorkerOptions {
|
|
|
87
172
|
onError?: (error: unknown) => void;
|
|
88
173
|
}
|
|
89
174
|
|
|
175
|
+
/** A single runtime-caching rule, matched against each `GET` request. */
|
|
176
|
+
export declare interface RuntimeRoute {
|
|
177
|
+
/** A `RegExp` tested against the full URL, or a predicate over the parsed URL. */
|
|
178
|
+
match: RegExp | ((url: URL, request: Request) => boolean);
|
|
179
|
+
/** How to resolve a match. */
|
|
180
|
+
strategy: RuntimeStrategy;
|
|
181
|
+
/** Cache bucket name for this route. */
|
|
182
|
+
cacheName: string;
|
|
183
|
+
/** Trim the cache to at most this many entries (FIFO) after each write. */
|
|
184
|
+
maxEntries?: number;
|
|
185
|
+
/** Treat a cached response older than this (seconds) as a miss. */
|
|
186
|
+
maxAgeSeconds?: number;
|
|
187
|
+
/** For `network-first`: fall back to cache after this timeout (seconds). */
|
|
188
|
+
networkTimeoutSeconds?: number;
|
|
189
|
+
/**
|
|
190
|
+
* Serve HTTP `Range` requests (206 Partial Content) by slicing the cached
|
|
191
|
+
* full response. Enable for audio/video so seeking works offline. The full
|
|
192
|
+
* resource is cached once (the `Range` header is stripped before caching).
|
|
193
|
+
*/
|
|
194
|
+
rangeRequests?: boolean;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Service-worker caching helpers — a small, dependency-free subset of what
|
|
199
|
+
* Workbox provides: precaching of the build's app shell (so the app launches
|
|
200
|
+
* offline) plus runtime caching strategies for fonts, APIs and images.
|
|
201
|
+
*
|
|
202
|
+
* Import these inside your own `sw.ts`. They run in the service-worker global
|
|
203
|
+
* scope, not the main thread. Pair `installPrecache` with the
|
|
204
|
+
* `tempestPwaManifest()` Vite plugin (from `tempest-react-sdk/vite`), which
|
|
205
|
+
* emits the `precache-manifest.json` this reads at install time.
|
|
206
|
+
*
|
|
207
|
+
* @example
|
|
208
|
+
* /// <reference lib="webworker" />
|
|
209
|
+
* import { installRuntimeCache, installPrecache } from "tempest-react-sdk/sw";
|
|
210
|
+
*
|
|
211
|
+
* // Register specific routes FIRST so they win over the precache catch-all.
|
|
212
|
+
* installRuntimeCache([
|
|
213
|
+
* { match: /\/api\//, strategy: "network-first", cacheName: "api", maxAgeSeconds: 300 },
|
|
214
|
+
* ]);
|
|
215
|
+
* installPrecache();
|
|
216
|
+
*/
|
|
217
|
+
/** Caching strategy for a runtime route. Mirrors the common Workbox trio. */
|
|
218
|
+
export declare type RuntimeStrategy = "cache-first" | "network-first" | "stale-while-revalidate";
|
|
219
|
+
|
|
90
220
|
/**
|
|
91
221
|
* Tell a waiting worker to activate immediately. Pair with `onUpdate` to roll
|
|
92
222
|
* out updates after the user confirms a reload prompt.
|