Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Moving recent nightly builds to latest #90

Merged
merged 18 commits into from
Sep 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19,946 changes: 9,796 additions & 10,150 deletions package-lock.json

Large diffs are not rendered by default.

12 changes: 12 additions & 0 deletions packages/cache/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
## @remix-pwa/cache 2.0.9-dev.1 (2023-09-26)


### Bug Fixes

* **cache:** fixed LRU cleanup workflow in cache 2dc0449


### Performance Improvements

* **cache:** slightly improved lru algo bec7ca3

## @remix-pwa/cache 2.0.8 (2023-09-25)


Expand Down
2 changes: 1 addition & 1 deletion packages/cache/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@remix-pwa/cache",
"version": "2.0.8",
"version": "2.0.9-dev.1",
"description": "A thin-layered wrapper around the browser's Cache Storage API that supercharges your Remix PWA's caching capabilities.",
"repository": {
"type": "git",
Expand Down
58 changes: 43 additions & 15 deletions packages/cache/src/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,21 +153,44 @@ export class RemixCache implements CustomCache {
}

private async _lruCleanup() {
if ((await this.length()) >= this._maxItems) {
this._values().then(async values => {
const val = values.sort((a, b) => {
// @ts-ignore
const aMeta = a.clone().json().metadata;
// @ts-ignore
const bMeta = b.clone().json().metadata;

return aMeta.accessedAt - bMeta.accessedAt;
})[0];
const isOverflowing = (await this.length()) >= this._maxItems;

if (isOverflowing) {
if (process.env.NODE_ENV === 'development')
console.log(`Cache '${this.name}' is overflowing. Running LRU cleanup.`);

const cache = await this._openCache();
const keys = await cache.keys();
const values = (await Promise.all(keys.map(key => cache.match(key)))) as Response[];

const keyVal = keys.map((key, i) => ({ key, val: values[i] }));

const comparableArrayPromise = keyVal.map(async val => {
const { metadata }: ResponseBody = await val.val.clone().json();

return {
metadata,
url: val.key.url,
};
});

const comparableArray = await Promise.all(comparableArrayPromise);

const sortedArr = comparableArray.sort((a, b) => {
return a.metadata.accessedAt - b.metadata.accessedAt;
});

const toBeDeletdItems = sortedArr.slice(0, sortedArr.length - this._maxItems + 1);

if (process.env.NODE_ENV === 'development')
console.log(`Deleting ${toBeDeletdItems.length} items from ${this.name} cache.`);

for (const deleted of toBeDeletdItems) {
// This runs everytime a new entry is added so that means the array maximum size can never
// exceed `maxItems + 1` (the new entry + the maxItems), so we can safely slice the array
// to the maxItems length starting from the first index.
this.delete(val.url);
});
await this.delete(deleted.url);
}
}
}

Expand Down Expand Up @@ -371,7 +394,7 @@ export class RemixCache implements CustomCache {
newHeaders.set('X-Remix-PWA-Original-Content-Type', contentType || 'text/plain');
newHeaders.set('X-Remix-PWA-TTL', expiresAt.toString());

response = new Response(
const toBeCachedRes = new Response(
JSON.stringify({
metadata: {
accessedAt,
Expand All @@ -390,12 +413,17 @@ export class RemixCache implements CustomCache {
}
);

Object.defineProperty(toBeCachedRes, 'url', { value: response.url });
Object.defineProperty(toBeCachedRes, 'type', { value: response.type });
Object.defineProperty(toBeCachedRes, 'ok', { value: response.ok });
Object.defineProperty(toBeCachedRes, 'redirected', { value: response.redirected });

// Cache the updated response and maintain the cache
try {
await this._lruCleanup();
return await cache.put(request, response.clone());
return await cache.put(request, toBeCachedRes.clone());
} catch (error) {
console.error('Failed to put to cache:', error);
if (process.env.NODE_ENV === 'development') console.error('Failed to put to cache:', error);
}
}

Expand Down
2 changes: 1 addition & 1 deletion packages/dev/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
## @remix-pwa/dev 2.0.25 (2023-09-26)
## @remix-pwa/dev 2.0.25-dev.1 (2023-09-26)


### Bug Fixes
Expand Down
2 changes: 1 addition & 1 deletion packages/dev/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@remix-pwa/dev",
"version": "2.0.25",
"version": "2.0.25-dev.1",
"description": "An esbuild compiler for Service Workers in Remix.run",
"repository": {
"type": "git",
Expand Down
10 changes: 10 additions & 0 deletions packages/strategy/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
## @remix-pwa/strategy 2.1.6-dev.1 (2023-09-26)





### Dependencies

* **@remix-pwa/cache:** upgraded to 2.0.9-dev.1

## @remix-pwa/strategy 2.1.5 (2023-09-25)


Expand Down
6 changes: 3 additions & 3 deletions packages/strategy/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@remix-pwa/strategy",
"version": "2.1.5",
"version": "2.1.6-dev.1",
"description": "A collection of service worker strategies for Remix PWA",
"repository": {
"type": "git",
Expand All @@ -27,14 +27,14 @@
"node": ">=14.0.0"
},
"peerDependencies": {
"@remix-pwa/cache": "^2.0.8"
"@remix-pwa/cache": "^2.0.9-dev.1"
},
"devDependencies": {
"@remix-pwa/eslint-config": "^0.0.0",
"@remix-pwa/lint-staged-config": "^0.0.0"
},
"dependencies": {
"@remix-pwa/cache": "^2.0.8"
"@remix-pwa/cache": "^2.0.9-dev.1"
},
"homepage": "https://remix-pwa.run",
"keywords": [
Expand Down
17 changes: 17 additions & 0 deletions packages/sw/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,20 @@
## @remix-pwa/sw 2.1.8-dev.1 (2023-09-26)


### Bug Fixes

* **sw:** updated `loadServiceWorker` defaults format faf7158
* **sw:** updated `loadServiceWorker` defaults format cdf73e0
* **sw:** updated and sorted out sw loader params 32e92ec





### Dependencies

* **@remix-pwa/cache:** upgraded to 2.0.9-dev.1

## @remix-pwa/sw 2.1.7 (2023-09-25)


Expand Down
6 changes: 3 additions & 3 deletions packages/sw/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@remix-pwa/sw",
"version": "2.1.7",
"version": "2.1.8-dev.1",
"description": "Service Worker APIs and utilities for Remix PWA",
"repository": {
"type": "git",
Expand Down Expand Up @@ -28,15 +28,15 @@
"test": "vitest --run --environment node --threads --single-thread --pass-with-no-tests"
},
"peerDependencies": {
"@remix-pwa/cache": "^2.0.8",
"@remix-pwa/cache": "^2.0.9-dev.1",
"@remix-run/dev": "^1.15.0 || ^2.0.0",
"@remix-run/react": "^1.15.0 || ^2.0.0",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"homepage": "https://remix-pwa.run",
"devDependencies": {
"@remix-pwa/cache": "^2.0.8",
"@remix-pwa/cache": "^2.0.9-dev.1",
"@remix-pwa/eslint-config": "^0.0.0",
"@remix-pwa/lint-staged-config": "^0.0.0",
"@remix-run/react": "^2.0.0",
Expand Down
43 changes: 32 additions & 11 deletions packages/sw/src/react/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,37 +9,54 @@ declare global {
}
}

export type LoadServiceWorkerOptions = RegistrationOptions & {
serviceWorkerUrl?: string;
serviceWorkerRegistrationCallback?: (registration: ServiceWorkerRegistration) => Promise<void> | void;
export type LoadServiceWorkerOptions = {
serviceWorkerUrl: string;
serviceWorkerRegistrationCallback: (registration: ServiceWorkerRegistration) => Promise<void> | void;
scope: RegistrationOptions['scope'];
type: RegistrationOptions['type'];
updateViaCache?: RegistrationOptions['updateViaCache'];
};

/**
* Load service worker in `entry.client` when the client gets hydrated.
*
* All parameters are optional.
*
* @param options - Options for loading the service worker.
* @param options.serviceWorkerUrl='/entry.worker.js' - URL of the service worker.
* @param options.serviceWorkerRegistrationCallback - Callback function when the service worker gets registered. Takes in the `ServiceWorkerRegistration` object.
* @param options.registrationOptions - Options for the service worker registration.
* @param serviceWorkerUrl='/entry.worker.js' - URL of the service worker.
* @param serviceWorkerRegistrationCallback - Callback function when the service worker gets registered. Takes in the `ServiceWorkerRegistration` object.
* @param scope - The service worker's registration scope.
* @param type - The service worker's type.
* @param updateViaCache - The service worker's `updateViaCache` option - controls how the browser handles updates to the service worker's script URL, and is one of the following strings:
* - `imports` - The browser bypasses the cache and attempts to update the service worker immediately.
* - `all` - The browser uses the cache to update the service worker.
* - `none` - The browser doesn't use the cache to update the service worker.
*
* ### Example
*
* ```ts
* loadServiceWorker({
* serviceWorkerUrl: "/entry.worker.js",
* scope: "/",
* serviceWorkerUrl: "/entry.worker.js"
* type: "classic",
* })
* ```
*/
export function loadServiceWorker(
{ serviceWorkerRegistrationCallback, serviceWorkerUrl, ...options }: LoadServiceWorkerOptions = {
{
scope = '/',
serviceWorkerRegistrationCallback = (reg: ServiceWorkerRegistration) => {
reg.update();
},
serviceWorkerUrl = '/entry.worker.js',
type = 'classic',
updateViaCache,
}: LoadServiceWorkerOptions = {
scope: '/',
serviceWorkerUrl: '/entry.worker.js',
type: 'classic',
serviceWorkerRegistrationCallback: (reg: ServiceWorkerRegistration) => {
reg.update();
},
serviceWorkerUrl: '/entry.worker.js',
}
) {
if ('serviceWorker' in navigator) {
Expand All @@ -53,7 +70,11 @@ export function loadServiceWorker(
};

try {
const registration = await navigator.serviceWorker.register(serviceWorkerUrl!, options);
const registration = await navigator.serviceWorker.register(serviceWorkerUrl, {
scope,
type,
updateViaCache: updateViaCache || 'none',
});

// await serviceWorkerRegistrationCallback?.(registration); ❌

Expand Down
8 changes: 6 additions & 2 deletions playground/app/entry.worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,12 @@ const ASSETS = 'assets-cache';
const dataCache = Storage.open(DATA, {
ttl: 60 * 60 * 24 * 7 * 1_000, // 7 days
});
const documentCache = Storage.open(PAGES);
const assetCache = Storage.open(ASSETS);
const documentCache = Storage.open(PAGES, {
maxItems: 3
});
const assetCache = Storage.open(ASSETS, {
maxItems: 5
});

let handler = new RemixNavigationHandler({
dataCache: dataCache,
Expand Down
6 changes: 5 additions & 1 deletion playground/app/root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
Outlet,
Scripts,
ScrollRestoration,
useLocation,
} from "@remix-run/react";

import stylesheet from './tailwind.css';
Expand All @@ -20,12 +21,15 @@ export const links: LinksFunction = () => [

export default function App() {
useSWEffect();
const location = useLocation();

useEffect(() => {
if (typeof window !== 'undefined') {
// ...
console.log('window update!');
window.$ServiceWorkerHMRHandler$();
}
})
}, [location])

return (
<html lang="en">
Expand Down
1 change: 1 addition & 0 deletions playground/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"dexie": "^3.2.4",
"dotenv": "^16.3.1",
"isbot": "^3.7.0",
"jotai": "^2.4.2",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
Expand Down
Loading
Loading