nuxt-skew-protection 0.2.1 → 0.2.3
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/dist/module.json +1 -1
- package/dist/module.mjs +28 -6
- package/dist/runtime/app/composables/useSkewProtection.d.ts +1 -1
- package/dist/runtime/app/composables/useSkewProtection.js +3 -9
- package/dist/runtime/app/plugins/check-updates-sse.client.d.ts +1 -1
- package/dist/runtime/app/plugins/check-updates-sse.client.js +13 -3
- package/dist/runtime/app/plugins/check-updates-websocket.client.d.ts +1 -1
- package/dist/runtime/app/plugins/check-updates-websocket.client.js +17 -2
- package/dist/runtime/app/plugins/init-build-id.d.ts +12 -0
- package/dist/runtime/app/plugins/init-build-id.js +29 -0
- package/dist/runtime/app/plugins/sw-track-user-modules.client.d.ts +1 -1
- package/dist/runtime/app/plugins/sw-track-user-modules.client.js +33 -1
- package/dist/runtime/shared/logger.d.ts +4 -0
- package/dist/runtime/shared/logger.js +5 -0
- package/dist/runtime/types.d.ts +0 -5
- package/dist/sw/_nuxt-skew-sw.js +1 -0
- package/package.json +2 -2
- package/dist/module.cjs +0 -757
- package/dist/module.d.cts +0 -64
- package/dist/module.d.ts +0 -64
package/dist/module.json
CHANGED
package/dist/module.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { writeFileSync, unlinkSync, existsSync, readFileSync, promises } from 'node:fs';
|
|
2
|
-
import { useNuxt, tryUseNuxt, useLogger, defineNuxtModule, createResolver, addTypeTemplate, addComponent, addImports,
|
|
2
|
+
import { useNuxt, tryUseNuxt, useLogger, defineNuxtModule, createResolver, addTypeTemplate, addComponent, addImports, addPlugin, addServerHandler } from '@nuxt/kit';
|
|
3
3
|
import { provider, env } from 'std-env';
|
|
4
4
|
import { join } from 'node:path';
|
|
5
5
|
import { tmpdir } from 'node:os';
|
|
@@ -515,8 +515,15 @@ function createAssetManager(options) {
|
|
|
515
515
|
try {
|
|
516
516
|
const latestData = await promises.readFile(latestPath, "utf-8");
|
|
517
517
|
const latestJson = JSON.parse(latestData);
|
|
518
|
+
const clientVersions = {};
|
|
519
|
+
for (const [versionId, versionData] of Object.entries(manifest.versions)) {
|
|
520
|
+
clientVersions[versionId] = {
|
|
521
|
+
timestamp: versionData.timestamp,
|
|
522
|
+
deletedChunks: versionData.deletedChunks
|
|
523
|
+
};
|
|
524
|
+
}
|
|
518
525
|
latestJson.skewProtection = {
|
|
519
|
-
versions:
|
|
526
|
+
versions: clientVersions
|
|
520
527
|
};
|
|
521
528
|
await promises.writeFile(latestPath, JSON.stringify(latestJson, null, 2), "utf-8");
|
|
522
529
|
} catch (error) {
|
|
@@ -531,10 +538,8 @@ function createAssetManager(options) {
|
|
|
531
538
|
const versionData = manifest.versions[buildId];
|
|
532
539
|
if (versionData) {
|
|
533
540
|
metaJson.skewProtection = {
|
|
534
|
-
assets: versionData.assets,
|
|
535
541
|
deletedChunks: versionData.deletedChunks,
|
|
536
|
-
timestamp: versionData.timestamp
|
|
537
|
-
expires: versionData.expires
|
|
542
|
+
timestamp: versionData.timestamp
|
|
538
543
|
};
|
|
539
544
|
}
|
|
540
545
|
await promises.writeFile(metaPath, JSON.stringify(metaJson, null, 2), "utf-8");
|
|
@@ -593,12 +598,19 @@ const module = defineNuxtModule({
|
|
|
593
598
|
cookie: options.cookie,
|
|
594
599
|
debug: options.debug
|
|
595
600
|
};
|
|
596
|
-
const nitroPreset =
|
|
601
|
+
const nitroPreset = resolveNitroPreset(nuxt.options.nitro);
|
|
597
602
|
addTypeTemplate({
|
|
598
603
|
filename: "types/nuxt-skew-protection.d.ts",
|
|
599
604
|
getContents: () => {
|
|
600
605
|
return `// Generated by nuxt-skew-protection
|
|
601
606
|
declare module '#app' {
|
|
607
|
+
interface RuntimeNuxtHooks {
|
|
608
|
+
'skew-protection:chunks-outdated': (payload: ChunksOutdatedPayload) => void | Promise<void>
|
|
609
|
+
}
|
|
610
|
+
interface NuxtApp {
|
|
611
|
+
$skewProtectionBuildId: Ref<string | undefined>
|
|
612
|
+
$skewProtectionCookie: Ref<string | undefined>
|
|
613
|
+
}
|
|
602
614
|
interface NuxtAppManifestMeta {
|
|
603
615
|
skewProtection?: {
|
|
604
616
|
versions?: Record<string, {
|
|
@@ -612,6 +624,13 @@ declare module '#app' {
|
|
|
612
624
|
}
|
|
613
625
|
|
|
614
626
|
declare module 'nuxt/app' {
|
|
627
|
+
interface RuntimeNuxtHooks {
|
|
628
|
+
'skew-protection:chunks-outdated': (payload: ChunksOutdatedPayload) => void | Promise<void>
|
|
629
|
+
}
|
|
630
|
+
interface NuxtApp {
|
|
631
|
+
$skewProtectionBuildId: Ref<string | undefined>
|
|
632
|
+
$skewProtectionCookie: Ref<string | undefined>
|
|
633
|
+
}
|
|
615
634
|
interface NuxtAppManifestMeta {
|
|
616
635
|
skewProtection?: {
|
|
617
636
|
versions?: Record<string, {
|
|
@@ -638,6 +657,9 @@ export {}
|
|
|
638
657
|
name: "useSkewProtection",
|
|
639
658
|
from: resolver.resolve("./runtime/app/composables/useSkewProtection")
|
|
640
659
|
});
|
|
660
|
+
addPlugin({
|
|
661
|
+
src: resolver.resolve("./runtime/app/plugins/init-build-id")
|
|
662
|
+
});
|
|
641
663
|
nuxt.options.alias["nuxt-skew-protection/server"] = resolver.resolve("./runtime/server");
|
|
642
664
|
if (options.storage?.driver) {
|
|
643
665
|
nuxt.options.nitro = nuxt.options.nitro || {};
|
|
@@ -3,7 +3,7 @@ import type { ChunksOutdatedPayload } from '../../types.js';
|
|
|
3
3
|
export declare function checkForUpdates(): Promise<void>;
|
|
4
4
|
export declare function useSkewProtection(): {
|
|
5
5
|
manifest: import("vue").Ref<NuxtAppManifestMeta | undefined, NuxtAppManifestMeta | undefined>;
|
|
6
|
-
clientVersion:
|
|
6
|
+
clientVersion: any;
|
|
7
7
|
isOutdated: import("vue").ComputedRef<boolean | undefined>;
|
|
8
8
|
onCurrentChunksOutdated: (callback: (payload: ChunksOutdatedPayload) => void | Promise<void>) => () => void;
|
|
9
9
|
onAppOutdated: (callback: (manifest?: NuxtAppManifestMeta) => void | Promise<void>) => () => void;
|
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
import { buildAssetsURL } from "#internal/nuxt/paths";
|
|
2
|
-
import {
|
|
2
|
+
import { useNuxtApp } from "nuxt/app";
|
|
3
3
|
import { computed, onUnmounted, ref } from "vue";
|
|
4
4
|
import { useRuntimeConfigSkewProtection } from "./useRuntimeConfigSkewProtection.js";
|
|
5
5
|
export async function checkForUpdates() {
|
|
6
6
|
const nuxtApp = useNuxtApp();
|
|
7
7
|
const runtimeConfig = useRuntimeConfigSkewProtection();
|
|
8
|
-
const
|
|
9
|
-
const clientVersion = import.meta.client ? cookie.value : runtimeConfig.buildId;
|
|
8
|
+
const clientVersion = nuxtApp.$skewProtectionBuildId?.value || runtimeConfig.buildId;
|
|
10
9
|
const meta = await $fetch(`${buildAssetsURL("builds/latest.json")}?${Date.now()}`).catch(() => {
|
|
11
10
|
return null;
|
|
12
11
|
});
|
|
@@ -17,12 +16,7 @@ export async function checkForUpdates() {
|
|
|
17
16
|
export function useSkewProtection() {
|
|
18
17
|
const nuxtApp = useNuxtApp();
|
|
19
18
|
const runtimeConfig = useRuntimeConfigSkewProtection();
|
|
20
|
-
const
|
|
21
|
-
default() {
|
|
22
|
-
return runtimeConfig.buildId;
|
|
23
|
-
}
|
|
24
|
-
});
|
|
25
|
-
const clientVersion = import.meta.client ? cookie.value : runtimeConfig.buildId;
|
|
19
|
+
const clientVersion = nuxtApp.$skewProtectionBuildId?.value || nuxtApp.$skewProtectionCookie?.value || runtimeConfig.buildId;
|
|
26
20
|
const manifest = ref();
|
|
27
21
|
function onCurrentChunksOutdated(callback) {
|
|
28
22
|
const hook = nuxtApp.hooks.hook("skew-protection:chunks-outdated", callback);
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
declare const _default: import("
|
|
1
|
+
declare const _default: import("nuxt/app").Plugin<Record<string, unknown>> & import("nuxt/app").ObjectPlugin<Record<string, unknown>>;
|
|
2
2
|
export default _default;
|
|
@@ -7,12 +7,13 @@ export default defineNuxtPlugin({
|
|
|
7
7
|
name: "skew-protection:sse-updates",
|
|
8
8
|
setup(nuxtApp) {
|
|
9
9
|
const { clientVersion } = useSkewProtection();
|
|
10
|
-
|
|
10
|
+
logger.debug("[SSE] Initializing SSE connection for version updates");
|
|
11
|
+
const { data, status, error } = useEventSource(`/_skew/sse`, [], {
|
|
11
12
|
autoReconnect: {
|
|
12
13
|
retries: 10,
|
|
13
14
|
delay: 5e3,
|
|
14
15
|
onFailed() {
|
|
15
|
-
logger.error("SSE
|
|
16
|
+
logger.error("[SSE] Max reconnection attempts reached");
|
|
16
17
|
}
|
|
17
18
|
},
|
|
18
19
|
serializer: {
|
|
@@ -20,13 +21,22 @@ export default defineNuxtPlugin({
|
|
|
20
21
|
read: (rawData) => JSON.parse(rawData)
|
|
21
22
|
}
|
|
22
23
|
});
|
|
24
|
+
watch(status, (newStatus) => {
|
|
25
|
+
logger.debug(`[SSE] Connection status changed: ${newStatus}`);
|
|
26
|
+
});
|
|
27
|
+
watch(error, (err) => {
|
|
28
|
+
if (err)
|
|
29
|
+
logger.debug("[SSE] Connection error:", err);
|
|
30
|
+
});
|
|
23
31
|
watch(data, (message) => {
|
|
24
|
-
logger.debug("SSE
|
|
32
|
+
logger.debug("[SSE] Message received:", message);
|
|
25
33
|
if (!message)
|
|
26
34
|
return;
|
|
27
35
|
if (message.type === "connected" && message.version) {
|
|
28
36
|
const newVersion = message.version;
|
|
37
|
+
logger.debug(`[SSE] Server version: ${newVersion}, Client version: ${clientVersion}`);
|
|
29
38
|
if (newVersion !== clientVersion) {
|
|
39
|
+
logger.debug("[SSE] Version mismatch detected, triggering update check");
|
|
30
40
|
nuxtApp.runWithContext(checkForUpdates);
|
|
31
41
|
}
|
|
32
42
|
}
|
|
@@ -12,5 +12,5 @@
|
|
|
12
12
|
* - Custom WebSocket servers
|
|
13
13
|
* - Any platform that supports WebSocket connections
|
|
14
14
|
*/
|
|
15
|
-
declare const _default: import("
|
|
15
|
+
declare const _default: import("nuxt/app").Plugin<Record<string, unknown>> & import("nuxt/app").ObjectPlugin<Record<string, unknown>>;
|
|
16
16
|
export default _default;
|
|
@@ -9,8 +9,10 @@ export default defineNuxtPlugin({
|
|
|
9
9
|
const { clientVersion } = useSkewProtection();
|
|
10
10
|
const protocol = typeof window !== "undefined" && window.location.protocol === "https:" ? "wss:" : "ws:";
|
|
11
11
|
const url = typeof window !== "undefined" ? `${protocol}//${window.location.host}/_skew/ws` : "";
|
|
12
|
+
logger.debug(`[WS] Initializing WebSocket connection: ${url}`);
|
|
12
13
|
const {
|
|
13
14
|
data,
|
|
15
|
+
status,
|
|
14
16
|
open,
|
|
15
17
|
close
|
|
16
18
|
} = useWebSocket(url, {
|
|
@@ -18,7 +20,7 @@ export default defineNuxtPlugin({
|
|
|
18
20
|
retries: 10,
|
|
19
21
|
delay: 5e3,
|
|
20
22
|
onFailed() {
|
|
21
|
-
logger.error("
|
|
23
|
+
logger.error("[WS] Max reconnection attempts reached");
|
|
22
24
|
}
|
|
23
25
|
},
|
|
24
26
|
heartbeat: {
|
|
@@ -33,29 +35,42 @@ export default defineNuxtPlugin({
|
|
|
33
35
|
immediate: false
|
|
34
36
|
// Don't connect immediately, wait for app:mounted
|
|
35
37
|
});
|
|
38
|
+
watch(status, (newStatus) => {
|
|
39
|
+
logger.debug(`[WS] Connection status changed: ${newStatus}`);
|
|
40
|
+
});
|
|
36
41
|
watch(data, (message) => {
|
|
37
42
|
if (!message)
|
|
38
43
|
return;
|
|
39
44
|
try {
|
|
40
45
|
const parsed = JSON.parse(message);
|
|
46
|
+
logger.debug("[WS] Message received:", parsed);
|
|
47
|
+
if (parsed.type === "ping") {
|
|
48
|
+
logger.debug("[WS] Heartbeat ping");
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
41
51
|
if (parsed.version) {
|
|
42
52
|
const newVersion = parsed.version;
|
|
53
|
+
logger.debug(`[WS] Server version: ${newVersion}, Client version: ${clientVersion}`);
|
|
43
54
|
if (newVersion !== clientVersion) {
|
|
55
|
+
logger.debug("[WS] Version mismatch detected, triggering update check");
|
|
44
56
|
nuxtApp.runWithContext(checkForUpdates);
|
|
45
57
|
}
|
|
46
58
|
}
|
|
47
59
|
} catch (error) {
|
|
48
|
-
logger.error("Failed to parse WebSocket message:", error);
|
|
60
|
+
logger.error("[WS] Failed to parse WebSocket message:", error);
|
|
49
61
|
}
|
|
50
62
|
});
|
|
51
63
|
nuxtApp.hook("app:mounted", () => {
|
|
64
|
+
logger.debug("[WS] App mounted, opening connection");
|
|
52
65
|
open();
|
|
53
66
|
});
|
|
54
67
|
nuxtApp.hook("app:error", () => {
|
|
68
|
+
logger.debug("[WS] App error, closing connection");
|
|
55
69
|
close();
|
|
56
70
|
});
|
|
57
71
|
if (import.meta.client) {
|
|
58
72
|
window.addEventListener("beforeunload", () => {
|
|
73
|
+
logger.debug("[WS] Page unload, closing connection");
|
|
59
74
|
close();
|
|
60
75
|
});
|
|
61
76
|
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Initialize buildId state for SSR->client hydration
|
|
3
|
+
* Also sets cookie client-side for static/prerendered scenarios
|
|
4
|
+
*/
|
|
5
|
+
declare const _default: import("nuxt/app").Plugin<{
|
|
6
|
+
skewProtectionBuildId: import("vue").Ref<any, any>;
|
|
7
|
+
skewProtectionCookie: import("nuxt/app").CookieRef<any>;
|
|
8
|
+
}> & import("nuxt/app").ObjectPlugin<{
|
|
9
|
+
skewProtectionBuildId: import("vue").Ref<any, any>;
|
|
10
|
+
skewProtectionCookie: import("nuxt/app").CookieRef<any>;
|
|
11
|
+
}>;
|
|
12
|
+
export default _default;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { defineNuxtPlugin, useCookie, useRuntimeConfig, useState } from "nuxt/app";
|
|
2
|
+
import { init } from "../../shared/logger.js";
|
|
3
|
+
export default defineNuxtPlugin({
|
|
4
|
+
name: "skew-protection:init-build-id",
|
|
5
|
+
enforce: "pre",
|
|
6
|
+
setup() {
|
|
7
|
+
init();
|
|
8
|
+
const runtimeConfig = useRuntimeConfig();
|
|
9
|
+
const buildId = runtimeConfig.app.buildId;
|
|
10
|
+
const cookieConfig = runtimeConfig.public.skewProtection.cookie;
|
|
11
|
+
const buildIdState = useState("skew-protection:build-id", () => buildId);
|
|
12
|
+
const { name, ...cookieOpts } = cookieConfig;
|
|
13
|
+
const cookie = useCookie(name, {
|
|
14
|
+
...cookieOpts,
|
|
15
|
+
readonly: false
|
|
16
|
+
});
|
|
17
|
+
if (import.meta.client && cookieConfig) {
|
|
18
|
+
if (!cookie.value && buildIdState.value) {
|
|
19
|
+
cookie.value = buildIdState.value;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return {
|
|
23
|
+
provide: {
|
|
24
|
+
skewProtectionBuildId: buildIdState,
|
|
25
|
+
skewProtectionCookie: cookie
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
});
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
declare const _default: import("
|
|
1
|
+
declare const _default: import("nuxt/app").Plugin<Record<string, unknown>> & import("nuxt/app").ObjectPlugin<Record<string, unknown>>;
|
|
2
2
|
export default _default;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { defineNuxtPlugin } from "nuxt/app";
|
|
2
|
+
import { logger } from "../../shared/logger.js";
|
|
2
3
|
import { useSkewProtection } from "../composables/useSkewProtection.js";
|
|
3
4
|
function normalizePath(pathOrUrl) {
|
|
4
5
|
try {
|
|
@@ -12,31 +13,43 @@ export default defineNuxtPlugin({
|
|
|
12
13
|
name: "skew-protection:service-worker",
|
|
13
14
|
setup(nuxtApp) {
|
|
14
15
|
if (!("serviceWorker" in navigator)) {
|
|
16
|
+
logger.debug("[SW] Service Worker not supported in this browser");
|
|
15
17
|
return;
|
|
16
18
|
}
|
|
17
19
|
const { clientVersion, onAppOutdated } = useSkewProtection();
|
|
20
|
+
logger.debug("[SW] Initializing service worker tracking");
|
|
18
21
|
const swRegistration = navigator.serviceWorker.register("/_nuxt-skew-sw.js");
|
|
19
22
|
swRegistration.then((registration) => {
|
|
23
|
+
logger.debug("[SW] Service worker registered successfully");
|
|
20
24
|
const sw = registration.active || registration.installing || registration.waiting;
|
|
21
|
-
if (!sw)
|
|
25
|
+
if (!sw) {
|
|
26
|
+
logger.debug("[SW] No active/installing/waiting service worker found");
|
|
22
27
|
return;
|
|
28
|
+
}
|
|
23
29
|
const alreadyLoadedModules = performance.getEntriesByType("resource").filter((r) => r.name.includes("/_nuxt/") && r.name.endsWith(".js")).map((r) => r.name);
|
|
30
|
+
logger.debug(`[SW] Syncing ${alreadyLoadedModules.length} pre-loaded modules to service worker`);
|
|
24
31
|
alreadyLoadedModules.forEach((url) => {
|
|
32
|
+
logger.debug(`[SW] Sending module to SW: ${url}`);
|
|
25
33
|
sw.postMessage({ type: "ADD_MODULE", url });
|
|
26
34
|
});
|
|
35
|
+
}).catch((error) => {
|
|
36
|
+
logger.debug("[SW] Service worker registration failed:", error);
|
|
27
37
|
});
|
|
28
38
|
async function getLoadedModules() {
|
|
29
39
|
const registration = await swRegistration;
|
|
30
40
|
const sw = registration.active;
|
|
31
41
|
if (!sw) {
|
|
42
|
+
logger.debug("[SW] No active service worker to get modules from");
|
|
32
43
|
return [];
|
|
33
44
|
}
|
|
45
|
+
logger.debug("[SW] Requesting loaded modules from service worker");
|
|
34
46
|
return new Promise((resolve) => {
|
|
35
47
|
let timeoutId;
|
|
36
48
|
const messageHandler = (event) => {
|
|
37
49
|
if (event.data.type === "MODULES_LIST") {
|
|
38
50
|
clearTimeout(timeoutId);
|
|
39
51
|
navigator.serviceWorker.removeEventListener("message", messageHandler);
|
|
52
|
+
logger.debug(`[SW] Received ${event.data.modules.length} loaded modules from SW`);
|
|
40
53
|
resolve(event.data.modules);
|
|
41
54
|
}
|
|
42
55
|
};
|
|
@@ -44,16 +57,20 @@ export default defineNuxtPlugin({
|
|
|
44
57
|
sw.postMessage({ type: "GET_MODULES" });
|
|
45
58
|
timeoutId = setTimeout(() => {
|
|
46
59
|
navigator.serviceWorker.removeEventListener("message", messageHandler);
|
|
60
|
+
logger.debug("[SW] Timeout waiting for modules list from service worker");
|
|
47
61
|
resolve([]);
|
|
48
62
|
}, 5e3);
|
|
49
63
|
});
|
|
50
64
|
}
|
|
51
65
|
async function checkDeletedChunks(deletedChunks, passedReleases) {
|
|
52
66
|
if (deletedChunks.length === 0) {
|
|
67
|
+
logger.debug("[SW] No deleted chunks to check");
|
|
53
68
|
return;
|
|
54
69
|
}
|
|
70
|
+
logger.debug(`[SW] Checking ${deletedChunks.length} deleted chunks against loaded modules`);
|
|
55
71
|
const loadedModules = await getLoadedModules();
|
|
56
72
|
if (loadedModules.length === 0) {
|
|
73
|
+
logger.debug("[SW] No loaded modules to check against");
|
|
57
74
|
return;
|
|
58
75
|
}
|
|
59
76
|
const normalizedDeletedChunks = new Set(deletedChunks.map(normalizePath));
|
|
@@ -61,7 +78,13 @@ export default defineNuxtPlugin({
|
|
|
61
78
|
const normalizedModule = normalizePath(module);
|
|
62
79
|
return normalizedDeletedChunks.has(normalizedModule);
|
|
63
80
|
});
|
|
81
|
+
logger.debug(`[SW] Found ${invalidatedModules.length} invalidated modules`);
|
|
64
82
|
if (invalidatedModules.length > 0) {
|
|
83
|
+
logger.debug("[SW] Triggering chunks-outdated hook with:", {
|
|
84
|
+
deletedChunks,
|
|
85
|
+
invalidatedModules,
|
|
86
|
+
passedReleases
|
|
87
|
+
});
|
|
65
88
|
await nuxtApp.hooks.callHook("skew-protection:chunks-outdated", {
|
|
66
89
|
deletedChunks,
|
|
67
90
|
invalidatedModules,
|
|
@@ -70,17 +93,22 @@ export default defineNuxtPlugin({
|
|
|
70
93
|
}
|
|
71
94
|
}
|
|
72
95
|
onAppOutdated(async (_manifest) => {
|
|
96
|
+
logger.debug("[SW] App outdated event received");
|
|
73
97
|
const versions = _manifest?.skewProtection?.versions;
|
|
74
98
|
if (!versions) {
|
|
99
|
+
logger.debug("[SW] No version information in manifest");
|
|
75
100
|
return;
|
|
76
101
|
}
|
|
77
102
|
const newVersionId = _manifest.id;
|
|
103
|
+
logger.debug(`[SW] Checking version transition: ${clientVersion} \u2192 ${newVersionId}`);
|
|
78
104
|
const sortedVersions = Object.entries(versions).map(([id, data]) => ({ id, timestamp: new Date(data.timestamp).getTime() })).sort((a, b) => a.timestamp - b.timestamp);
|
|
79
105
|
const currentIdx = sortedVersions.findIndex((v) => v.id === clientVersion);
|
|
80
106
|
const newIdx = sortedVersions.findIndex((v) => v.id === newVersionId);
|
|
107
|
+
logger.debug(`[SW] Version indices - current: ${currentIdx}, new: ${newIdx}`);
|
|
81
108
|
const allDeletedChunks = [];
|
|
82
109
|
const passedReleases = [];
|
|
83
110
|
if (currentIdx === -1) {
|
|
111
|
+
logger.debug("[SW] Current version not found in manifest, checking all versions");
|
|
84
112
|
for (const version of sortedVersions) {
|
|
85
113
|
passedReleases.push(version.id);
|
|
86
114
|
const versionData = versions[version.id];
|
|
@@ -89,6 +117,7 @@ export default defineNuxtPlugin({
|
|
|
89
117
|
}
|
|
90
118
|
}
|
|
91
119
|
} else if (newIdx === -1) {
|
|
120
|
+
logger.debug("[SW] New version not in manifest, checking all versions after current");
|
|
92
121
|
for (let i = currentIdx + 1; i < sortedVersions.length; i++) {
|
|
93
122
|
const version = sortedVersions[i];
|
|
94
123
|
if (version) {
|
|
@@ -100,6 +129,7 @@ export default defineNuxtPlugin({
|
|
|
100
129
|
}
|
|
101
130
|
}
|
|
102
131
|
} else {
|
|
132
|
+
logger.debug(`[SW] Checking versions between current (${currentIdx}) and new (${newIdx})`);
|
|
103
133
|
for (let i = currentIdx + 1; i <= newIdx; i++) {
|
|
104
134
|
const version = sortedVersions[i];
|
|
105
135
|
if (version) {
|
|
@@ -111,10 +141,12 @@ export default defineNuxtPlugin({
|
|
|
111
141
|
}
|
|
112
142
|
}
|
|
113
143
|
}
|
|
144
|
+
logger.debug(`[SW] Collected ${allDeletedChunks.length} deleted chunks across ${passedReleases.length} releases`);
|
|
114
145
|
if (allDeletedChunks.length > 0) {
|
|
115
146
|
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
116
147
|
await checkDeletedChunks(allDeletedChunks, passedReleases);
|
|
117
148
|
}
|
|
149
|
+
logger.debug("[SW] Resetting modules in service worker");
|
|
118
150
|
swRegistration.then((reg) => reg.active?.postMessage({ type: "RESET_MODULES" }));
|
|
119
151
|
});
|
|
120
152
|
}
|
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
import { createConsola } from "consola";
|
|
2
|
+
import { useRuntimeConfig } from "nuxt/app";
|
|
2
3
|
export const logger = createConsola({
|
|
3
4
|
defaults: {
|
|
4
5
|
tag: "nuxt-skew-protection"
|
|
5
6
|
}
|
|
6
7
|
});
|
|
8
|
+
export function init() {
|
|
9
|
+
const config = useRuntimeConfig();
|
|
10
|
+
logger.level = config.public.skewProtection.debug ? 4 : 3;
|
|
11
|
+
}
|
package/dist/runtime/types.d.ts
CHANGED
|
@@ -19,8 +19,3 @@ export interface ChunksOutdatedPayload {
|
|
|
19
19
|
invalidatedModules: string[];
|
|
20
20
|
passedReleases: string[];
|
|
21
21
|
}
|
|
22
|
-
declare module '#app' {
|
|
23
|
-
interface RuntimeNuxtHooks {
|
|
24
|
-
'skew-protection:chunks-outdated': (payload: ChunksOutdatedPayload) => void | Promise<void>;
|
|
25
|
-
}
|
|
26
|
-
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const loadedModules=new Set;self.addEventListener("activate",e=>{e.waitUntil(self.clients.claim())}),self.addEventListener("fetch",e=>{const t=e.request.url;(e.request.destination==="script"||t.endsWith(".js"))&&(loadedModules.add(t),e.waitUntil(self.clients.matchAll().then(a=>{a.forEach(s=>{s.postMessage({type:"MODULE_LOADED",url:t,modules:Array.from(loadedModules)})})})))}),self.addEventListener("message",e=>{if(e.data.type==="GET_MODULES"){const t=Array.from(loadedModules);e.source.postMessage({type:"MODULES_LIST",modules:t})}if(e.data.type==="CHECK_MODULE"){const t=loadedModules.has(e.data.url);e.source.postMessage({type:"MODULE_STATUS",url:e.data.url,loaded:t})}e.data.type==="RESET_MODULES"&&(loadedModules.clear(),e.source.postMessage({type:"MODULES_RESET",success:!0})),e.data.type==="ADD_MODULE"&&loadedModules.add(e.data.url)});
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nuxt-skew-protection",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.2.
|
|
4
|
+
"version": "0.2.3",
|
|
5
5
|
"description": "Instantly adopted Nuxt releases with long-lived build assets.",
|
|
6
6
|
"author": {
|
|
7
7
|
"name": "Harlan Wilton",
|
|
@@ -86,7 +86,7 @@
|
|
|
86
86
|
},
|
|
87
87
|
"scripts": {
|
|
88
88
|
"lint": "eslint . --fix",
|
|
89
|
-
"build": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxt-module-build build",
|
|
89
|
+
"build": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxt-module-build build && unbuild --config sw.build.config.ts",
|
|
90
90
|
"dev": "nuxi dev playground",
|
|
91
91
|
"dev:build": "nuxi build playground",
|
|
92
92
|
"dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxt-module-build build && nuxi prepare playground",
|