@absolutejs/pwa

中文文档
0.17.0发布于 2026/10/24MITTypeScriptES Module构建来源已验证近 30 天下载 5609

Framework-agnostic installability, offline Sync, service workers, and Web Push for AbsoluteJS apps

原始使用文档
文档目录11 节
  1. Server
  2. Portable push in AbsoluteJS
  3. Client
  4. Offline Sync
  5. Install prompt
  6. Embedded browsers and capability UX
  7. App update prompt
  8. License
  9. Long-lived tab updates
  10. Automatic updates
  11. Recovering asset loads without losing the current page

@absolutejs/pwa

Framework-agnostic primitives for turning any app into an installable, offline-capable, push-capable PWA: a web app manifest, finite background Sync, the push service worker, a VAPID Web Push sender that flags dead endpoints, and browser glue for service-worker registration + subscription.

Its direct primitives remain storage- and framework-agnostic. AbsoluteJS builds add the recommended path: Auth owns registration, Dispatch owns lifecycle and fanout, and page code uses only @absolutejs/devices.

bun add @absolutejs/pwa

Server

import {
  createWebAppManifest,
  pushServiceWorker,
  createWebPush,
} from "@absolutejs/pwa";

const ICON = "/icons/app-512.png";

// Serve as application/manifest+json at /manifest.webmanifest
export const manifest = createWebAppManifest({
  name: "My App",
  shortName: "MyApp",
  themeColor: "#6366f1",
  icons: [
    { src: ICON, sizes: "192x192", type: "image/png", purpose: "any" },
    { src: ICON, sizes: "512x512", type: "image/png", purpose: "any" },
  ],
});

// Serve as text/javascript at /sw.js with header `Service-Worker-Allowed: /`.
// Pass `offline` to also precache an app shell + serve a fallback page when a
// navigation fails offline, and cache same-origin assets cache-first.
export const sw = pushServiceWorker({
  icon: ICON,
  offline: { fallback: "/offline.html", assetPrefix: "/assets/" },
  sync: true,
});

// VAPID sender — pass empty/unset keys and it no-ops (isConfigured() === false),
// so push degrades gracefully to your email/in-app fallback.
const push = createWebPush({
  publicKey: process.env.VAPID_PUBLIC_KEY,
  privateKey: process.env.VAPID_PRIVATE_KEY,
  subject: "mailto:[email protected]",
});

// Fan out to a user's devices; prune whatever it reports gone.
const { gone } = await push.sendMany(subscriptions, {
  title: "New match",
  body: "Acme Co. just replied.",
  url: "/inbox",
});
await pruneEndpoints(gone); // your storage

Mounting is yours. With Elysia:

new Elysia()
  .get("/manifest.webmanifest", ({ set }) => {
    set.headers["content-type"] = "application/manifest+json";
    return manifest;
  })
  .get("/sw.js", ({ set }) => {
    set.headers["content-type"] = "text/javascript";
    set.headers["service-worker-allowed"] = "/";
    return sw;
  });

Portable push in AbsoluteJS

In an AbsoluteJS application, importing pushNotifications and enabling pwa automatically generates the browser adapter and subscription-rotation worker. Set the public VAPID_PUBLIC_KEY in the build environment; keep VAPID_PRIVATE_KEY only in the trusted delivery process. Configure Auth once with a Dispatch lifecycle at auth({ push: ... }). The browser can submit only its provider credential and opaque installation ID—Auth derives user, tenant, and topics on the server.

import { pushNotifications } from "@absolutejs/devices";

await pushNotifications.requestPermission();
await pushNotifications.enable();

The same page code uses APNs/FCM in a Capacitor shell and Web Push in a browser. For direct PWA integrations, pass push to registerServiceWorker() or call configurePwaPush() explicitly. Installation identity is shared with the service worker in IndexedDB so browser subscription rotation updates the same trusted server record even when no page is open.

Dispatch users can import createWebPushDispatchAdapter from @absolutejs/pwa/dispatch; it maps provider-neutral messages to the Web Push sender and classifies gone/retryable results for lifecycle retirement.

Client

import {
  registerServiceWorker,
  getPushStatus,
  subscribeToPush,
  unsubscribeFromPush,
} from "@absolutejs/pwa/client";

// At boot. By default this waits for page load, then retries transient
// browser/network failures up to three total attempts.
await registerServiceWorker(); // defaults to "/sw.js"

// Toggle on: returns the subscription JSON — send it through your typed API.
const subscription = await subscribeToPush(vapidPublicKey);
await api.push.subscriptions.post(subscription);

// Toggle off: returns the endpoint to drop server-side.
const endpoint = await unsubscribeFromPush();
await api.push.subscriptions.delete({ endpoint });

