nuxt-skew-protection 0.4.3 → 0.6.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 +1 -0
- package/dist/module.d.mts +6 -0
- package/dist/module.json +6 -1
- package/dist/module.mjs +105 -47
- package/dist/runtime/adapters/ably/node.js +3 -2
- package/dist/runtime/adapters/ably/web.js +3 -2
- package/dist/runtime/adapters/pusher/node.js +3 -2
- package/dist/runtime/adapters/pusher/web.js +3 -2
- package/dist/runtime/app/composables/useActiveConnections.d.ts +8 -0
- package/dist/runtime/app/composables/useActiveConnections.js +21 -0
- package/dist/runtime/app/composables/useRuntimeConfigSkewProtection.d.ts +0 -1
- package/dist/runtime/app/composables/useRuntimeConfigSkewProtection.js +1 -5
- package/dist/runtime/app/composables/useSkewProtection.d.ts +13 -1
- package/dist/runtime/app/composables/useSkewProtection.js +43 -8
- package/dist/runtime/app/plugins/check-updates-adapter.client.d.ts +7 -1
- package/dist/runtime/app/plugins/check-updates-adapter.client.js +19 -36
- package/dist/runtime/app/plugins/check-updates-sse.client.d.ts +7 -1
- package/dist/runtime/app/plugins/check-updates-sse.client.js +21 -36
- package/dist/runtime/app/plugins/check-updates-websocket.client.d.ts +7 -15
- package/dist/runtime/app/plugins/check-updates-websocket.client.js +35 -71
- package/dist/runtime/app/types.d.ts +25 -0
- package/dist/runtime/app/types.js +0 -0
- package/dist/runtime/app/utils/create-skew-connection.d.ts +17 -0
- package/dist/runtime/app/utils/create-skew-connection.js +48 -0
- package/dist/runtime/const.d.ts +7 -0
- package/dist/runtime/const.js +6 -0
- package/dist/runtime/server/middleware/set-skew-protection-cookie.js +4 -7
- package/dist/runtime/server/plugins/connection-tracking-cloudflare-durable.d.ts +2 -0
- package/dist/runtime/server/plugins/connection-tracking-cloudflare-durable.js +34 -0
- package/dist/runtime/server/plugins/connection-tracking.d.ts +2 -0
- package/dist/runtime/server/plugins/connection-tracking.js +25 -0
- package/dist/runtime/server/routes/_skew/sse.js +13 -7
- package/dist/runtime/server/routes/_skew/ws.js +20 -4
- package/dist/runtime/types.d.ts +2 -1
- package/package.json +7 -4
- package/dist/runtime/app/plugins/init-build-id.d.ts +0 -12
- package/dist/runtime/app/plugins/init-build-id.js +0 -29
package/README.md
CHANGED
|
@@ -24,6 +24,7 @@ Nuxt Skew Protection solves this with proactive update prompts and persistent bu
|
|
|
24
24
|
- ⚡ **Instant Update Prompts** - Zero-config real-time notifications on deploy. Users adopt your latest build immediately.
|
|
25
25
|
- 🎯 **Chunk-Aware Targeting** - Notifications fire only when the user's loaded chunks are invalidated. No noise for unrelated updates.
|
|
26
26
|
- 🎨 **Headless UI** - Drop-in notification component with first-class Nuxt UI support.
|
|
27
|
+
- 📊 **Live Connection Monitoring** - Track active users and version distribution in real-time for admin dashboards and rollout progress.
|
|
27
28
|
- 🔌 **Third-Party Adapters** - Real-time updates on any platform (including static sites) via [Pusher](https://pusher.com) or [Ably](https://ably.com).
|
|
28
29
|
|
|
29
30
|
## Installation
|
package/dist/module.d.mts
CHANGED
|
@@ -56,6 +56,12 @@ interface ModuleOptions {
|
|
|
56
56
|
* @default false
|
|
57
57
|
*/
|
|
58
58
|
debug?: boolean;
|
|
59
|
+
/**
|
|
60
|
+
* Enable connection tracking to monitor active SSE/WebSocket connections
|
|
61
|
+
* Exposes useActiveConnections() composable with real-time stats
|
|
62
|
+
* @default false
|
|
63
|
+
*/
|
|
64
|
+
connectionTracking?: boolean;
|
|
59
65
|
}
|
|
60
66
|
interface ModulePublicRuntimeConfig {
|
|
61
67
|
skewProtection: NuxtSkewProtectionRuntimeConfig;
|
package/dist/module.json
CHANGED
|
@@ -4,7 +4,12 @@
|
|
|
4
4
|
"nuxt": ">=4.0.0"
|
|
5
5
|
},
|
|
6
6
|
"configKey": "skewProtection",
|
|
7
|
-
"
|
|
7
|
+
"moduleDependencies": {
|
|
8
|
+
"@nuxtjs/robots": {
|
|
9
|
+
"version": ">=5.6.7"
|
|
10
|
+
}
|
|
11
|
+
},
|
|
12
|
+
"version": "0.6.0",
|
|
8
13
|
"builder": {
|
|
9
14
|
"@nuxt/module-builder": "1.0.2",
|
|
10
15
|
"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 { useLogger, useNuxt, tryUseNuxt, defineNuxtModule, createResolver, hasNuxtModule, addTypeTemplate, addComponent, addImports,
|
|
2
|
+
import { useLogger, useNuxt, tryUseNuxt, defineNuxtModule, createResolver, hasNuxtModule, addTypeTemplate, addComponent, addImports, addServerHandler, addPlugin, tryResolveModule, addTemplate } from '@nuxt/kit';
|
|
3
3
|
import { colors } from 'consola/utils';
|
|
4
4
|
import { useSiteConfig, installNuxtSiteConfig } from 'nuxt-site-config/kit';
|
|
5
5
|
import { readPackageJSON } from 'pkg-types';
|
|
@@ -242,6 +242,29 @@ function isSkewAdapter(value) {
|
|
|
242
242
|
return typeof value === "object" && value !== null && "name" in value && "subscribe" in value && "broadcast" in value && typeof value.subscribe === "function" && typeof value.broadcast === "function";
|
|
243
243
|
}
|
|
244
244
|
|
|
245
|
+
function formatStorageError(error, operation) {
|
|
246
|
+
const cause = error instanceof Error ? error.cause : void 0;
|
|
247
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
248
|
+
const causeMessage = cause?.message || "";
|
|
249
|
+
if (causeMessage.includes("ENOTFOUND") || causeMessage.includes("getaddrinfo")) {
|
|
250
|
+
const hostMatch = causeMessage.match(/ENOTFOUND\s+(\S+)/) || causeMessage.match(/getaddrinfo\s+\S+\s+(\S+)/);
|
|
251
|
+
const host = hostMatch?.[1] || "unknown host";
|
|
252
|
+
return new Error(`Storage ${operation} failed: Could not resolve host '${host}'. Check your storage URL/credentials are correct.`);
|
|
253
|
+
}
|
|
254
|
+
if (causeMessage.includes("ECONNREFUSED") || message.includes("ECONNREFUSED")) {
|
|
255
|
+
return new Error(`Storage ${operation} failed: Connection refused. Is the storage server running and accessible?`);
|
|
256
|
+
}
|
|
257
|
+
if (message.includes("401") || message.includes("Unauthorized") || message.includes("WRONGPASS")) {
|
|
258
|
+
return new Error(`Storage ${operation} failed: Authentication failed. Check your storage credentials.`);
|
|
259
|
+
}
|
|
260
|
+
if (message.includes("timeout") || message.includes("ETIMEDOUT")) {
|
|
261
|
+
return new Error(`Storage ${operation} failed: Connection timed out. Check network connectivity to storage.`);
|
|
262
|
+
}
|
|
263
|
+
if (message === "fetch failed") {
|
|
264
|
+
return new Error(`Storage ${operation} failed: Network error. ${causeMessage || "Check your storage configuration."}`);
|
|
265
|
+
}
|
|
266
|
+
return new Error(`Storage ${operation} failed: ${message}`);
|
|
267
|
+
}
|
|
245
268
|
async function processBatch(items, batchSize, processor) {
|
|
246
269
|
const results = [];
|
|
247
270
|
for (let i = 0; i < items.length; i += batchSize) {
|
|
@@ -284,24 +307,23 @@ async function getFilesRecursively(dir) {
|
|
|
284
307
|
return files;
|
|
285
308
|
}
|
|
286
309
|
async function getVersionManifest(storage) {
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
if (manifest && typeof manifest === "object" && "versions" in manifest)
|
|
310
|
+
const emptyManifest = { current: "", versions: {} };
|
|
311
|
+
return storage.getItem("version-manifest.json").then((manifest) => {
|
|
312
|
+
if (manifest && typeof manifest === "object" && "versions" in manifest)
|
|
290
313
|
return manifest;
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
return
|
|
298
|
-
|
|
299
|
-
versions: {}
|
|
300
|
-
};
|
|
301
|
-
}
|
|
314
|
+
return emptyManifest;
|
|
315
|
+
}).catch((e) => {
|
|
316
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
317
|
+
const cause = e instanceof Error ? e.cause?.message || "" : "";
|
|
318
|
+
if (cause.includes("ENOTFOUND") || cause.includes("ECONNREFUSED") || message.includes("401") || message === "fetch failed")
|
|
319
|
+
throw formatStorageError(e, "read");
|
|
320
|
+
return emptyManifest;
|
|
321
|
+
});
|
|
302
322
|
}
|
|
303
323
|
async function setVersionManifest(manifest, storage) {
|
|
304
|
-
await storage.setItem("version-manifest.json", manifest)
|
|
324
|
+
await storage.setItem("version-manifest.json", manifest).catch((e) => {
|
|
325
|
+
throw formatStorageError(e, "write");
|
|
326
|
+
});
|
|
305
327
|
}
|
|
306
328
|
function formatBytes(bytes) {
|
|
307
329
|
if (bytes < 1024)
|
|
@@ -321,9 +343,9 @@ function createAssetManager(options) {
|
|
|
321
343
|
});
|
|
322
344
|
const retentionDays = options.retentionDays || 7;
|
|
323
345
|
const maxNumberOfVersions = options.maxNumberOfVersions || 20;
|
|
324
|
-
async function getAssetsFromBuild(
|
|
346
|
+
async function getAssetsFromBuild(publicDir) {
|
|
325
347
|
const startTime = Date.now();
|
|
326
|
-
const nuxtDir = join$1(
|
|
348
|
+
const nuxtDir = join$1(publicDir, "_nuxt");
|
|
327
349
|
logger.debug(`Scanning build assets from ${nuxtDir}`);
|
|
328
350
|
const assets = [];
|
|
329
351
|
const nuxtFiles = await getFilesRecursively(nuxtDir);
|
|
@@ -427,10 +449,9 @@ function createAssetManager(options) {
|
|
|
427
449
|
await setVersionManifest(manifest, storage);
|
|
428
450
|
}
|
|
429
451
|
}
|
|
430
|
-
async function storeAssetsInStorage(buildId,
|
|
452
|
+
async function storeAssetsInStorage(buildId, publicDir, assets) {
|
|
431
453
|
const startTime = Date.now();
|
|
432
454
|
logger.debug(`storeAssetsInStorage: starting for ${buildId} (${assets.length} assets)`);
|
|
433
|
-
const publicDir = join$1(outputDir, "public");
|
|
434
455
|
const manifestStart = Date.now();
|
|
435
456
|
const manifest = await getVersionManifest(storage);
|
|
436
457
|
logger.debug(`storeAssetsInStorage: loaded manifest in ${formatDuration(Date.now() - manifestStart)}`);
|
|
@@ -509,7 +530,7 @@ function createAssetManager(options) {
|
|
|
509
530
|
createdAt: new Date(data.timestamp).getTime()
|
|
510
531
|
}));
|
|
511
532
|
}
|
|
512
|
-
async function restoreOldAssetsToPublic(currentBuildId,
|
|
533
|
+
async function restoreOldAssetsToPublic(currentBuildId, publicDir, currentAssets = [], isExistingVersion = false) {
|
|
513
534
|
const startTime = Date.now();
|
|
514
535
|
logger.debug(`restoreOldAssetsToPublic: starting for ${currentBuildId}`);
|
|
515
536
|
const manifestStart = Date.now();
|
|
@@ -525,7 +546,6 @@ function createAssetManager(options) {
|
|
|
525
546
|
}
|
|
526
547
|
const versionCount = Object.keys(manifest.versions).length - 1;
|
|
527
548
|
logger.debug(`restoreOldAssetsToPublic: checking ${versionCount} previous versions`);
|
|
528
|
-
const publicDir = join$1(outputDir, "public");
|
|
529
549
|
const restoredAssets = [];
|
|
530
550
|
const currentAssetsSet = new Set(currentAssets);
|
|
531
551
|
const currentFileIds = /* @__PURE__ */ new Set();
|
|
@@ -646,9 +666,9 @@ function createAssetManager(options) {
|
|
|
646
666
|
}
|
|
647
667
|
logger.debug(`restoreOldAssetsToPublic: total ${formatDuration(Date.now() - startTime)}`);
|
|
648
668
|
}
|
|
649
|
-
async function augmentBuildMetadata(buildId,
|
|
669
|
+
async function augmentBuildMetadata(buildId, publicDir) {
|
|
650
670
|
const manifest = await getVersionManifest(storage);
|
|
651
|
-
const latestPath = join$1(
|
|
671
|
+
const latestPath = join$1(publicDir, "_nuxt", "builds", "latest.json");
|
|
652
672
|
try {
|
|
653
673
|
const latestData = await promises.readFile(latestPath, "utf-8");
|
|
654
674
|
const latestJson = JSON.parse(latestData);
|
|
@@ -668,7 +688,7 @@ function createAssetManager(options) {
|
|
|
668
688
|
logger.warn("Failed to augment builds/latest.json:", error);
|
|
669
689
|
}
|
|
670
690
|
}
|
|
671
|
-
const metaPath = join$1(
|
|
691
|
+
const metaPath = join$1(publicDir, "_nuxt", "builds", "meta", `${buildId}.json`);
|
|
672
692
|
try {
|
|
673
693
|
const metaData = await promises.readFile(metaPath, "utf-8");
|
|
674
694
|
const metaJson = JSON.parse(metaData);
|
|
@@ -694,7 +714,8 @@ function createAssetManager(options) {
|
|
|
694
714
|
listExistingVersions,
|
|
695
715
|
restoreOldAssetsToPublic,
|
|
696
716
|
augmentBuildMetadata,
|
|
697
|
-
getManifest: () => getVersionManifest(storage)
|
|
717
|
+
getManifest: () => getVersionManifest(storage),
|
|
718
|
+
dispose: () => storage.dispose()
|
|
698
719
|
};
|
|
699
720
|
}
|
|
700
721
|
|
|
@@ -704,7 +725,12 @@ const module$1 = defineNuxtModule({
|
|
|
704
725
|
compatibility: {
|
|
705
726
|
nuxt: ">=4.0.0"
|
|
706
727
|
},
|
|
707
|
-
configKey: "skewProtection"
|
|
728
|
+
configKey: "skewProtection",
|
|
729
|
+
moduleDependencies: {
|
|
730
|
+
"@nuxtjs/robots": {
|
|
731
|
+
version: ">=5.6.7"
|
|
732
|
+
}
|
|
733
|
+
}
|
|
708
734
|
},
|
|
709
735
|
defaults: {
|
|
710
736
|
retentionDays: 30,
|
|
@@ -737,6 +763,7 @@ const module$1 = defineNuxtModule({
|
|
|
737
763
|
nuxt.options.runtimeConfig.public.skewProtection = {
|
|
738
764
|
cookie: options.cookie,
|
|
739
765
|
debug: options.debug,
|
|
766
|
+
connectionTracking: options.connectionTracking,
|
|
740
767
|
version
|
|
741
768
|
};
|
|
742
769
|
const nitroPreset = resolveNitroPreset(nuxt.options.nitro);
|
|
@@ -748,15 +775,19 @@ const module$1 = defineNuxtModule({
|
|
|
748
775
|
}
|
|
749
776
|
addTypeTemplate({
|
|
750
777
|
filename: "types/nuxt-skew-protection.d.ts",
|
|
751
|
-
getContents: () =>
|
|
752
|
-
|
|
778
|
+
getContents: () => `// Generated by nuxt-skew-protection
|
|
779
|
+
import type { ChunksOutdatedPayload, SkewAdapterConfig, SkewConnection, SkewSSEConfig, SkewWebSocketConfig } from '#skew-protection/app/types'
|
|
780
|
+
|
|
753
781
|
declare module '#app' {
|
|
754
782
|
interface RuntimeNuxtHooks {
|
|
755
783
|
'skew-protection:chunks-outdated': (payload: ChunksOutdatedPayload) => void | Promise<void>
|
|
784
|
+
'skew:message': (message: { type: string, [key: string]: unknown }) => void | Promise<void>
|
|
785
|
+
'skew:ws:config': (config: SkewWebSocketConfig) => void | Promise<void>
|
|
786
|
+
'skew:sse:config': (config: SkewSSEConfig) => void | Promise<void>
|
|
787
|
+
'skew:adapter:config': (config: SkewAdapterConfig) => void | Promise<void>
|
|
756
788
|
}
|
|
757
789
|
interface NuxtApp {
|
|
758
|
-
$
|
|
759
|
-
$skewProtectionCookie: Ref<string | undefined>
|
|
790
|
+
$skewConnection?: SkewConnection
|
|
760
791
|
}
|
|
761
792
|
interface NuxtAppManifestMeta {
|
|
762
793
|
skewProtection?: {
|
|
@@ -773,10 +804,13 @@ declare module '#app' {
|
|
|
773
804
|
declare module 'nuxt/app' {
|
|
774
805
|
interface RuntimeNuxtHooks {
|
|
775
806
|
'skew-protection:chunks-outdated': (payload: ChunksOutdatedPayload) => void | Promise<void>
|
|
807
|
+
'skew:message': (message: { type: string, [key: string]: unknown }) => void | Promise<void>
|
|
808
|
+
'skew:ws:config': (config: SkewWebSocketConfig) => void | Promise<void>
|
|
809
|
+
'skew:sse:config': (config: SkewSSEConfig) => void | Promise<void>
|
|
810
|
+
'skew:adapter:config': (config: SkewAdapterConfig) => void | Promise<void>
|
|
776
811
|
}
|
|
777
812
|
interface NuxtApp {
|
|
778
|
-
$
|
|
779
|
-
$skewProtectionCookie: Ref<string | undefined>
|
|
813
|
+
$skewConnection?: SkewConnection
|
|
780
814
|
}
|
|
781
815
|
interface NuxtAppManifestMeta {
|
|
782
816
|
skewProtection?: {
|
|
@@ -790,12 +824,26 @@ declare module 'nuxt/app' {
|
|
|
790
824
|
}
|
|
791
825
|
}
|
|
792
826
|
|
|
827
|
+
export type { ChunksOutdatedPayload, SkewAdapterConfig, SkewConnection, SkewSSEConfig, SkewWebSocketConfig }
|
|
828
|
+
`
|
|
829
|
+
}, { nuxt: true });
|
|
830
|
+
addTypeTemplate({
|
|
831
|
+
filename: "types/nuxt-skew-protection-nitro.d.ts",
|
|
832
|
+
getContents: () => `// Generated by nuxt-skew-protection
|
|
833
|
+
declare module 'nitropack/types' {
|
|
834
|
+
interface NitroRuntimeHooks {
|
|
835
|
+
'skew:connection:open': (payload: {
|
|
836
|
+
id: string
|
|
837
|
+
version: string
|
|
838
|
+
send: (data: { type: string, total: number, versions: Record<string, number> }) => void
|
|
839
|
+
}) => void
|
|
840
|
+
'skew:connection:close': (payload: { id: string }) => void
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
|
|
793
844
|
export {}
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
}, {
|
|
797
|
-
nuxt: true
|
|
798
|
-
});
|
|
845
|
+
`
|
|
846
|
+
}, { nitro: true });
|
|
799
847
|
addComponent({
|
|
800
848
|
name: "SkewNotification",
|
|
801
849
|
filePath: resolver.resolve(`./runtime/app/components/SkewNotification.vue`)
|
|
@@ -804,9 +852,17 @@ export {}
|
|
|
804
852
|
name: "useSkewProtection",
|
|
805
853
|
from: resolver.resolve("./runtime/app/composables/useSkewProtection")
|
|
806
854
|
});
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
855
|
+
if (options.connectionTracking) {
|
|
856
|
+
addImports({
|
|
857
|
+
name: "useActiveConnections",
|
|
858
|
+
from: resolver.resolve("./runtime/app/composables/useActiveConnections")
|
|
859
|
+
});
|
|
860
|
+
nuxt.options.nitro = nuxt.options.nitro || {};
|
|
861
|
+
nuxt.options.nitro.plugins = nuxt.options.nitro.plugins || [];
|
|
862
|
+
const connectionTrackingPlugin = nitroPreset === "cloudflare-durable" ? "./runtime/server/plugins/connection-tracking-cloudflare-durable" : "./runtime/server/plugins/connection-tracking";
|
|
863
|
+
nuxt.options.nitro.plugins.push(resolver.resolve(connectionTrackingPlugin));
|
|
864
|
+
}
|
|
865
|
+
nuxt.options.alias["#skew-protection"] = resolver.resolve("./runtime");
|
|
810
866
|
nuxt.options.alias["nuxt-skew-protection/server"] = resolver.resolve("./runtime/server");
|
|
811
867
|
if (options.storage?.driver) {
|
|
812
868
|
nuxt.options.nitro = nuxt.options.nitro || {};
|
|
@@ -864,12 +920,12 @@ export {}
|
|
|
864
920
|
const buildId = nuxt.options.runtimeConfig.app.buildId ||= nuxt.options.buildId;
|
|
865
921
|
let assetManager;
|
|
866
922
|
nitro.hooks.hook("compiled", async () => {
|
|
867
|
-
const
|
|
923
|
+
const publicDir = nitro.options.output.publicDir;
|
|
868
924
|
assetManager = createAssetManager({
|
|
869
925
|
...options,
|
|
870
926
|
driver: await resolveBuildTimeDriver(options.storage)
|
|
871
927
|
});
|
|
872
|
-
const assets = await assetManager.getAssetsFromBuild(
|
|
928
|
+
const assets = await assetManager.getAssetsFromBuild(publicDir);
|
|
873
929
|
const { isExistingVersion } = await assetManager.updateVersionsManifest(buildId, assets);
|
|
874
930
|
const manifest = await assetManager.getManifest();
|
|
875
931
|
const totalReleases = Object.keys(manifest.versions).length;
|
|
@@ -883,7 +939,7 @@ export {}
|
|
|
883
939
|
} else {
|
|
884
940
|
logger.log(`Storing ${colors.yellow(assets.length.toString())} assets for ${colors.cyan(buildId.slice(0, 8))} (${totalReleases} releases, oldest from ${timeInfo}) [${storageInfo}]`);
|
|
885
941
|
}
|
|
886
|
-
await assetManager.storeAssetsInStorage(buildId,
|
|
942
|
+
await assetManager.storeAssetsInStorage(buildId, publicDir, assets).catch((error) => {
|
|
887
943
|
logger.error(`Failed to store assets:`, error instanceof Error ? error.message : error);
|
|
888
944
|
throw error;
|
|
889
945
|
});
|
|
@@ -902,12 +958,14 @@ export {}
|
|
|
902
958
|
}
|
|
903
959
|
logger.log(`Restoring build files from ${versionCount} release${versionCount > 1 ? "s" : ""} (${totalAssets} assets) [${versionSizes.join(", ")}]...`);
|
|
904
960
|
}
|
|
905
|
-
await assetManager.restoreOldAssetsToPublic(buildId,
|
|
906
|
-
await assetManager.augmentBuildMetadata(buildId,
|
|
961
|
+
await assetManager.restoreOldAssetsToPublic(buildId, publicDir, assets, isExistingVersion);
|
|
962
|
+
await assetManager.augmentBuildMetadata(buildId, publicDir);
|
|
907
963
|
});
|
|
908
964
|
nitro.hooks.hook("close", async () => {
|
|
909
965
|
if (assetManager) {
|
|
910
|
-
await assetManager.cleanupExpiredVersions()
|
|
966
|
+
await assetManager.cleanupExpiredVersions().catch(() => {
|
|
967
|
+
});
|
|
968
|
+
await assetManager.dispose();
|
|
911
969
|
}
|
|
912
970
|
});
|
|
913
971
|
});
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { Rest } from "ably";
|
|
2
2
|
import { defineNodeBroadcast } from "../../../utils";
|
|
3
|
+
import { SKEW_DEFAULT_CHANNEL, SKEW_MESSAGE_TYPE } from "../../const.js";
|
|
3
4
|
export const broadcast = defineNodeBroadcast(async (config, version) => {
|
|
4
5
|
const ably = new Rest({ key: config.key });
|
|
5
|
-
const channelName = config.channel ||
|
|
6
|
-
const eventName = config.event ||
|
|
6
|
+
const channelName = config.channel || SKEW_DEFAULT_CHANNEL;
|
|
7
|
+
const eventName = config.event || SKEW_MESSAGE_TYPE.VERSION;
|
|
7
8
|
const channel = ably.channels.get(channelName);
|
|
8
9
|
await channel.publish(eventName, { version });
|
|
9
10
|
});
|
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import { onNuxtReady } from "nuxt/app";
|
|
2
2
|
import { defineWebSubscribe } from "../../../utils";
|
|
3
|
+
import { SKEW_DEFAULT_CHANNEL, SKEW_MESSAGE_TYPE } from "../../const.js";
|
|
3
4
|
export const subscribe = defineWebSubscribe((config, onMessage) => {
|
|
4
5
|
let cleanup;
|
|
5
6
|
onNuxtReady(async () => {
|
|
6
7
|
const { Realtime } = await import("ably");
|
|
7
8
|
const ably = new Realtime({ key: config.key });
|
|
8
|
-
const channelName = config.channel ||
|
|
9
|
-
const eventName = config.event ||
|
|
9
|
+
const channelName = config.channel || SKEW_DEFAULT_CHANNEL;
|
|
10
|
+
const eventName = config.event || SKEW_MESSAGE_TYPE.VERSION;
|
|
10
11
|
const channel = ably.channels.get(channelName);
|
|
11
12
|
await channel.subscribe(eventName, (message) => {
|
|
12
13
|
const data = typeof message.data === "string" ? JSON.parse(message.data) : message.data;
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { createHash, createHmac } from "node:crypto";
|
|
2
2
|
import { defineNodeBroadcast } from "../../../utils";
|
|
3
|
+
import { SKEW_DEFAULT_CHANNEL, SKEW_MESSAGE_TYPE } from "../../const.js";
|
|
3
4
|
export const broadcast = defineNodeBroadcast(async (config, version) => {
|
|
4
|
-
const channelName = config.channel ||
|
|
5
|
-
const eventName = config.event ||
|
|
5
|
+
const channelName = config.channel || SKEW_DEFAULT_CHANNEL;
|
|
6
|
+
const eventName = config.event || SKEW_MESSAGE_TYPE.VERSION;
|
|
6
7
|
const body = JSON.stringify({
|
|
7
8
|
name: eventName,
|
|
8
9
|
channel: channelName,
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { onNuxtReady } from "nuxt/app";
|
|
2
2
|
import { defineWebSubscribe } from "../../../utils";
|
|
3
|
+
import { SKEW_DEFAULT_CHANNEL, SKEW_MESSAGE_TYPE } from "../../const.js";
|
|
3
4
|
export const subscribe = defineWebSubscribe((config, onMessage) => {
|
|
4
5
|
let cleanup;
|
|
5
6
|
onNuxtReady(async () => {
|
|
@@ -7,8 +8,8 @@ export const subscribe = defineWebSubscribe((config, onMessage) => {
|
|
|
7
8
|
const pusher = new Pusher(config.key, {
|
|
8
9
|
cluster: config.cluster
|
|
9
10
|
});
|
|
10
|
-
const channelName = config.channel ||
|
|
11
|
-
const eventName = config.event ||
|
|
11
|
+
const channelName = config.channel || SKEW_DEFAULT_CHANNEL;
|
|
12
|
+
const eventName = config.event || SKEW_MESSAGE_TYPE.VERSION;
|
|
12
13
|
const channel = pusher.subscribe(channelName);
|
|
13
14
|
channel.bind(eventName, (data) => {
|
|
14
15
|
onMessage({ version: data.version });
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { useNuxtApp, useRuntimeConfig } from "nuxt/app";
|
|
2
|
+
import { computed, ref } from "vue";
|
|
3
|
+
const stats = ref({ total: 0, versions: {} });
|
|
4
|
+
let hooked = false;
|
|
5
|
+
export function useActiveConnections() {
|
|
6
|
+
const config = useRuntimeConfig().public.skewProtection;
|
|
7
|
+
if (!config?.connectionTracking) {
|
|
8
|
+
throw new Error("[nuxt-skew-protection] useActiveConnections() requires `connectionTracking: true` in your module config.");
|
|
9
|
+
}
|
|
10
|
+
if (!hooked) {
|
|
11
|
+
hooked = true;
|
|
12
|
+
useNuxtApp().hooks.hook("skew:message", (message) => {
|
|
13
|
+
if (message.type === "stats")
|
|
14
|
+
stats.value = { total: message.total, versions: message.versions };
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
return {
|
|
18
|
+
total: computed(() => stats.value.total),
|
|
19
|
+
versions: computed(() => stats.value.versions)
|
|
20
|
+
};
|
|
21
|
+
}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import type { SkewProtectionRuntimeConfig } from '../../types.js';
|
|
2
2
|
/**
|
|
3
3
|
* Get skew protection runtime config with proper types
|
|
4
|
-
* Ensures cookie config is always defined with required properties
|
|
5
4
|
*/
|
|
6
5
|
export declare function useRuntimeConfigSkewProtection(): SkewProtectionRuntimeConfig;
|
|
@@ -1,8 +1,4 @@
|
|
|
1
1
|
import { useRuntimeConfig } from "nuxt/app";
|
|
2
2
|
export function useRuntimeConfigSkewProtection() {
|
|
3
|
-
|
|
4
|
-
return {
|
|
5
|
-
...config.public.skewProtection,
|
|
6
|
-
buildId: config.app.buildId
|
|
7
|
-
};
|
|
3
|
+
return useRuntimeConfig().public.skewProtection;
|
|
8
4
|
}
|
|
@@ -1,11 +1,23 @@
|
|
|
1
1
|
import type { NuxtAppManifestMeta } from 'nuxt/app';
|
|
2
2
|
import type { ChunksOutdatedPayload } from '../../types.js';
|
|
3
|
+
export interface UseSkewProtectionOptions {
|
|
4
|
+
/**
|
|
5
|
+
* Lazy connection mode - don't auto-connect on mount
|
|
6
|
+
* When false (default), connections are established automatically on mount
|
|
7
|
+
* When true, users must call connect() manually
|
|
8
|
+
* @default false
|
|
9
|
+
*/
|
|
10
|
+
lazy?: boolean;
|
|
11
|
+
}
|
|
3
12
|
export declare function checkForUpdates(): Promise<void>;
|
|
4
|
-
export declare function useSkewProtection(): {
|
|
13
|
+
export declare function useSkewProtection(options?: UseSkewProtectionOptions): {
|
|
5
14
|
manifest: import("vue").Ref<NuxtAppManifestMeta | undefined, NuxtAppManifestMeta | undefined>;
|
|
6
15
|
clientVersion: any;
|
|
16
|
+
isConnected: import("vue").ComputedRef<boolean>;
|
|
7
17
|
isOnline: Readonly<import("vue").ShallowRef<boolean>>;
|
|
8
18
|
isOutdated: import("vue").ComputedRef<boolean | undefined>;
|
|
19
|
+
connect: () => void;
|
|
20
|
+
disconnect: () => void;
|
|
9
21
|
onCurrentChunksOutdated: (callback: (payload: ChunksOutdatedPayload) => void | Promise<void>) => () => void;
|
|
10
22
|
onAppOutdated: (callback: (manifest?: NuxtAppManifestMeta) => void | Promise<void>) => () => void;
|
|
11
23
|
checkForUpdates: typeof checkForUpdates;
|
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
import { buildAssetsURL } from "#internal/nuxt/paths";
|
|
2
2
|
import { useOnline } from "@vueuse/core";
|
|
3
|
-
import { useNuxtApp } from "nuxt/app";
|
|
4
|
-
import { computed, onUnmounted, ref } from "vue";
|
|
5
|
-
import {
|
|
3
|
+
import { useNuxtApp, useRuntimeConfig } from "nuxt/app";
|
|
4
|
+
import { computed, onMounted, onUnmounted, ref } from "vue";
|
|
5
|
+
import { SKEW_MESSAGE_TYPE } from "../../const.js";
|
|
6
|
+
import { logger } from "../../shared/logger.js";
|
|
7
|
+
import { createBackoffQueue } from "../utils/backoff-queue.js";
|
|
8
|
+
const isConnected = ref(false);
|
|
6
9
|
export async function checkForUpdates() {
|
|
7
10
|
if (import.meta.client && !useOnline().value)
|
|
8
11
|
return;
|
|
9
12
|
const nuxtApp = useNuxtApp();
|
|
10
|
-
const
|
|
11
|
-
const clientVersion = nuxtApp.$skewProtectionBuildId?.value || runtimeConfig.buildId;
|
|
13
|
+
const clientVersion = nuxtApp.$skewConnection?.buildId || useRuntimeConfig().app.buildId;
|
|
12
14
|
const meta = await $fetch(`${buildAssetsURL("builds/latest.json")}?${Date.now()}`).catch(() => {
|
|
13
15
|
return null;
|
|
14
16
|
});
|
|
@@ -16,11 +18,41 @@ export async function checkForUpdates() {
|
|
|
16
18
|
await nuxtApp.hooks.callHook("app:manifest:update", meta);
|
|
17
19
|
}
|
|
18
20
|
}
|
|
19
|
-
export function useSkewProtection() {
|
|
21
|
+
export function useSkewProtection(options = {}) {
|
|
22
|
+
const { lazy = false } = options;
|
|
20
23
|
const nuxtApp = useNuxtApp();
|
|
21
|
-
const
|
|
22
|
-
const clientVersion = nuxtApp.$skewProtectionBuildId?.value || nuxtApp.$skewProtectionCookie?.value || runtimeConfig.buildId;
|
|
24
|
+
const clientVersion = nuxtApp.$skewConnection?.buildId || nuxtApp.$skewConnection?.cookie?.value || useRuntimeConfig().app.buildId;
|
|
23
25
|
const manifest = ref();
|
|
26
|
+
const queue = createBackoffQueue({
|
|
27
|
+
delays: [0, 5e3, 3e4, 3e5],
|
|
28
|
+
onTick: () => nuxtApp.runWithContext(checkForUpdates)
|
|
29
|
+
});
|
|
30
|
+
if (!lazy) {
|
|
31
|
+
onMounted(() => {
|
|
32
|
+
nuxtApp.$skewConnection?.connect();
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
nuxtApp.hooks.hook("skew:message", (msg) => {
|
|
36
|
+
if (msg.type !== SKEW_MESSAGE_TYPE.VERSION && msg.type !== SKEW_MESSAGE_TYPE.CONNECTED)
|
|
37
|
+
return;
|
|
38
|
+
if (!msg.version || msg.version === clientVersion)
|
|
39
|
+
return;
|
|
40
|
+
logger.debug(`[SkewProtection] Version mismatch (${msg.version} !== ${clientVersion}), starting backoff checks`);
|
|
41
|
+
queue.start();
|
|
42
|
+
});
|
|
43
|
+
function connect() {
|
|
44
|
+
if (!import.meta.client || isConnected.value)
|
|
45
|
+
return;
|
|
46
|
+
isConnected.value = true;
|
|
47
|
+
nuxtApp.$skewConnection?.connect();
|
|
48
|
+
}
|
|
49
|
+
function disconnect() {
|
|
50
|
+
if (!import.meta.client || !isConnected.value)
|
|
51
|
+
return;
|
|
52
|
+
isConnected.value = false;
|
|
53
|
+
queue.clear();
|
|
54
|
+
nuxtApp.$skewConnection?.disconnect();
|
|
55
|
+
}
|
|
24
56
|
function onCurrentChunksOutdated(callback) {
|
|
25
57
|
const hook = nuxtApp.hooks.hook("skew-protection:chunks-outdated", callback);
|
|
26
58
|
onUnmounted(() => {
|
|
@@ -45,8 +77,11 @@ export function useSkewProtection() {
|
|
|
45
77
|
return {
|
|
46
78
|
manifest,
|
|
47
79
|
clientVersion,
|
|
80
|
+
isConnected: computed(() => isConnected.value),
|
|
48
81
|
isOnline: useOnline(),
|
|
49
82
|
isOutdated: computed(() => manifest.value && clientVersion !== manifest.value.id),
|
|
83
|
+
connect,
|
|
84
|
+
disconnect,
|
|
50
85
|
onCurrentChunksOutdated,
|
|
51
86
|
onAppOutdated,
|
|
52
87
|
checkForUpdates,
|
|
@@ -1,2 +1,8 @@
|
|
|
1
|
-
|
|
1
|
+
import type { SkewAdapterConfig } from '../types.js';
|
|
2
|
+
export type { SkewAdapterConfig };
|
|
3
|
+
declare const _default: import("nuxt/app").Plugin<{
|
|
4
|
+
skewConnection: import("../utils/create-skew-connection.js").SkewConnection;
|
|
5
|
+
}> & import("nuxt/app").ObjectPlugin<{
|
|
6
|
+
skewConnection: import("../utils/create-skew-connection.js").SkewConnection;
|
|
7
|
+
}>;
|
|
2
8
|
export default _default;
|
|
@@ -1,42 +1,25 @@
|
|
|
1
|
-
import { config, subscribe } from "#skew-adapter";
|
|
2
|
-
import { defineNuxtPlugin, useRuntimeConfig } from "nuxt/app";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import { createBackoffQueue } from "../utils/backoff-queue.js";
|
|
1
|
+
import { config as adapterConfig, subscribe } from "#skew-adapter";
|
|
2
|
+
import { defineNuxtPlugin, useNuxtApp, useRuntimeConfig } from "nuxt/app";
|
|
3
|
+
import { SKEW_MESSAGE_TYPE } from "../../const.js";
|
|
4
|
+
import { createSkewConnection } from "../utils/create-skew-connection.js";
|
|
6
5
|
export default defineNuxtPlugin({
|
|
7
6
|
name: "skew-protection:adapter-updates",
|
|
8
|
-
setup(
|
|
9
|
-
const
|
|
7
|
+
async setup() {
|
|
8
|
+
const nuxtApp = useNuxtApp();
|
|
10
9
|
const adapterName = useRuntimeConfig().public.skewProtection.adapterName;
|
|
11
|
-
const
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
10
|
+
const config = {
|
|
11
|
+
channel: adapterConfig.channel || "skew-protection",
|
|
12
|
+
adapterConfig
|
|
13
|
+
};
|
|
14
|
+
await nuxtApp.callHook("skew:adapter:config", config);
|
|
15
|
+
const skewConnection = createSkewConnection({
|
|
16
|
+
name: `Adapter:${adapterName}`,
|
|
17
|
+
setup(onMessage) {
|
|
18
|
+
return subscribe(config.adapterConfig, (msg) => {
|
|
19
|
+
onMessage({ type: SKEW_MESSAGE_TYPE.VERSION, channel: config.channel, ...msg });
|
|
20
|
+
});
|
|
21
|
+
}
|
|
17
22
|
});
|
|
18
|
-
|
|
19
|
-
cleanup = subscribe(config, (msg) => {
|
|
20
|
-
if (!msg.version) {
|
|
21
|
-
logger.debug(`[${adapterName}] Received message without version, ignoring`);
|
|
22
|
-
return;
|
|
23
|
-
}
|
|
24
|
-
logger.debug(`[${adapterName}] Received version: ${msg.version}`);
|
|
25
|
-
if (msg.version !== clientVersion) {
|
|
26
|
-
logger.debug(`[${adapterName}] Version mismatch (${msg.version} !== ${clientVersion}), starting backoff checks`);
|
|
27
|
-
queue.start();
|
|
28
|
-
}
|
|
29
|
-
});
|
|
30
|
-
});
|
|
31
|
-
nuxtApp.hook("app:error", () => {
|
|
32
|
-
queue.clear();
|
|
33
|
-
cleanup?.();
|
|
34
|
-
});
|
|
35
|
-
if (import.meta.client) {
|
|
36
|
-
window.addEventListener("beforeunload", () => {
|
|
37
|
-
queue.clear();
|
|
38
|
-
cleanup?.();
|
|
39
|
-
});
|
|
40
|
-
}
|
|
23
|
+
return { provide: { skewConnection } };
|
|
41
24
|
}
|
|
42
25
|
});
|
|
@@ -1,2 +1,8 @@
|
|
|
1
|
-
|
|
1
|
+
import type { SkewSSEConfig } from '../types.js';
|
|
2
|
+
export type { SkewSSEConfig };
|
|
3
|
+
declare const _default: import("nuxt/app").Plugin<{
|
|
4
|
+
skewConnection: import("../utils/create-skew-connection.js").SkewConnection;
|
|
5
|
+
}> & import("nuxt/app").ObjectPlugin<{
|
|
6
|
+
skewConnection: import("../utils/create-skew-connection.js").SkewConnection;
|
|
7
|
+
}>;
|
|
2
8
|
export default _default;
|
|
@@ -1,45 +1,30 @@
|
|
|
1
1
|
import { useEventSource } from "@vueuse/core";
|
|
2
|
-
import { defineNuxtPlugin } from "nuxt/app";
|
|
2
|
+
import { defineNuxtPlugin, useNuxtApp } from "nuxt/app";
|
|
3
3
|
import { watch } from "vue";
|
|
4
|
-
import {
|
|
5
|
-
import { checkForUpdates, useSkewProtection } from "../composables/useSkewProtection.js";
|
|
4
|
+
import { createSkewConnection } from "../utils/create-skew-connection.js";
|
|
6
5
|
export default defineNuxtPlugin({
|
|
7
6
|
name: "skew-protection:sse-updates",
|
|
8
|
-
setup(
|
|
9
|
-
const
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
retries: 10,
|
|
14
|
-
delay: 5e3,
|
|
15
|
-
onFailed() {
|
|
16
|
-
logger.error("[SSE] Max reconnection attempts reached");
|
|
17
|
-
}
|
|
18
|
-
},
|
|
19
|
-
serializer: {
|
|
20
|
-
// @ts-expect-error untyped
|
|
21
|
-
read: (rawData) => JSON.parse(rawData)
|
|
7
|
+
async setup() {
|
|
8
|
+
const nuxtApp = useNuxtApp();
|
|
9
|
+
const config = {
|
|
10
|
+
url: "/_skew/sse",
|
|
11
|
+
options: {
|
|
12
|
+
autoReconnect: { retries: 10, delay: 5e3 }
|
|
22
13
|
}
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
return;
|
|
35
|
-
if (message.type === "connected" && message.version) {
|
|
36
|
-
const newVersion = message.version;
|
|
37
|
-
logger.debug(`[SSE] Server version: ${newVersion}, Client version: ${clientVersion}`);
|
|
38
|
-
if (newVersion !== clientVersion) {
|
|
39
|
-
logger.debug("[SSE] Version mismatch detected, triggering update check");
|
|
40
|
-
nuxtApp.runWithContext(checkForUpdates);
|
|
41
|
-
}
|
|
14
|
+
};
|
|
15
|
+
await nuxtApp.callHook("skew:sse:config", config);
|
|
16
|
+
const skewConnection = createSkewConnection({
|
|
17
|
+
name: "SSE",
|
|
18
|
+
setup(onMessage) {
|
|
19
|
+
const sse = useEventSource(config.url, [], config.options);
|
|
20
|
+
watch(sse.data, (raw) => {
|
|
21
|
+
if (!raw)
|
|
22
|
+
return;
|
|
23
|
+
onMessage(JSON.parse(raw));
|
|
24
|
+
});
|
|
25
|
+
return sse.close;
|
|
42
26
|
}
|
|
43
27
|
});
|
|
28
|
+
return { provide: { skewConnection } };
|
|
44
29
|
}
|
|
45
30
|
});
|
|
@@ -1,16 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
* This allows our WebSocket updates to integrate seamlessly with Nuxt's existing reload logic.
|
|
9
|
-
*
|
|
10
|
-
* Can be used on:
|
|
11
|
-
* - Cloudflare Workers with Durable Objects
|
|
12
|
-
* - Custom WebSocket servers
|
|
13
|
-
* - Any platform that supports WebSocket connections
|
|
14
|
-
*/
|
|
15
|
-
declare const _default: import("nuxt/app").Plugin<Record<string, unknown>> & import("nuxt/app").ObjectPlugin<Record<string, unknown>>;
|
|
1
|
+
import type { SkewWebSocketConfig } from '../types.js';
|
|
2
|
+
export type { SkewWebSocketConfig };
|
|
3
|
+
declare const _default: import("nuxt/app").Plugin<{
|
|
4
|
+
skewConnection: import("../utils/create-skew-connection.js").SkewConnection;
|
|
5
|
+
}> & import("nuxt/app").ObjectPlugin<{
|
|
6
|
+
skewConnection: import("../utils/create-skew-connection.js").SkewConnection;
|
|
7
|
+
}>;
|
|
16
8
|
export default _default;
|
|
@@ -1,78 +1,42 @@
|
|
|
1
1
|
import { useWebSocket } from "@vueuse/core";
|
|
2
|
-
import { defineNuxtPlugin } from "nuxt/app";
|
|
2
|
+
import { defineNuxtPlugin, useNuxtApp } from "nuxt/app";
|
|
3
3
|
import { watch } from "vue";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
4
|
+
import { SKEW_MESSAGE_TYPE } from "../../const.js";
|
|
5
|
+
import { createSkewConnection } from "../utils/create-skew-connection.js";
|
|
6
6
|
export default defineNuxtPlugin({
|
|
7
|
-
name: "skew-protection:
|
|
8
|
-
setup(
|
|
9
|
-
const
|
|
10
|
-
const protocol =
|
|
11
|
-
const
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
watch(status, (newStatus) => {
|
|
39
|
-
logger.debug(`[WS] Connection status changed: ${newStatus}`);
|
|
40
|
-
});
|
|
41
|
-
watch(data, (message) => {
|
|
42
|
-
if (!message)
|
|
43
|
-
return;
|
|
44
|
-
try {
|
|
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
|
-
}
|
|
51
|
-
if (parsed.version) {
|
|
52
|
-
const newVersion = parsed.version;
|
|
53
|
-
logger.debug(`[WS] Server version: ${newVersion}, Client version: ${clientVersion}`);
|
|
54
|
-
if (newVersion !== clientVersion) {
|
|
55
|
-
logger.debug("[WS] Version mismatch detected, triggering update check");
|
|
56
|
-
nuxtApp.runWithContext(checkForUpdates);
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
} catch (error) {
|
|
60
|
-
logger.error("[WS] Failed to parse WebSocket message:", error);
|
|
7
|
+
name: "skew-protection:ws-updates",
|
|
8
|
+
async setup() {
|
|
9
|
+
const nuxtApp = useNuxtApp();
|
|
10
|
+
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
|
|
11
|
+
const config = {
|
|
12
|
+
url: `${protocol}//${window.location.host}/_skew/ws`,
|
|
13
|
+
options: {
|
|
14
|
+
autoReconnect: { retries: 10, delay: 5e3 },
|
|
15
|
+
heartbeat: {
|
|
16
|
+
message: JSON.stringify({ type: SKEW_MESSAGE_TYPE.PING, timestamp: Date.now() }),
|
|
17
|
+
interval: 3e4,
|
|
18
|
+
pongTimeout: 1e4
|
|
19
|
+
},
|
|
20
|
+
immediate: false
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
await nuxtApp.callHook("skew:ws:config", config);
|
|
24
|
+
const skewConnection = createSkewConnection({
|
|
25
|
+
name: "WS",
|
|
26
|
+
setup(onMessage) {
|
|
27
|
+
const ws = useWebSocket(config.url, config.options);
|
|
28
|
+
watch(ws.data, (raw) => {
|
|
29
|
+
if (!raw)
|
|
30
|
+
return;
|
|
31
|
+
const msg = JSON.parse(raw);
|
|
32
|
+
if (msg.type === SKEW_MESSAGE_TYPE.PING)
|
|
33
|
+
return;
|
|
34
|
+
onMessage(msg);
|
|
35
|
+
});
|
|
36
|
+
ws.open();
|
|
37
|
+
return ws.close;
|
|
61
38
|
}
|
|
62
39
|
});
|
|
63
|
-
|
|
64
|
-
logger.debug("[WS] App mounted, opening connection");
|
|
65
|
-
open();
|
|
66
|
-
});
|
|
67
|
-
nuxtApp.hook("app:error", () => {
|
|
68
|
-
logger.debug("[WS] App error, closing connection");
|
|
69
|
-
close();
|
|
70
|
-
});
|
|
71
|
-
if (import.meta.client) {
|
|
72
|
-
window.addEventListener("beforeunload", () => {
|
|
73
|
-
logger.debug("[WS] Page unload, closing connection");
|
|
74
|
-
close();
|
|
75
|
-
});
|
|
76
|
-
}
|
|
40
|
+
return { provide: { skewConnection } };
|
|
77
41
|
}
|
|
78
42
|
});
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { UseEventSourceOptions, UseWebSocketOptions } from '@vueuse/core';
|
|
2
|
+
import type { Ref } from 'vue';
|
|
3
|
+
export interface SkewWebSocketConfig {
|
|
4
|
+
url: string;
|
|
5
|
+
options: UseWebSocketOptions;
|
|
6
|
+
}
|
|
7
|
+
export interface SkewSSEConfig {
|
|
8
|
+
url: string;
|
|
9
|
+
options: UseEventSourceOptions<string>;
|
|
10
|
+
}
|
|
11
|
+
export interface SkewAdapterConfig {
|
|
12
|
+
channel: string;
|
|
13
|
+
adapterConfig: Record<string, unknown>;
|
|
14
|
+
}
|
|
15
|
+
export interface ChunksOutdatedPayload {
|
|
16
|
+
deletedChunks: string[];
|
|
17
|
+
invalidatedModules: string[];
|
|
18
|
+
passedReleases: string[];
|
|
19
|
+
}
|
|
20
|
+
export interface SkewConnection {
|
|
21
|
+
connect: () => void;
|
|
22
|
+
disconnect: () => void;
|
|
23
|
+
buildId: string;
|
|
24
|
+
cookie: Ref<string | null | undefined>;
|
|
25
|
+
}
|
|
File without changes
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { Ref } from 'vue';
|
|
2
|
+
export interface SkewMessage {
|
|
3
|
+
type: string;
|
|
4
|
+
version?: string;
|
|
5
|
+
[key: string]: unknown;
|
|
6
|
+
}
|
|
7
|
+
export interface CreateSkewConnectionConfig {
|
|
8
|
+
name: string;
|
|
9
|
+
setup: (onMessage: (msg: SkewMessage) => void) => (() => void) | void;
|
|
10
|
+
}
|
|
11
|
+
export interface SkewConnection {
|
|
12
|
+
connect: () => void;
|
|
13
|
+
disconnect: () => void;
|
|
14
|
+
buildId: string;
|
|
15
|
+
cookie: Ref<string | null | undefined>;
|
|
16
|
+
}
|
|
17
|
+
export declare function createSkewConnection(config: CreateSkewConnectionConfig): SkewConnection;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { useBotDetection } from "#imports";
|
|
2
|
+
import { useCookie, useNuxtApp, useRuntimeConfig } from "nuxt/app";
|
|
3
|
+
import { init, logger } from "../../shared/logger.js";
|
|
4
|
+
export function createSkewConnection(config) {
|
|
5
|
+
const { name, setup } = config;
|
|
6
|
+
const nuxtApp = useNuxtApp();
|
|
7
|
+
const runtimeConfig = useRuntimeConfig();
|
|
8
|
+
const buildId = runtimeConfig.app.buildId;
|
|
9
|
+
init();
|
|
10
|
+
const { isBot } = useBotDetection();
|
|
11
|
+
const cookieConfig = runtimeConfig.public.skewProtection.cookie;
|
|
12
|
+
const { name: cookieName, ...cookieOpts } = cookieConfig;
|
|
13
|
+
const cookie = useCookie(cookieName, { ...cookieOpts, readonly: false });
|
|
14
|
+
if (isBot.value) {
|
|
15
|
+
logger.debug(`[${name}] Skipping connection for bot`);
|
|
16
|
+
return { connect: () => {
|
|
17
|
+
}, disconnect: () => {
|
|
18
|
+
}, buildId, cookie };
|
|
19
|
+
}
|
|
20
|
+
if (import.meta.client && !cookie.value) {
|
|
21
|
+
cookie.value = buildId;
|
|
22
|
+
}
|
|
23
|
+
let cleanup;
|
|
24
|
+
let isConnected = false;
|
|
25
|
+
const handleMessage = (msg) => {
|
|
26
|
+
logger.debug(`[${name}] Received message:`, msg.type);
|
|
27
|
+
nuxtApp.hooks.callHook("skew:message", msg);
|
|
28
|
+
};
|
|
29
|
+
const connect = () => {
|
|
30
|
+
if (isConnected)
|
|
31
|
+
return;
|
|
32
|
+
isConnected = true;
|
|
33
|
+
logger.debug(`[${name}] Connecting`);
|
|
34
|
+
cleanup = setup(handleMessage);
|
|
35
|
+
};
|
|
36
|
+
const disconnect = () => {
|
|
37
|
+
if (!isConnected)
|
|
38
|
+
return;
|
|
39
|
+
isConnected = false;
|
|
40
|
+
logger.debug(`[${name}] Disconnecting`);
|
|
41
|
+
cleanup?.();
|
|
42
|
+
};
|
|
43
|
+
nuxtApp.hook("app:error", disconnect);
|
|
44
|
+
if (import.meta.client) {
|
|
45
|
+
window.addEventListener("beforeunload", disconnect);
|
|
46
|
+
}
|
|
47
|
+
return { connect, disconnect, buildId, cookie };
|
|
48
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare const SKEW_MESSAGE_TYPE: {
|
|
2
|
+
readonly VERSION: "version";
|
|
3
|
+
readonly CONNECTED: "connected";
|
|
4
|
+
readonly PING: "ping";
|
|
5
|
+
};
|
|
6
|
+
export type SkewMessageType = typeof SKEW_MESSAGE_TYPE[keyof typeof SKEW_MESSAGE_TYPE];
|
|
7
|
+
export declare const SKEW_DEFAULT_CHANNEL = "skew-protection";
|
|
@@ -3,13 +3,10 @@ import { useRuntimeConfig } from "nitropack/runtime";
|
|
|
3
3
|
import { setSkewProtectionCookie } from "../imports/cookie.js";
|
|
4
4
|
export default defineEventHandler(async (event) => {
|
|
5
5
|
const secFetchDest = getHeader(event, "sec-fetch-dest");
|
|
6
|
-
if (secFetchDest !== "document")
|
|
6
|
+
if (secFetchDest !== "document")
|
|
7
7
|
return;
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
const currentBuildId = config.app.buildId;
|
|
11
|
-
if (!currentBuildId) {
|
|
8
|
+
const buildId = useRuntimeConfig(event).app.buildId;
|
|
9
|
+
if (!buildId)
|
|
12
10
|
return;
|
|
13
|
-
|
|
14
|
-
setSkewProtectionCookie(event, currentBuildId);
|
|
11
|
+
setSkewProtectionCookie(event, buildId);
|
|
15
12
|
});
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { defineNitroPlugin } from "nitropack/runtime";
|
|
2
|
+
function getCtx(peer) {
|
|
3
|
+
return peer?._internal?.durable?.ctx || null;
|
|
4
|
+
}
|
|
5
|
+
function getStats(ctx) {
|
|
6
|
+
const websockets = ctx.getWebSockets();
|
|
7
|
+
const versions = {};
|
|
8
|
+
for (const ws of websockets) {
|
|
9
|
+
const v = ws.deserializeAttachment?.()?.v || "unknown";
|
|
10
|
+
versions[v] = (versions[v] || 0) + 1;
|
|
11
|
+
}
|
|
12
|
+
return { total: websockets.length, versions };
|
|
13
|
+
}
|
|
14
|
+
function broadcast(ctx) {
|
|
15
|
+
const stats = getStats(ctx);
|
|
16
|
+
const msg = JSON.stringify({ type: "stats", ...stats });
|
|
17
|
+
for (const ws of ctx.getWebSockets()) ws.send(msg);
|
|
18
|
+
}
|
|
19
|
+
export default defineNitroPlugin((nitroApp) => {
|
|
20
|
+
nitroApp.hooks.hook("skew:connection:open", ({ version, peer }) => {
|
|
21
|
+
const ws = peer?._internal?.ws;
|
|
22
|
+
if (ws?.serializeAttachment) {
|
|
23
|
+
ws.serializeAttachment({ ...ws.deserializeAttachment?.() || {}, v: version });
|
|
24
|
+
}
|
|
25
|
+
const ctx = getCtx(peer);
|
|
26
|
+
if (ctx)
|
|
27
|
+
broadcast(ctx);
|
|
28
|
+
});
|
|
29
|
+
nitroApp.hooks.hook("skew:connection:close", ({ peer }) => {
|
|
30
|
+
const ctx = getCtx(peer);
|
|
31
|
+
if (ctx)
|
|
32
|
+
broadcast(ctx);
|
|
33
|
+
});
|
|
34
|
+
});
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { defineNitroPlugin } from "nitropack/runtime";
|
|
2
|
+
export default defineNitroPlugin((nitroApp) => {
|
|
3
|
+
const connections = /* @__PURE__ */ new Map();
|
|
4
|
+
const getStats = () => {
|
|
5
|
+
const versions = {};
|
|
6
|
+
for (const conn of connections.values()) {
|
|
7
|
+
versions[conn.version] = (versions[conn.version] || 0) + 1;
|
|
8
|
+
}
|
|
9
|
+
return { total: connections.size, versions };
|
|
10
|
+
};
|
|
11
|
+
const broadcast = () => {
|
|
12
|
+
const stats = getStats();
|
|
13
|
+
for (const conn of connections.values()) {
|
|
14
|
+
conn.send({ type: "stats", ...stats });
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
nitroApp.hooks.hook("skew:connection:open", ({ id, version, send }) => {
|
|
18
|
+
connections.set(id, { version, send });
|
|
19
|
+
broadcast();
|
|
20
|
+
});
|
|
21
|
+
nitroApp.hooks.hook("skew:connection:close", ({ id }) => {
|
|
22
|
+
connections.delete(id);
|
|
23
|
+
broadcast();
|
|
24
|
+
});
|
|
25
|
+
});
|
|
@@ -1,23 +1,28 @@
|
|
|
1
1
|
import { createEventStream, defineEventHandler } from "h3";
|
|
2
2
|
import { useNitroApp, useRuntimeConfig } from "nitropack/runtime";
|
|
3
|
+
import { SKEW_MESSAGE_TYPE } from "../../../const.js";
|
|
4
|
+
import { getSkewProtectionCookie } from "../../imports/cookie.js";
|
|
3
5
|
export default defineEventHandler(async (event) => {
|
|
4
6
|
const nitroApp = useNitroApp();
|
|
5
7
|
const stream = createEventStream(event);
|
|
6
|
-
const
|
|
7
|
-
const serverVersion = config.app.buildId;
|
|
8
|
+
const serverVersion = useRuntimeConfig(event).app.buildId;
|
|
8
9
|
const send = (data) => {
|
|
9
10
|
stream.push(JSON.stringify(data));
|
|
10
11
|
};
|
|
11
12
|
send({
|
|
12
|
-
type:
|
|
13
|
+
type: SKEW_MESSAGE_TYPE.CONNECTED,
|
|
13
14
|
version: serverVersion,
|
|
14
15
|
timestamp: Date.now()
|
|
15
16
|
});
|
|
17
|
+
const connectionId = crypto.randomUUID();
|
|
18
|
+
const clientVersion = getSkewProtectionCookie(event) || serverVersion;
|
|
19
|
+
await nitroApp.hooks.callHook("skew:connection:open", {
|
|
20
|
+
id: connectionId,
|
|
21
|
+
version: clientVersion,
|
|
22
|
+
send
|
|
23
|
+
});
|
|
16
24
|
const keepaliveInterval = setInterval(() => {
|
|
17
|
-
send({
|
|
18
|
-
type: "keepalive",
|
|
19
|
-
timestamp: Date.now()
|
|
20
|
-
});
|
|
25
|
+
send({ type: "keepalive", timestamp: Date.now() });
|
|
21
26
|
}, 3e4);
|
|
22
27
|
let cleanupDone = false;
|
|
23
28
|
const close = async () => {
|
|
@@ -25,6 +30,7 @@ export default defineEventHandler(async (event) => {
|
|
|
25
30
|
return;
|
|
26
31
|
cleanupDone = true;
|
|
27
32
|
clearInterval(keepaliveInterval);
|
|
33
|
+
await nitroApp.hooks.callHook("skew:connection:close", { id: connectionId });
|
|
28
34
|
await stream.close();
|
|
29
35
|
};
|
|
30
36
|
stream.onClosed(close);
|
|
@@ -1,17 +1,33 @@
|
|
|
1
|
+
import { parse as parseCookie } from "cookie-es";
|
|
1
2
|
import { defineWebSocketHandler } from "h3";
|
|
2
|
-
import { useRuntimeConfig } from "nitropack/runtime";
|
|
3
|
+
import { useNitroApp, useRuntimeConfig } from "nitropack/runtime";
|
|
4
|
+
import { SKEW_MESSAGE_TYPE } from "../../../const.js";
|
|
5
|
+
import { getSkewProtectionCookieName } from "../../imports/cookie.js";
|
|
3
6
|
export default defineWebSocketHandler({
|
|
4
7
|
open(peer) {
|
|
5
|
-
const
|
|
8
|
+
const serverVersion = useRuntimeConfig().app.buildId;
|
|
9
|
+
const cookieName = getSkewProtectionCookieName();
|
|
6
10
|
peer.send(JSON.stringify({
|
|
7
|
-
type:
|
|
8
|
-
version:
|
|
11
|
+
type: SKEW_MESSAGE_TYPE.CONNECTED,
|
|
12
|
+
version: serverVersion,
|
|
9
13
|
timestamp: Date.now()
|
|
10
14
|
}));
|
|
15
|
+
const cookieHeader = peer.request?.headers?.get("cookie") || "";
|
|
16
|
+
const cookies = parseCookie(cookieHeader);
|
|
17
|
+
const clientVersion = cookies[cookieName] || serverVersion;
|
|
18
|
+
useNitroApp().hooks.callHook("skew:connection:open", {
|
|
19
|
+
id: peer.id,
|
|
20
|
+
version: clientVersion,
|
|
21
|
+
send: (data) => peer.send(JSON.stringify(data)),
|
|
22
|
+
peer
|
|
23
|
+
});
|
|
11
24
|
},
|
|
12
25
|
message(peer, message) {
|
|
13
26
|
if (message.text().includes("ping")) {
|
|
14
27
|
peer.send(JSON.stringify({ type: "pong" }));
|
|
15
28
|
}
|
|
29
|
+
},
|
|
30
|
+
close(peer) {
|
|
31
|
+
useNitroApp().hooks.callHook("skew:connection:close", { id: peer.id, peer });
|
|
16
32
|
}
|
|
17
33
|
});
|
package/dist/runtime/types.d.ts
CHANGED
|
@@ -6,13 +6,14 @@ export interface NuxtSkewProtectionRuntimeConfig {
|
|
|
6
6
|
name?: string;
|
|
7
7
|
};
|
|
8
8
|
debug: boolean;
|
|
9
|
+
connectionTracking?: boolean;
|
|
9
10
|
}
|
|
10
11
|
export interface SkewProtectionRuntimeConfig {
|
|
11
12
|
cookie: Omit<CookieSerializeOptions, 'encode'> & {
|
|
12
13
|
name: string;
|
|
13
14
|
};
|
|
14
|
-
buildId: string;
|
|
15
15
|
debug: boolean;
|
|
16
|
+
connectionTracking?: boolean;
|
|
16
17
|
}
|
|
17
18
|
export interface ChunksOutdatedPayload {
|
|
18
19
|
deletedChunks: string[];
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nuxt-skew-protection",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.6.0",
|
|
5
5
|
"description": "Solve Nuxt version skews with persistent assets and instant updates.",
|
|
6
6
|
"author": {
|
|
7
7
|
"name": "Harlan Wilton",
|
|
@@ -36,6 +36,7 @@
|
|
|
36
36
|
"dist"
|
|
37
37
|
],
|
|
38
38
|
"peerDependencies": {
|
|
39
|
+
"@nuxtjs/robots": ">=5.6.7",
|
|
39
40
|
"ably": ">=2",
|
|
40
41
|
"pusher-js": ">=8"
|
|
41
42
|
},
|
|
@@ -54,7 +55,7 @@
|
|
|
54
55
|
"consola": "^3.4.2",
|
|
55
56
|
"cookie-es": "^2.0.0",
|
|
56
57
|
"defu": "^6.1.4",
|
|
57
|
-
"nuxt-site-config": "^3.2.
|
|
58
|
+
"nuxt-site-config": "^3.2.14",
|
|
58
59
|
"ofetch": "^1.5.1",
|
|
59
60
|
"pathe": "^2.0.3",
|
|
60
61
|
"pkg-types": "^2.3.0",
|
|
@@ -75,6 +76,7 @@
|
|
|
75
76
|
"@nuxtjs/color-mode": "^4.0.0",
|
|
76
77
|
"@nuxtjs/eslint-config-typescript": "^12.1.0",
|
|
77
78
|
"@nuxtjs/i18n": "^10.2.1",
|
|
79
|
+
"@nuxtjs/robots": "^5.6.7",
|
|
78
80
|
"@types/ioredis": "^5.0.0",
|
|
79
81
|
"@types/ws": "^8.18.1",
|
|
80
82
|
"@unocss/nuxt": "66.5.10",
|
|
@@ -85,7 +87,7 @@
|
|
|
85
87
|
"ably": "^2.15.0",
|
|
86
88
|
"better-sqlite3": "^12.5.0",
|
|
87
89
|
"bumpp": "^10.3.2",
|
|
88
|
-
"eslint": "^9.39.
|
|
90
|
+
"eslint": "^9.39.2",
|
|
89
91
|
"eventsource": "^4.1.0",
|
|
90
92
|
"execa": "^9.6.1",
|
|
91
93
|
"firebase-functions": "^7.0.1",
|
|
@@ -105,7 +107,8 @@
|
|
|
105
107
|
"ws": "^8.18.3"
|
|
106
108
|
},
|
|
107
109
|
"resolutions": {
|
|
108
|
-
"nuxt-skew-protection": "workspace:*"
|
|
110
|
+
"nuxt-skew-protection": "workspace:*",
|
|
111
|
+
"reka-ui": "2.6.1"
|
|
109
112
|
},
|
|
110
113
|
"scripts": {
|
|
111
114
|
"lint": "eslint . --fix",
|
|
@@ -1,12 +0,0 @@
|
|
|
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;
|
|
@@ -1,29 +0,0 @@
|
|
|
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
|
-
});
|