nuxt-skew-protection 0.1.6 → 0.2.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/dist/module.cjs CHANGED
@@ -633,9 +633,6 @@ export {}
633
633
  name: "SkewNotification",
634
634
  filePath: resolver.resolve(`./runtime/app/components/SkewNotification.vue`)
635
635
  });
636
- kit.addPlugin({
637
- src: resolver.resolve("./runtime/app/plugins/0.skew-protection")
638
- });
639
636
  kit.addImports({
640
637
  name: "useSkewProtection",
641
638
  from: resolver.resolve("./runtime/app/composables/useSkewProtection")
@@ -658,10 +655,12 @@ export {}
658
655
  middleware: true
659
656
  });
660
657
  }
661
- kit.addServerHandler({
662
- handler: resolver.resolve("./runtime/server/middleware/set-skew-protection-cookie"),
663
- middleware: true
664
- });
658
+ if (options.cookie !== false) {
659
+ kit.addServerHandler({
660
+ handler: resolver.resolve("./runtime/server/middleware/set-skew-protection-cookie"),
661
+ middleware: true
662
+ });
663
+ }
665
664
  kit.addPlugin({
666
665
  src: resolver.resolve("./runtime/app/plugins/sw-track-user-modules.client"),
667
666
  mode: "client"
package/dist/module.d.cts CHANGED
@@ -30,7 +30,7 @@ interface ModuleOptions {
30
30
  /**
31
31
  * Cookie configuration for storing deployment version
32
32
  */
33
- cookie?: Omit<CookieSerializeOptions, 'encode'> & {
33
+ cookie?: false | Omit<CookieSerializeOptions, 'encode'> & {
34
34
  /**
35
35
  * Cookie name for storing deployment version
36
36
  * @default '__nkpv'
package/dist/module.d.mts CHANGED
@@ -30,7 +30,7 @@ interface ModuleOptions {
30
30
  /**
31
31
  * Cookie configuration for storing deployment version
32
32
  */
33
- cookie?: Omit<CookieSerializeOptions, 'encode'> & {
33
+ cookie?: false | Omit<CookieSerializeOptions, 'encode'> & {
34
34
  /**
35
35
  * Cookie name for storing deployment version
36
36
  * @default '__nkpv'
package/dist/module.d.ts CHANGED
@@ -30,7 +30,7 @@ interface ModuleOptions {
30
30
  /**
31
31
  * Cookie configuration for storing deployment version
32
32
  */
33
- cookie?: Omit<CookieSerializeOptions, 'encode'> & {
33
+ cookie?: false | Omit<CookieSerializeOptions, 'encode'> & {
34
34
  /**
35
35
  * Cookie name for storing deployment version
36
36
  * @default '__nkpv'
package/dist/module.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "nuxt": ">=4.0.0"
5
5
  },
6
6
  "configKey": "skewProtection",
7
- "version": "0.1.6",
7
+ "version": "0.2.0",
8
8
  "builder": {
9
9
  "@nuxt/module-builder": "1.0.2",
10
10
  "unbuild": "3.6.1"
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, addPlugin, addImports, addServerHandler } from '@nuxt/kit';
2
+ import { useNuxt, tryUseNuxt, useLogger, defineNuxtModule, createResolver, addTypeTemplate, addComponent, addImports, addServerHandler, addPlugin } 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';
@@ -630,9 +630,6 @@ export {}
630
630
  name: "SkewNotification",
631
631
  filePath: resolver.resolve(`./runtime/app/components/SkewNotification.vue`)
632
632
  });
633
- addPlugin({
634
- src: resolver.resolve("./runtime/app/plugins/0.skew-protection")
635
- });
636
633
  addImports({
637
634
  name: "useSkewProtection",
638
635
  from: resolver.resolve("./runtime/app/composables/useSkewProtection")
@@ -655,10 +652,12 @@ export {}
655
652
  middleware: true
656
653
  });
657
654
  }
658
- addServerHandler({
659
- handler: resolver.resolve("./runtime/server/middleware/set-skew-protection-cookie"),
660
- middleware: true
661
- });
655
+ if (options.cookie !== false) {
656
+ addServerHandler({
657
+ handler: resolver.resolve("./runtime/server/middleware/set-skew-protection-cookie"),
658
+ middleware: true
659
+ });
660
+ }
662
661
  addPlugin({
663
662
  src: resolver.resolve("./runtime/app/plugins/sw-track-user-modules.client"),
664
663
  mode: "client"
@@ -1,6 +1,6 @@
1
1
  <script setup>
2
- import { reloadNuxtApp } from "#imports";
3
2
  import { useTimeAgo } from "@vueuse/core";
3
+ import { reloadNuxtApp } from "nuxt/app";
4
4
  import { computed, ref } from "vue";
5
5
  import { useSkewProtection } from "../composables/useSkewProtection";
6
6
  const props = defineProps({
@@ -54,10 +54,12 @@ async function handleReload() {
54
54
  persistState: true
55
55
  });
56
56
  }
57
+ const shouldRender = import.meta.client && !import.meta.prerender;
57
58
  </script>
58
59
 
59
60
  <template>
60
61
  <slot
62
+ v-if="shouldRender"
61
63
  :is-current-chunks-outdated="isCurrentChunksOutdated"
62
64
  :dismiss="handleDismiss"
63
65
  :reload="handleReload"
@@ -1,13 +1,12 @@
1
- import type { NuxtAppManifestMeta } from '#app';
2
- import type { Ref } from 'vue';
1
+ import type { NuxtAppManifestMeta } from 'nuxt/app';
3
2
  import type { ChunksOutdatedPayload } from '../../types.js';
3
+ export declare function checkForUpdates(): Promise<void>;
4
4
  export declare function useSkewProtection(): {
5
- cookie: import("#app").CookieRef<any>;
5
+ manifest: import("vue").Ref<NuxtAppManifestMeta | undefined, NuxtAppManifestMeta | undefined>;
6
+ clientVersion: any;
7
+ isOutdated: import("vue").ComputedRef<boolean | undefined>;
6
8
  onCurrentChunksOutdated: (callback: (payload: ChunksOutdatedPayload) => void | Promise<void>) => () => void;
7
- onAppOutdated: (callback: (manifest?: NuxtAppManifestMeta) => void | Promise<void>) => void;
8
- checkForUpdates: () => Promise<void>;
9
+ onAppOutdated: (callback: (manifest?: NuxtAppManifestMeta) => void | Promise<void>) => () => void;
10
+ checkForUpdates: typeof checkForUpdates;
9
11
  simulateUpdate(): Promise<void>;
10
- manifest: Ref<NuxtAppManifestMeta | null>;
11
- currentVersion: string | undefined;
12
- isOutdated: Ref<boolean>;
13
12
  };
@@ -1,25 +1,22 @@
1
- import { useCookie, useNuxtApp, useRuntimeConfig } from "#app";
2
1
  import { buildAssetsURL } from "#internal/nuxt/paths";
3
- import { onUnmounted } from "vue";
4
- import { useRuntimeConfigSkewProtection } from "./useRuntimeConfigSkewProtection.js";
5
- export function useSkewProtection() {
2
+ import { useNuxtApp, useRuntimeConfig } from "nuxt/app";
3
+ import { computed, onUnmounted, ref } from "vue";
4
+ export async function checkForUpdates() {
6
5
  const nuxtApp = useNuxtApp();
7
- const config = useRuntimeConfig();
8
- const { cookie: cookieConfig } = useRuntimeConfigSkewProtection();
9
- const { name: cookieName, ...cookieOptions } = cookieConfig;
10
- const cookie = useCookie(cookieName, {
11
- default: () => config.app.buildId,
12
- ...cookieOptions
6
+ const runtimeConfig = useRuntimeConfig();
7
+ const clientVersion = runtimeConfig.app.buildId;
8
+ const meta = await $fetch(`${buildAssetsURL("builds/latest.json")}?${Date.now()}`).catch(() => {
9
+ return null;
13
10
  });
14
- const skewProtection = nuxtApp.$skewProtection;
15
- async function checkForUpdates() {
16
- const meta = await $fetch(`${buildAssetsURL("builds/latest.json")}?${Date.now()}`).catch(() => {
17
- return null;
18
- });
19
- if (meta && meta?.id !== skewProtection.currentVersion) {
20
- await nuxtApp.hooks.callHook("app:manifest:update", meta);
21
- }
11
+ if (meta && meta?.id !== clientVersion) {
12
+ await nuxtApp.hooks.callHook("app:manifest:update", meta);
22
13
  }
14
+ }
15
+ export function useSkewProtection() {
16
+ const nuxtApp = useNuxtApp();
17
+ const runtimeConfig = useRuntimeConfig();
18
+ const clientVersion = runtimeConfig.app.buildId;
19
+ const manifest = ref();
23
20
  function onCurrentChunksOutdated(callback) {
24
21
  const hook = nuxtApp.hooks.hook("skew-protection:chunks-outdated", callback);
25
22
  onUnmounted(() => {
@@ -30,16 +27,21 @@ export function useSkewProtection() {
30
27
  return hook;
31
28
  }
32
29
  function onAppOutdated(callback) {
33
- const hook = nuxtApp.hooks.hook("app:manifest:update", callback);
30
+ const hook = nuxtApp.hooks.hook("app:manifest:update", (_manifest) => {
31
+ manifest.value = _manifest;
32
+ callback(_manifest);
33
+ });
34
34
  onUnmounted(() => {
35
35
  if (typeof hook === "function") {
36
36
  hook();
37
37
  }
38
38
  });
39
+ return hook;
39
40
  }
40
41
  return {
41
- ...skewProtection,
42
- cookie,
42
+ manifest,
43
+ clientVersion,
44
+ isOutdated: computed(() => manifest.value && clientVersion !== manifest.value.id),
43
45
  onCurrentChunksOutdated,
44
46
  onAppOutdated,
45
47
  checkForUpdates,
@@ -1,13 +1,13 @@
1
- import { defineNuxtPlugin } from "#app";
1
+ import { defineNuxtPlugin, useRuntimeConfig } from "#app";
2
2
  import { useEventSource } from "@vueuse/core";
3
3
  import { watch } from "vue";
4
4
  import { logger } from "../../shared/logger.js";
5
- import { useSkewProtection } from "../composables/useSkewProtection.js";
5
+ import { checkForUpdates } from "../composables/useSkewProtection.js";
6
6
  export default defineNuxtPlugin({
7
7
  name: "skew-protection:sse-updates",
8
- setup() {
9
- const skew = useSkewProtection();
10
- const clientVersion = skew.cookie.value;
8
+ setup(nuxtApp) {
9
+ const runtimeConfig = useRuntimeConfig();
10
+ const clientVersion = runtimeConfig.app.buildId;
11
11
  const { data } = useEventSource(`/_skew/sse`, [], {
12
12
  autoReconnect: {
13
13
  retries: 10,
@@ -28,7 +28,7 @@ export default defineNuxtPlugin({
28
28
  if (message.type === "connected" && message.version) {
29
29
  const newVersion = message.version;
30
30
  if (newVersion !== clientVersion) {
31
- skew.checkForUpdates();
31
+ nuxtApp.runWithContext(checkForUpdates);
32
32
  }
33
33
  }
34
34
  });
@@ -1,19 +1,18 @@
1
- import { defineNuxtPlugin } from "#app";
1
+ import { defineNuxtPlugin, useRuntimeConfig } from "#app";
2
2
  import { useWebSocket } from "@vueuse/core";
3
3
  import { watch } from "vue";
4
4
  import { logger } from "../../shared/logger.js";
5
5
  import { useRuntimeConfigSkewProtection } from "../composables/useRuntimeConfigSkewProtection.js";
6
- import { useSkewProtection } from "../composables/useSkewProtection.js";
6
+ import { checkForUpdates } from "../composables/useSkewProtection.js";
7
7
  export default defineNuxtPlugin({
8
8
  name: "skew-protection:websocket-updates",
9
9
  setup(nuxtApp) {
10
10
  const skewConfig = useRuntimeConfigSkewProtection();
11
- const skewProtection = useSkewProtection();
12
- const versionCookie = skewProtection.cookie;
11
+ const runtimeConfig = useRuntimeConfig();
12
+ const clientVersion = runtimeConfig.app.buildId;
13
13
  const protocol = typeof window !== "undefined" && window.location.protocol === "https:" ? "wss:" : "ws:";
14
14
  const url = typeof window !== "undefined" ? `${protocol}//${window.location.host}/_skew/ws` : "";
15
15
  const {
16
- status,
17
16
  data,
18
17
  open,
19
18
  close
@@ -44,11 +43,8 @@ export default defineNuxtPlugin({
44
43
  const parsed = JSON.parse(message);
45
44
  if (parsed.type === "version-update" && parsed.version) {
46
45
  const newVersion = parsed.version;
47
- if (newVersion !== versionCookie.value) {
48
- nuxtApp.hooks.callHook("app:manifest:update", {
49
- id: newVersion,
50
- timestamp: parsed.timestamp || Date.now()
51
- });
46
+ if (newVersion !== clientVersion) {
47
+ nuxtApp.runWithContext(checkForUpdates);
52
48
  if (skewConfig.debug) {
53
49
  logger.info(`Version update received via WebSocket: ${newVersion}`);
54
50
  }
@@ -66,22 +62,16 @@ export default defineNuxtPlugin({
66
62
  logger.error("Failed to parse WebSocket message:", error);
67
63
  }
68
64
  });
69
- watch(status, (newStatus) => {
70
- if (skewConfig.debug) {
71
- if (newStatus === "OPEN") {
72
- logger.info("WebSocket connection established");
73
- } else if (newStatus === "CONNECTING") {
74
- logger.info("WebSocket connecting...");
75
- } else if (newStatus === "CLOSED") {
76
- logger.info("WebSocket connection closed");
77
- }
78
- }
79
- });
80
65
  nuxtApp.hook("app:mounted", () => {
81
66
  open();
82
67
  });
83
68
  nuxtApp.hook("app:error", () => {
84
69
  close();
85
70
  });
71
+ if (import.meta.client) {
72
+ window.addEventListener("beforeunload", () => {
73
+ close();
74
+ });
75
+ }
86
76
  }
87
77
  });
@@ -1,12 +1,9 @@
1
- import type { NuxtAppManifestMeta } from '#app';
2
1
  declare const _default: import("#app").Plugin<{
3
2
  skewServiceWorker: {
4
- manifest: import("vue").Ref<NuxtAppManifestMeta | undefined, NuxtAppManifestMeta | undefined>;
5
3
  getLoadedModules: () => Promise<string[]>;
6
4
  };
7
5
  }> & import("#app").ObjectPlugin<{
8
6
  skewServiceWorker: {
9
- manifest: import("vue").Ref<NuxtAppManifestMeta | undefined, NuxtAppManifestMeta | undefined>;
10
7
  getLoadedModules: () => Promise<string[]>;
11
8
  };
12
9
  }>;
@@ -1,6 +1,4 @@
1
- import { defineNuxtPlugin } from "#app";
2
- import { ref } from "vue";
3
- import { useSkewProtection } from "../composables/useSkewProtection.js";
1
+ import { defineNuxtPlugin, useRuntimeConfig } from "#app";
4
2
  function normalizePath(pathOrUrl) {
5
3
  try {
6
4
  const url = new URL(pathOrUrl);
@@ -15,21 +13,22 @@ export default defineNuxtPlugin({
15
13
  if (!("serviceWorker" in navigator)) {
16
14
  return;
17
15
  }
18
- const skew = useSkewProtection();
19
- const versionCookie = skew.cookie.value;
20
- const manifest = ref();
16
+ const runtimeConfig = useRuntimeConfig();
17
+ const clientVersion = runtimeConfig.app.buildId;
21
18
  navigator.serviceWorker.register("/_skew/sw.js");
22
19
  function getLoadedModules() {
23
20
  return new Promise((resolve) => {
21
+ let timeoutId;
24
22
  const messageHandler = (event) => {
25
23
  if (event.data.type === "MODULES_LIST") {
24
+ clearTimeout(timeoutId);
26
25
  navigator.serviceWorker.removeEventListener("message", messageHandler);
27
26
  resolve(event.data.modules);
28
27
  }
29
28
  };
30
29
  navigator.serviceWorker.addEventListener("message", messageHandler);
31
30
  navigator.serviceWorker.controller?.postMessage({ type: "GET_MODULES" });
32
- setTimeout(() => {
31
+ timeoutId = setTimeout(() => {
33
32
  navigator.serviceWorker.removeEventListener("message", messageHandler);
34
33
  resolve([]);
35
34
  }, 5e3);
@@ -56,20 +55,18 @@ export default defineNuxtPlugin({
56
55
  });
57
56
  }
58
57
  }
59
- nuxtApp.hook("app:manifest:update", async (_manifest) => {
60
- manifest.value = _manifest;
58
+ nuxtApp.hooks.hook("app:manifest:update", async (_manifest) => {
61
59
  const versions = _manifest?.skewProtection?.versions;
62
60
  if (!versions) {
63
61
  return;
64
62
  }
65
63
  const newVersionId = _manifest.id;
66
- const currentVersionId = versionCookie.value;
67
- if (!currentVersionId || currentVersionId === newVersionId) {
64
+ if (!clientVersion || clientVersion === newVersionId) {
68
65
  return;
69
66
  }
70
67
  navigator.serviceWorker.controller?.postMessage({ type: "RESET_MODULES" });
71
68
  const sortedVersions = Object.entries(versions).map(([id, data]) => ({ id, timestamp: new Date(data.timestamp).getTime() })).sort((a, b) => a.timestamp - b.timestamp);
72
- const currentIdx = sortedVersions.findIndex((v) => v.id === currentVersionId);
69
+ const currentIdx = sortedVersions.findIndex((v) => v.id === clientVersion);
73
70
  const newIdx = sortedVersions.findIndex((v) => v.id === newVersionId);
74
71
  if (currentIdx === -1 || newIdx === -1) {
75
72
  return;
@@ -93,7 +90,6 @@ export default defineNuxtPlugin({
93
90
  return {
94
91
  provide: {
95
92
  skewServiceWorker: {
96
- manifest,
97
93
  getLoadedModules
98
94
  }
99
95
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nuxt-skew-protection",
3
3
  "type": "module",
4
- "version": "0.1.6",
4
+ "version": "0.2.0",
5
5
  "description": "Instantly adopted Nuxt releases with long-lived build assets.",
6
6
  "author": {
7
7
  "name": "Harlan Wilton",
@@ -31,6 +31,7 @@
31
31
  "dependencies": {
32
32
  "@nuxt/kit": "^4.1.3",
33
33
  "@nuxtjs/robots": "^5.5.5",
34
+ "@vueuse/core": "^13.9.0",
34
35
  "consola": "^3.4.2",
35
36
  "cookie-es": "^2.0.0",
36
37
  "defu": "^6.1.4",
@@ -1,27 +0,0 @@
1
- import type { NuxtAppManifestMeta } from '#app';
2
- declare const _default: import("#app").Plugin<{
3
- skewProtection: {
4
- manifest: import("vue").Ref<{
5
- id: string;
6
- timestamp: number;
7
- } | null, NuxtAppManifestMeta | {
8
- id: string;
9
- timestamp: number;
10
- } | null>;
11
- currentVersion: any;
12
- isOutdated: import("vue").ComputedRef<boolean>;
13
- };
14
- }> & import("#app").ObjectPlugin<{
15
- skewProtection: {
16
- manifest: import("vue").Ref<{
17
- id: string;
18
- timestamp: number;
19
- } | null, NuxtAppManifestMeta | {
20
- id: string;
21
- timestamp: number;
22
- } | null>;
23
- currentVersion: any;
24
- isOutdated: import("vue").ComputedRef<boolean>;
25
- };
26
- }>;
27
- export default _default;
@@ -1,41 +0,0 @@
1
- import { useRuntimeConfig } from "#app";
2
- import { useWindowFocus } from "@vueuse/core";
3
- import { defineNuxtPlugin } from "nuxt/app";
4
- import { computed, ref, watch } from "vue";
5
- import { useSkewProtection } from "../composables/useSkewProtection.js";
6
- export default defineNuxtPlugin({
7
- name: "skew-protection:root",
8
- setup(nuxtApp) {
9
- const runtimeConfig = useRuntimeConfig();
10
- const skewProtection = useSkewProtection();
11
- const currentVersion = runtimeConfig.app.buildId || skewProtection.cookie.value;
12
- const latestVersion = ref(currentVersion);
13
- const manifest = ref(null);
14
- const isOutdated = computed(() => currentVersion !== latestVersion.value);
15
- if (import.meta.client) {
16
- nuxtApp.hooks.hook("app:manifest:update", (_manifest) => {
17
- if (_manifest) {
18
- manifest.value = _manifest;
19
- const newVersion = _manifest.id;
20
- if (newVersion && newVersion !== latestVersion.value) {
21
- latestVersion.value = newVersion;
22
- }
23
- }
24
- });
25
- const focused = useWindowFocus();
26
- watch(focused, () => {
27
- if (isOutdated.value) {
28
- }
29
- });
30
- }
31
- return {
32
- provide: {
33
- skewProtection: {
34
- manifest,
35
- currentVersion,
36
- isOutdated
37
- }
38
- }
39
- };
40
- }
41
- });