const status = await getPushStatus(); // { supported, permission, subscribed }

Offline Sync

@absolutejs/pwa can provision @absolutejs/sync automatically for an authenticated browser app. Generate the worker with sync: true, then enable the client bridge during registration:

await registerServiceWorker("/sw.js", { sync: {} });

The Sync browser runtime is loaded lazily only when this bridge is enabled, so manifest-, install-, and push-only applications do not pay its client cost.

AbsoluteJS supplies storageSchema automatically by composing the app schema with declarative metadata from installed Sync packs. The same JSON-safe plan is used by the foreground client and service worker, so IndexedDB upgrades before either runtime reads cached rows or flushes the durable outbox. Direct PWA integrations may pass that component bundle through sync.storageSchema.

The bundle also carries local-data sensitivity, retention, and quota rules. Browsers do not receive pretend encryption backed by a key stored beside the ciphertext: an encryption-required record fails closed unless the direct PWA integration supplies an audited Sync protection provider. Portable packs can instead declare onProtectionUnavailable: "memory-only"; the feature keeps its live browser state and online-only mutations without writing sensitive rows or arguments to IndexedDB, while the same bundle is durably encrypted by the native Keychain/Keystore-backed adapter. Quota pressure evicts complete cached projections and never the durable outbox.

With @absolutejs/auth and syncSocket() mounted, no page-level token or collection list is needed. The client performs a strict same-origin JSON POST to /__absolute/sync/principal using the existing HTTP-only session cookie. The response contains only an opaque account namespace. Foreground Sync clients and the worker share a namespaced IndexedDB store; the worker discovers persisted id-keyed collection descriptors, flushes the durable outbox, and pulls finite updates through /__absolute/sync/background.

Background Sync is best-effort because browser support and scheduling vary. Online, focus, and visible-page events also reconnect and flush active clients, so foreground/resume remains the correctness path. Native apps continue using their Bearer-based Auth transport rather than this cookie-session bridge.

Advanced endpoints, limits, and the shared database name are configurable:

await registerServiceWorker("/sw.js", {
  sync: {
    endpoint: "/__absolute/sync/background",
    principalEndpoint: "/__absolute/sync/principal",
    databaseName: "absolutejs-sync-v1",
    maxMutations: 50,
    maxPulls: 50,
  },
});

Both endpoints must resolve to the page's exact origin and redirects are refused. Cookies, bearer tokens, mutation arguments, and application rows are never embedded in the worker script or service-worker messages. If the session is absent, the worker configuration is cleared. On focus, online, and visible page transitions, the bridge resolves the principal again before syncing. An account change aborts the old run, clears its runtime, and installs the new opaque namespace before any new work starts. configurePwaSync() is also exported for hosts that register their worker separately.

Observe sanitized run outcomes without sending application data to AbsoluteJS:

import { getLastPwaSyncResult, onPwaSyncResult } from "@absolutejs/pwa/client";

const unsubscribe = onPwaSyncResult((result) => {
  // { ok, durationMs, trigger, acknowledged?, pulled?, ... }
  console.log(result);
});

const latest = getLastPwaSyncResult();

The same aggregate result is dispatched on window as the absolute:pwa-sync-result custom event. Its contract permits only status, duration, trigger, and aggregate counts; namespaces, endpoints, credentials, mutation arguments, and rows are discarded at the page boundary. This is an application-observable signal, not built-in analytics or a phone-home channel.

Install prompt

Capture the browser's install signal and drive it from your own button:

import {
  initInstallPrompt,
  onInstallable,
  promptInstall,
  canInstall,
} from "@absolutejs/pwa/client";

initInstallPrompt(); // once at boot

// React to availability (show/hide your install button):
const off = onInstallable((installable) => setShowInstall(installable));

// From a click handler (must be a user gesture):
const accepted = await promptInstall();

Embedded browsers and capability UX

Feature-detect before offering browser-dependent actions, then use embedded- browser identity only to explain an unavailable capability:

import {
  detectEmbeddedBrowser,
  getBrowserCapabilities,
} from "@absolutejs/pwa/client";

const capabilities = getBrowserCapabilities();
if (!capabilities.pushNotifications && capabilities.embeddedBrowser) {
  showOpenInBrowserHelp(capabilities.embeddedBrowser.app);
}

// Pure user-agent classification is also available for SSR/tests.
detectEmbeddedBrowser(request.headers.get("user-agent") ?? "");

Detection is deliberately conservative: Facebook, Instagram, and Messenger are identified only from their explicit host-app markers. Unknown WebViews return null; capability checks remain authoritative.

App update prompt

One latched update flow handles both waiting service workers and release probes. Detection never reloads the page; only the user's update action does:

import {
  announceUpdateAvailable,
  applyUpdate,
  checkForUpdate,
  onUpdateAvailable,
} from "@absolutejs/pwa/client";

// Render your framework's branded prompt. A signal received before this
// subscription is retained and delivered immediately.
const off = onUpdateAvailable(() => showUpdatePrompt());

// Bridge any release detector, including @absolutejs/beacon's releaseProbe:
const onStale = (release: { currentRelease: string; newestRelease: string }) =>
  announceUpdateAvailable({ ...release, source: "release-probe" });

// Safe to call on focus, visibility change, or an interval.
await checkForUpdate();

// Call only from the prompt's button. This activates a waiting worker when one
// exists, then performs exactly one bounded reload.
await applyUpdate();

The service worker must be built without skipWaiting (the default) so it waits for explicit user consent. Repeated release-probe and service-worker signals merge into one prompt instead of creating competing reload paths.

Every client function is feature-safe (no-ops when the APIs are missing or during SSR). subscribeToPush throws Error("notification-permission-denied") on a hard permission denial so you can message it.

License

MIT

Long-lived tab updates

Subscribe with onUpdateAvailable before calling startAppUpdateChecks({ currentRelease, endpoint: "/version" }) from @absolutejs/pwa/client. Serve a non-cached { release } or { commit } response and embed the same release in each rendered page. The package checks immediately, once a minute while visible, and on focus, visibility and reconnect. Return the cleanup on unmount. The probe works even without service workers, ignores offline/malformed responses, and never reloads automatically. Render your app's persistent Update now button and call applyUpdate() only from that user action. A waiting worker activates first; otherwise it performs one reload. Failed activation lookups can be retried.

Automatic updates

startAutoUpdate() applies a discovered update on its own, at a moment that cannot lose work: immediately in a hidden tab, or after idleMs (default 15s) without pointer, key, wheel, touch or scroll input in a visible one. It never reloads while a dialog[open], [role="dialog"] or [aria-modal="true"] element is present, while a text field has focus, or while your isBusy() returns true (a throwing check counts as busy); it re-checks every retryMs.

import {
  onUpdateAvailable,
  startAppUpdateChecks,
  startAutoUpdate,
} from "@absolutejs/pwa/client";

const offPrompt = onUpdateAvailable(() => showUpdateBanner()); // fallback while busy
const stopChecks = startAppUpdateChecks({
  currentRelease,
  endpoint: "/version",
});
const stopAuto = startAutoUpdate({ isBusy: () => hasUnsavedDrafts() });

The page reloads at its current URL. Keep an Update now banner for the busy case.

Recovering asset loads without losing the current page

startAppUpdateChecks() also monitors same-origin script, stylesheet, and module-preload failures. It never reloads automatically. Subscribe to onAssetLoadFailure alongside onUpdateAvailable to show one retry/update action. A failure captured before the UI subscribes is replayed to that subscriber. The original error remains available to error tracking.

Feed handled router errors into reportAssetLoadFailure(error, destination). It returns false for unrelated errors or external destinations. After a successful navigation, call clearAssetLoadFailure(). On the user's explicit retry, call applyUpdate({ targetUrl: failure?.targetUrl }): this activates a waiting worker if necessary and replaces the failed destination once. Offline or failed activation attempts remain retryable; no timer reloads the page without that explicit action.

版本与发布记录

@absolutejs/pwa 共发布 30 个版本,首次发布于 2026/06/19;过去 12 个月发布了 30 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.17.0latest2026/10/2413 天前
0.16.32026/10/2214 天前
0.16.22026/10/0928 天前
0.16.12026/09/271 个月前
0.16.02026/09/261 个月前
0.15.02026/09/241 个月前

关于 @absolutejs/pwa 的常见问题

@absolutejs/pwa 是什么?

Framework-agnostic installability, offline Sync, service workers, and Web Push for AbsoluteJS apps

如何安装 @absolutejs/pwa?

在项目目录运行 npm install @absolutejs/pwa,或使用 pnpm add / yarn add / bun add。

@absolutejs/pwa 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@absolutejs/pwa 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@absolutejs/pwa 可以商用吗?

@absolutejs/pwa 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@absolutejs/pwa 的下载量有多少?

根据 npm 官方下载统计,@absolutejs/pwa 在 2026/10/05 – 2026/11/03 这 30 天内被下载 5,609 次,日均约 187 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@absolutejs/pwa 还在维护吗?

最新版本 0.17.0 发布于 2026/10/24(13 天前);至今共发布 30 个版本,其中过去 12 个月发布了 30 个;首次发布于 2026/06/19。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。