nuxt-skew-protection 1.5.4 → 1.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 +8 -4
- package/dist/module.d.mts +4 -1
- package/dist/module.json +1 -1
- package/dist/module.mjs +87 -101
- package/dist/runtime/adapters/ably/index.js +5 -0
- package/dist/runtime/adapters/ably/node.d.ts +3 -7
- package/dist/runtime/adapters/ably/web.d.ts +2 -1
- package/dist/runtime/adapters/index.d.ts +2 -1
- package/dist/runtime/adapters/index.js +2 -1
- package/dist/runtime/adapters/pusher/index.js +5 -0
- package/dist/runtime/adapters/pusher/node.d.ts +3 -8
- package/dist/runtime/adapters/pusher/web.d.ts +2 -1
- package/dist/runtime/adapters/types.d.ts +31 -9
- package/dist/runtime/adapters/types.js +8 -7
- package/dist/runtime/app/plugins/multi-tab.client.js +12 -20
- package/dist/runtime/app/plugins/sw-track-user-modules.client.js +52 -32
- package/dist/runtime/types.d.ts +1 -0
- package/package.json +3 -2
- package/skills/nuxt-skew-protection/SKILL.md +148 -0
package/README.md
CHANGED
|
@@ -3,6 +3,13 @@
|
|
|
3
3
|
[![npm version][npm-version-src]][npm-version-href]
|
|
4
4
|
[![npm downloads][npm-downloads-src]][npm-downloads-href]
|
|
5
5
|
[![Nuxt][nuxt-src]][nuxt-href]
|
|
6
|
+
<a href="https://skilld.dev/gh/harlan-zw/nuxt-skew-protection">
|
|
7
|
+
<picture>
|
|
8
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://skilld.dev/b/harlan-zw/nuxt-skew-protection?theme=dark">
|
|
9
|
+
<source media="(prefers-color-scheme: light)" srcset="https://skilld.dev/b/harlan-zw/nuxt-skew-protection?theme=light">
|
|
10
|
+
<img alt="Skill repository on skilld.dev" src="https://skilld.dev/b/harlan-zw/nuxt-skew-protection?theme=light">
|
|
11
|
+
</picture>
|
|
12
|
+
</a>
|
|
6
13
|
|
|
7
14
|
> Keep old build assets available and notify users when their app needs an update.
|
|
8
15
|
|
|
@@ -36,10 +43,7 @@ npx nuxi@latest module add nuxt-skew-protection
|
|
|
36
43
|
```
|
|
37
44
|
|
|
38
45
|
> [!TIP]
|
|
39
|
-
>
|
|
40
|
-
> ```bash
|
|
41
|
-
> npx skilld add nuxt-skew-protection
|
|
42
|
-
> ```
|
|
46
|
+
> Using an AI agent? Get the nuxt-skew-protection Skill on [skilld.dev/gh/harlan-zw/nuxt-skew-protection](https://skilld.dev/gh/harlan-zw/nuxt-skew-protection).
|
|
43
47
|
|
|
44
48
|
## Documentation
|
|
45
49
|
|
package/dist/module.d.mts
CHANGED
|
@@ -38,6 +38,9 @@ interface ModuleOptions {
|
|
|
38
38
|
* `/pro/*` on a host shared with a marketing app): use `/pro/__skew` so the
|
|
39
39
|
* websocket/health requests resolve to this worker's deployment instead of
|
|
40
40
|
* leaking to the sibling app that owns the host route.
|
|
41
|
+
*
|
|
42
|
+
* This is the full public path, including `app.baseURL`. When unset, it is
|
|
43
|
+
* auto-detected: `app.baseURL: '/app/'` gives `/app/__skew`.
|
|
41
44
|
* @default '/__skew'
|
|
42
45
|
*/
|
|
43
46
|
basePath?: string;
|
|
@@ -95,7 +98,7 @@ interface ModuleOptions {
|
|
|
95
98
|
* How to handle outdated chunks.
|
|
96
99
|
* - 'prompt': Show notification, let user decide (default)
|
|
97
100
|
* - 'immediate': Reload immediately when chunks are invalidated
|
|
98
|
-
* - 'idle': Reload
|
|
101
|
+
* - 'idle': Reload after 60 seconds without user input, or when the tab is hidden
|
|
99
102
|
* - false: Disable automatic handling, use hooks for custom logic
|
|
100
103
|
* @default 'prompt'
|
|
101
104
|
*/
|
package/dist/module.json
CHANGED
package/dist/module.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { existsSync, promises } from 'node:fs';
|
|
2
|
-
import { useLogger, useNuxt, defineNuxtModule, createResolver, hasNuxtModule, addTypeTemplate, addComponent, addImports, addServerHandler, addPlugin, tryResolveModule, addTemplate } from '@nuxt/kit';
|
|
2
|
+
import { useLogger, useNuxt, defineNuxtModule, createResolver, hasNuxtModule, addTypeTemplate, addComponent, addImports, addServerHandler, addPlugin, tryResolveModule, resolvePath, addTemplate } from '@nuxt/kit';
|
|
3
3
|
import { colors } from 'consola/utils';
|
|
4
4
|
import { setupNitroRuntimeCompatibility, resolveNitroPreset, renderNitroTypeAugmentations, isNuxtGenerate } from 'nuxtseo-shared/kit';
|
|
5
5
|
import { readPackageJSON } from 'pkg-types';
|
|
@@ -33,6 +33,15 @@ function resolveBundleAssets(options, env = process.env) {
|
|
|
33
33
|
bundleAssets: true
|
|
34
34
|
};
|
|
35
35
|
}
|
|
36
|
+
function resolveDefaultUpdateStrategy(input) {
|
|
37
|
+
if (input.isStatic)
|
|
38
|
+
return "polling";
|
|
39
|
+
if (input.nitroPreset === "cloudflare-durable")
|
|
40
|
+
return "ws";
|
|
41
|
+
if (input.nitroPreset?.includes("cloudflare"))
|
|
42
|
+
return "polling";
|
|
43
|
+
return "sse";
|
|
44
|
+
}
|
|
36
45
|
|
|
37
46
|
const SKEW_SEGMENT = "__skew";
|
|
38
47
|
const DEFAULT_COOKIE_NAME = "__nkpv";
|
|
@@ -40,13 +49,22 @@ function trimSlashes(value) {
|
|
|
40
49
|
return value.replace(/^\/+|\/+$/g, "");
|
|
41
50
|
}
|
|
42
51
|
function resolveBuildAssetsPath(app = {}) {
|
|
43
|
-
|
|
44
|
-
|
|
52
|
+
return `${joinSegments(app.baseURL, app.buildAssetsDir || "/_nuxt/")}/`;
|
|
53
|
+
}
|
|
54
|
+
function joinSegments(...values) {
|
|
55
|
+
const path = values.map((value) => trimSlashes(value || "")).filter(Boolean).join("/");
|
|
56
|
+
return `/${path}`;
|
|
57
|
+
}
|
|
58
|
+
function isUnder(path, prefix) {
|
|
59
|
+
return prefix === "/" || path === prefix || path.startsWith(`${prefix}/`);
|
|
45
60
|
}
|
|
46
61
|
function resolveBasePath(input = {}) {
|
|
47
|
-
if (input.basePath)
|
|
48
|
-
return `/${trimSlashes(input.basePath)}`;
|
|
49
62
|
const app = input.app || {};
|
|
63
|
+
const baseURL = joinSegments(app.baseURL);
|
|
64
|
+
if (input.basePath) {
|
|
65
|
+
const explicit = `/${trimSlashes(input.basePath)}`;
|
|
66
|
+
return isUnder(explicit, baseURL) ? explicit : joinSegments(baseURL, explicit);
|
|
67
|
+
}
|
|
50
68
|
const assetsDir = app.buildAssetsDir || "";
|
|
51
69
|
let mount = "";
|
|
52
70
|
if (assetsDir.startsWith("/")) {
|
|
@@ -55,9 +73,13 @@ function resolveBasePath(input = {}) {
|
|
|
55
73
|
const mountEnd = nuxtAssetsIndex === -1 ? segments.length - 1 : nuxtAssetsIndex;
|
|
56
74
|
mount = segments.slice(0, mountEnd).join("/");
|
|
57
75
|
}
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
76
|
+
return joinSegments(baseURL, mount, SKEW_SEGMENT);
|
|
77
|
+
}
|
|
78
|
+
function toServerRoute(publicPath, baseURL) {
|
|
79
|
+
const base = joinSegments(baseURL);
|
|
80
|
+
if (base === "/" || !isUnder(publicPath, base))
|
|
81
|
+
return publicPath;
|
|
82
|
+
return publicPath.slice(base.length) || "/";
|
|
61
83
|
}
|
|
62
84
|
function resolveCookieName(explicitName, basePath) {
|
|
63
85
|
if (explicitName)
|
|
@@ -797,43 +819,37 @@ function createAssetManager(options) {
|
|
|
797
819
|
}
|
|
798
820
|
async function augmentBuildMetadata(buildId, publicDir) {
|
|
799
821
|
const manifest = await getVersionManifest(storage);
|
|
800
|
-
const
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
822
|
+
const buildsDir = join$1(publicDir, buildAssetsDir, "builds");
|
|
823
|
+
const versions = {};
|
|
824
|
+
const deletedChunks = {};
|
|
825
|
+
for (const [versionId, versionData] of Object.entries(manifest.versions)) {
|
|
826
|
+
versions[versionId] = { timestamp: versionData.timestamp };
|
|
827
|
+
if (versionData.deletedChunks?.length)
|
|
828
|
+
deletedChunks[versionId] = versionData.deletedChunks;
|
|
829
|
+
}
|
|
830
|
+
const latestPath = join$1(buildsDir, "latest.json");
|
|
831
|
+
await promises.readFile(latestPath, "utf-8").then(async (latestData) => {
|
|
804
832
|
const latestJson = JSON.parse(latestData);
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
timestamp: versionData.timestamp,
|
|
809
|
-
deletedChunks: versionData.deletedChunks
|
|
810
|
-
};
|
|
811
|
-
}
|
|
812
|
-
latestJson.skewProtection = {
|
|
813
|
-
versions: clientVersions
|
|
814
|
-
};
|
|
815
|
-
newLatestContent = JSON.stringify(latestJson, null, 2);
|
|
816
|
-
await promises.writeFile(latestPath, newLatestContent, "utf-8");
|
|
817
|
-
} catch (error) {
|
|
833
|
+
latestJson.skewProtection = { versions };
|
|
834
|
+
await promises.writeFile(latestPath, JSON.stringify(latestJson), "utf-8");
|
|
835
|
+
}).catch((error) => {
|
|
818
836
|
const message = error instanceof Error ? error.message : String(error);
|
|
819
837
|
throw new Error(`Failed to augment builds/latest.json: ${message}`);
|
|
820
|
-
}
|
|
821
|
-
const metaPath = join$1(
|
|
822
|
-
|
|
823
|
-
const metaData = await promises.readFile(metaPath, "utf-8");
|
|
838
|
+
});
|
|
839
|
+
const metaPath = join$1(buildsDir, "meta", `${buildId}.json`);
|
|
840
|
+
await promises.readFile(metaPath, "utf-8").then(async (metaData) => {
|
|
824
841
|
const metaJson = JSON.parse(metaData);
|
|
825
|
-
const
|
|
826
|
-
if (
|
|
827
|
-
metaJson.skewProtection = {
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
};
|
|
831
|
-
}
|
|
832
|
-
await promises.writeFile(metaPath, JSON.stringify(metaJson, null, 2), "utf-8");
|
|
833
|
-
} catch (error) {
|
|
842
|
+
const timestamp = versions[buildId]?.timestamp;
|
|
843
|
+
if (timestamp)
|
|
844
|
+
metaJson.skewProtection = { timestamp };
|
|
845
|
+
await promises.writeFile(metaPath, JSON.stringify(metaJson), "utf-8");
|
|
846
|
+
}).catch((error) => {
|
|
834
847
|
const message = error instanceof Error ? error.message : String(error);
|
|
835
848
|
throw new Error(`Failed to augment builds/meta/${buildId}.json: ${message}`);
|
|
836
|
-
}
|
|
849
|
+
});
|
|
850
|
+
const skewPath = join$1(buildsDir, "skew", `${buildId}.json`);
|
|
851
|
+
await promises.mkdir(dirname(skewPath), { recursive: true });
|
|
852
|
+
await promises.writeFile(skewPath, JSON.stringify({ deletedChunks }), "utf-8");
|
|
837
853
|
}
|
|
838
854
|
return {
|
|
839
855
|
getAssetsFromBuild,
|
|
@@ -896,10 +912,14 @@ const module$1 = defineNuxtModule({
|
|
|
896
912
|
return;
|
|
897
913
|
}
|
|
898
914
|
const nitroCompatibility = setupNitroRuntimeCompatibility(nuxt);
|
|
899
|
-
const
|
|
900
|
-
const
|
|
915
|
+
const explicitBasePath = options.basePath;
|
|
916
|
+
const basePathExplicit = !!explicitBasePath;
|
|
917
|
+
const basePath = resolveBasePath({ basePath: explicitBasePath, app: nuxt.options.app });
|
|
901
918
|
options.basePath = basePath;
|
|
919
|
+
if (explicitBasePath && basePath !== resolveBasePath({ basePath: explicitBasePath }))
|
|
920
|
+
logger.warn(`\`basePath\` ${explicitBasePath} is outside \`app.baseURL\`. The module uses ${basePath}.`);
|
|
902
921
|
logger.debug(`Endpoints mounted at ${basePath}/* (${basePathExplicit ? "explicit" : "auto-detected"})`);
|
|
922
|
+
const skewRoute = (endpoint) => toServerRoute(`${basePath}${endpoint}`, nuxt.options.app.baseURL);
|
|
903
923
|
if (options.cookie !== false) {
|
|
904
924
|
options.cookie = options.cookie || {};
|
|
905
925
|
options.cookie.name = resolveCookieName(options.cookie.name, basePath);
|
|
@@ -983,9 +1003,6 @@ declare module '#app' {
|
|
|
983
1003
|
skewProtection?: {
|
|
984
1004
|
versions?: Record<string, {
|
|
985
1005
|
timestamp: string
|
|
986
|
-
expires: string
|
|
987
|
-
assets: string[]
|
|
988
|
-
deletedChunks?: string[]
|
|
989
1006
|
}>
|
|
990
1007
|
}
|
|
991
1008
|
}
|
|
@@ -1008,9 +1025,6 @@ declare module 'nuxt/app' {
|
|
|
1008
1025
|
skewProtection?: {
|
|
1009
1026
|
versions?: Record<string, {
|
|
1010
1027
|
timestamp: string
|
|
1011
|
-
expires: string
|
|
1012
|
-
assets: string[]
|
|
1013
|
-
deletedChunks?: string[]
|
|
1014
1028
|
}>
|
|
1015
1029
|
}
|
|
1016
1030
|
}
|
|
@@ -1076,17 +1090,17 @@ export {}
|
|
|
1076
1090
|
if (nuxt.options.dev && options.connectionTracking) {
|
|
1077
1091
|
if (nuxt.options.nitro?.experimental?.websocket) {
|
|
1078
1092
|
addServerHandler({
|
|
1079
|
-
route:
|
|
1093
|
+
route: skewRoute("/ws"),
|
|
1080
1094
|
handler: resolver.resolve("./runtime/server/routes/__skew/ws")
|
|
1081
1095
|
});
|
|
1082
1096
|
addServerHandler({
|
|
1083
|
-
route:
|
|
1097
|
+
route: skewRoute("/subscribe-stats"),
|
|
1084
1098
|
method: "post",
|
|
1085
1099
|
handler: resolver.resolve("./runtime/server/routes/__skew/subscribe-stats.post")
|
|
1086
1100
|
});
|
|
1087
1101
|
if (options.routeTracking) {
|
|
1088
1102
|
addServerHandler({
|
|
1089
|
-
route:
|
|
1103
|
+
route: skewRoute("/route"),
|
|
1090
1104
|
method: "post",
|
|
1091
1105
|
handler: resolver.resolve("./runtime/server/routes/__skew/route.post")
|
|
1092
1106
|
});
|
|
@@ -1161,7 +1175,7 @@ export {}
|
|
|
1161
1175
|
nitroConfig.cloudflare.wrangler.assets ||= {};
|
|
1162
1176
|
nitroConfig.cloudflare.wrangler.assets.run_worker_first = withCloudflareBuildAssetRouting(
|
|
1163
1177
|
nitroConfig.cloudflare.wrangler.assets.run_worker_first,
|
|
1164
|
-
|
|
1178
|
+
buildAssetsPath
|
|
1165
1179
|
);
|
|
1166
1180
|
nitroConfig.rollupConfig ||= {};
|
|
1167
1181
|
const existingPlugins = nitroConfig.rollupConfig.plugins;
|
|
@@ -1191,7 +1205,7 @@ export {}
|
|
|
1191
1205
|
} else if (options.updateStrategy === "sse") {
|
|
1192
1206
|
resolvedStrategy = "sse";
|
|
1193
1207
|
} else if (!options.updateStrategy) {
|
|
1194
|
-
resolvedStrategy = isStatic
|
|
1208
|
+
resolvedStrategy = resolveDefaultUpdateStrategy({ isStatic, nitroPreset });
|
|
1195
1209
|
}
|
|
1196
1210
|
if (isStatic && resolvedStrategy !== "polling" && resolvedStrategy !== "adapter") {
|
|
1197
1211
|
logger.warn(`Strategy "${resolvedStrategy}" requires a server but static generation detected. Falling back to polling.`);
|
|
@@ -1215,14 +1229,14 @@ export {}
|
|
|
1215
1229
|
}
|
|
1216
1230
|
if (!isStatic) {
|
|
1217
1231
|
addServerHandler({
|
|
1218
|
-
route:
|
|
1232
|
+
route: skewRoute("/health"),
|
|
1219
1233
|
method: "get",
|
|
1220
1234
|
handler: resolver.resolve("./runtime/server/routes/__skew/health.get")
|
|
1221
1235
|
});
|
|
1222
1236
|
}
|
|
1223
1237
|
if (options.connectionTracking && !isStatic) {
|
|
1224
1238
|
addServerHandler({
|
|
1225
|
-
route:
|
|
1239
|
+
route: skewRoute("/admin/stats"),
|
|
1226
1240
|
method: "get",
|
|
1227
1241
|
handler: resolver.resolve("./runtime/server/routes/__skew/admin/stats.get")
|
|
1228
1242
|
});
|
|
@@ -1311,34 +1325,22 @@ export {}
|
|
|
1311
1325
|
if (resolvedStrategy === "adapter" && isAdapter) {
|
|
1312
1326
|
const adapter = options.updateStrategy;
|
|
1313
1327
|
nuxt.options.runtimeConfig.public.skewProtection.adapterName = adapter.name;
|
|
1314
|
-
const result = adapter.
|
|
1315
|
-
if (
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
} else {
|
|
1326
|
-
logger.warn(msg);
|
|
1327
|
-
}
|
|
1328
|
-
}
|
|
1329
|
-
} else if (adapter.name === "ably") {
|
|
1330
|
-
if (!await tryResolveModule("ably", nuxt.options.rootDir)) {
|
|
1331
|
-
const msg = `The ably adapter requires \`ably\`. Install with: npx nypm add ably`;
|
|
1332
|
-
if (!nuxt.options.dev && !nuxt.options._prepare) {
|
|
1333
|
-
throw new Error(msg);
|
|
1334
|
-
} else {
|
|
1335
|
-
logger.warn(msg);
|
|
1336
|
-
}
|
|
1337
|
-
}
|
|
1328
|
+
const result = adapter.parseConfig(adapter.config);
|
|
1329
|
+
if (result._tag === "Err")
|
|
1330
|
+
throw new Error(`${adapter.name} adapter config invalid: ${result.issues.join(", ")}`);
|
|
1331
|
+
const publicAdapterConfig = adapter.toPublicConfig(result.config);
|
|
1332
|
+
for (const dependency of adapter.dependencies) {
|
|
1333
|
+
if (await tryResolveModule(dependency, nuxt.options.rootDir))
|
|
1334
|
+
continue;
|
|
1335
|
+
const msg = `The ${adapter.name} adapter requires \`${dependency}\`. Install with: npx nypm add ${dependency}`;
|
|
1336
|
+
if (!nuxt.options.dev && !nuxt.options._prepare)
|
|
1337
|
+
throw new Error(msg);
|
|
1338
|
+
logger.warn(msg);
|
|
1338
1339
|
}
|
|
1340
|
+
const adapterWebEntry = await resolvePath(adapter.web);
|
|
1339
1341
|
const template = addTemplate({
|
|
1340
1342
|
filename: "skew-adapter.mjs",
|
|
1341
|
-
getContents: () => `import { subscribe } from
|
|
1343
|
+
getContents: () => `import { subscribe } from ${JSON.stringify(adapterWebEntry)}
|
|
1342
1344
|
export const config = ${JSON.stringify(publicAdapterConfig)}
|
|
1343
1345
|
export { subscribe }`
|
|
1344
1346
|
});
|
|
@@ -1350,25 +1352,9 @@ export { subscribe }`
|
|
|
1350
1352
|
if (!nuxt.options.dev && !nuxt.options._prepare) {
|
|
1351
1353
|
nuxt.hook("close", async () => {
|
|
1352
1354
|
const buildId = nuxt.options.runtimeConfig.app.buildId || nuxt.options.buildId;
|
|
1353
|
-
const channel =
|
|
1355
|
+
const channel = result.config.channel || "skew-protection";
|
|
1354
1356
|
logger.log(`Broadcasting update ${colors.cyan(buildId.slice(0, 8))} via ${colors.green(adapter.name)} (channel: ${colors.gray(channel)})`);
|
|
1355
|
-
|
|
1356
|
-
switch (adapter.name) {
|
|
1357
|
-
case "pusher": {
|
|
1358
|
-
const { broadcast } = await import('../dist/runtime/adapters/pusher/node.js');
|
|
1359
|
-
broadcastFn = broadcast;
|
|
1360
|
-
break;
|
|
1361
|
-
}
|
|
1362
|
-
case "ably": {
|
|
1363
|
-
const { broadcast } = await import('../dist/runtime/adapters/ably/node.js');
|
|
1364
|
-
broadcastFn = broadcast;
|
|
1365
|
-
break;
|
|
1366
|
-
}
|
|
1367
|
-
default:
|
|
1368
|
-
logger.warn(`No broadcast implementation for adapter: ${adapter.name}`);
|
|
1369
|
-
return;
|
|
1370
|
-
}
|
|
1371
|
-
await broadcastFn(adapter.config, buildId).then(() => logger.success(`Broadcast complete`)).catch((err) => logger.error(`Broadcast failed: ${err.message}`));
|
|
1357
|
+
await adapter.broadcast(result.config, buildId).then(() => logger.success(`Broadcast complete`)).catch((err) => logger.error(`Broadcast failed: ${err.message}`));
|
|
1372
1358
|
});
|
|
1373
1359
|
}
|
|
1374
1360
|
} else if (resolvedStrategy === "ws") {
|
|
@@ -1378,7 +1364,7 @@ export { subscribe }`
|
|
|
1378
1364
|
logger.warn("Websockets are only supported in Cloudflare using `cloudflare-durable` preset. Falling back to polling.");
|
|
1379
1365
|
} else {
|
|
1380
1366
|
addServerHandler({
|
|
1381
|
-
route:
|
|
1367
|
+
route: skewRoute("/ws"),
|
|
1382
1368
|
handler: resolver.resolve("./runtime/server/routes/__skew/ws")
|
|
1383
1369
|
});
|
|
1384
1370
|
addPlugin(resolver.resolve("./runtime/app/plugins/check-updates-websocket.client"));
|
|
@@ -1388,18 +1374,18 @@ export { subscribe }`
|
|
|
1388
1374
|
logger.warn("SSE not supported on Cloudflare Workers (no persistent connections). Falling back to polling.");
|
|
1389
1375
|
} else {
|
|
1390
1376
|
addServerHandler({
|
|
1391
|
-
route:
|
|
1377
|
+
route: skewRoute("/sse"),
|
|
1392
1378
|
handler: resolver.resolve("./runtime/server/routes/__skew/sse")
|
|
1393
1379
|
});
|
|
1394
1380
|
if (options.connectionTracking) {
|
|
1395
1381
|
addServerHandler({
|
|
1396
|
-
route:
|
|
1382
|
+
route: skewRoute("/subscribe-stats"),
|
|
1397
1383
|
method: "post",
|
|
1398
1384
|
handler: resolver.resolve("./runtime/server/routes/__skew/subscribe-stats.post")
|
|
1399
1385
|
});
|
|
1400
1386
|
if (options.routeTracking) {
|
|
1401
1387
|
addServerHandler({
|
|
1402
|
-
route:
|
|
1388
|
+
route: skewRoute("/route"),
|
|
1403
1389
|
method: "post",
|
|
1404
1390
|
handler: resolver.resolve("./runtime/server/routes/__skew/route.post")
|
|
1405
1391
|
});
|
|
@@ -1,8 +1,13 @@
|
|
|
1
|
+
import { fileURLToPath } from "node:url";
|
|
1
2
|
import { defineAdapter } from "../types.js";
|
|
2
3
|
import { ablyConfigSchema } from "./types.js";
|
|
3
4
|
export { ablyConfigSchema } from "./types.js";
|
|
4
5
|
export const ablyAdapter = defineAdapter({
|
|
5
6
|
name: "ably",
|
|
7
|
+
web: fileURLToPath(new URL("./web", import.meta.url)),
|
|
8
|
+
dependencies: ["ably"],
|
|
9
|
+
// Lazy, so loading nuxt.config does not load the server SDK.
|
|
10
|
+
broadcast: (config, version) => import("./node.js").then((m) => m.broadcast(config, version)),
|
|
6
11
|
schema: ablyConfigSchema,
|
|
7
12
|
toPublicConfig: ({ authUrl, clientId, channel, event }) => ({
|
|
8
13
|
authUrl,
|
|
@@ -1,7 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
clientId?: string | undefined;
|
|
5
|
-
channel?: string | undefined;
|
|
6
|
-
event?: string | undefined;
|
|
7
|
-
}>;
|
|
1
|
+
import type { BroadcastFn } from '../types.js';
|
|
2
|
+
import type { AblyAdapterConfig } from './types.js';
|
|
3
|
+
export declare const broadcast: BroadcastFn<AblyAdapterConfig>;
|
|
@@ -2,4 +2,5 @@ import type { SkewAdapter } from './types.js';
|
|
|
2
2
|
export declare function isSkewAdapter(value: unknown): value is SkewAdapter;
|
|
3
3
|
export type { AblyAdapterConfig } from './ably/types.js';
|
|
4
4
|
export type { PusherAdapterConfig } from './pusher/types.js';
|
|
5
|
-
export type { SkewAdapter, SkewAdapterFactory } from './types.js';
|
|
5
|
+
export type { AdapterConfigResult, BroadcastFn, DefineAdapterOptions, SkewAdapter, SkewAdapterFactory, SubscribeFn } from './types.js';
|
|
6
|
+
export { defineAdapter, defineNodeBroadcast, defineWebSubscribe } from './types.js';
|
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
export function isSkewAdapter(value) {
|
|
2
|
-
return typeof value === "object" && value !== null &&
|
|
2
|
+
return typeof value === "object" && value !== null && typeof value.name === "string" && typeof value.web === "string" && typeof value.parseConfig === "function" && typeof value.toPublicConfig === "function" && typeof value.broadcast === "function";
|
|
3
3
|
}
|
|
4
|
+
export { defineAdapter, defineNodeBroadcast, defineWebSubscribe } from "./types.js";
|
|
@@ -1,8 +1,13 @@
|
|
|
1
|
+
import { fileURLToPath } from "node:url";
|
|
1
2
|
import { defineAdapter } from "../types.js";
|
|
2
3
|
import { pusherConfigSchema } from "./types.js";
|
|
3
4
|
export { pusherConfigSchema } from "./types.js";
|
|
4
5
|
export const pusherAdapter = defineAdapter({
|
|
5
6
|
name: "pusher",
|
|
7
|
+
web: fileURLToPath(new URL("./web", import.meta.url)),
|
|
8
|
+
dependencies: ["pusher-js"],
|
|
9
|
+
// Lazy, so loading nuxt.config does not load the server SDK.
|
|
10
|
+
broadcast: (config, version) => import("./node.js").then((m) => m.broadcast(config, version)),
|
|
6
11
|
schema: pusherConfigSchema,
|
|
7
12
|
toPublicConfig: ({ key, cluster, channel, event }) => ({
|
|
8
13
|
key,
|
|
@@ -1,8 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
appId: string;
|
|
5
|
-
secret: string;
|
|
6
|
-
channel?: string | undefined;
|
|
7
|
-
event?: string | undefined;
|
|
8
|
-
}>;
|
|
1
|
+
import type { BroadcastFn } from '../types.js';
|
|
2
|
+
import type { PusherAdapterConfig } from './types.js';
|
|
3
|
+
export declare const broadcast: BroadcastFn<PusherAdapterConfig>;
|
|
@@ -1,24 +1,46 @@
|
|
|
1
1
|
import type { z } from 'zod';
|
|
2
|
+
export type AdapterConfigResult<TConfig> = {
|
|
3
|
+
_tag: 'Ok';
|
|
4
|
+
config: TConfig;
|
|
5
|
+
} | {
|
|
6
|
+
_tag: 'Err';
|
|
7
|
+
issues: string[];
|
|
8
|
+
};
|
|
9
|
+
export type BroadcastFn<T> = (config: T, version: string) => Promise<void>;
|
|
10
|
+
export type SubscribeFn<T> = (config: T, onMessage: (msg: {
|
|
11
|
+
version: string;
|
|
12
|
+
}) => void) => () => void;
|
|
13
|
+
/**
|
|
14
|
+
* A realtime provider for `updateStrategy`. It lives in nuxt.config, so every
|
|
15
|
+
* field must survive Nuxt's deep clone of the config: plain data and functions,
|
|
16
|
+
* never class instances.
|
|
17
|
+
*/
|
|
2
18
|
export interface SkewAdapter<TConfig = unknown, TPublicConfig extends Record<string, unknown> = Record<string, unknown>> {
|
|
3
19
|
name: string;
|
|
4
20
|
config: TConfig;
|
|
5
|
-
|
|
21
|
+
/** Validate `config` at build time. */
|
|
22
|
+
parseConfig: (config: unknown) => AdapterConfigResult<TConfig>;
|
|
23
|
+
/** The part of `config` that ships to the browser. Never include secrets. */
|
|
6
24
|
toPublicConfig: (config: TConfig) => TPublicConfig;
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
25
|
+
/**
|
|
26
|
+
* Module the client bundles: an absolute path, an alias such as `~/`, or a
|
|
27
|
+
* package specifier. It must export `subscribe` (see `defineWebSubscribe`).
|
|
28
|
+
*/
|
|
29
|
+
web: string;
|
|
30
|
+
/** Packages the build requires before it bundles `web`. */
|
|
31
|
+
dependencies: string[];
|
|
32
|
+
/** Runs on the build machine after a production build, with the new build id. */
|
|
33
|
+
broadcast: BroadcastFn<TConfig>;
|
|
11
34
|
}
|
|
12
35
|
export type SkewAdapterFactory<TConfig, TPublicConfig extends Record<string, unknown> = Record<string, unknown>> = (config: TConfig) => SkewAdapter<TConfig, TPublicConfig>;
|
|
13
36
|
export interface DefineAdapterOptions<TConfig, TPublicConfig extends Record<string, unknown>> {
|
|
14
37
|
name: string;
|
|
15
38
|
schema: z.ZodType<TConfig>;
|
|
16
39
|
toPublicConfig: (config: TConfig) => TPublicConfig;
|
|
40
|
+
web: string;
|
|
41
|
+
dependencies?: string[];
|
|
42
|
+
broadcast: BroadcastFn<TConfig>;
|
|
17
43
|
}
|
|
18
|
-
export type BroadcastFn<T> = (config: T, version: string) => Promise<void>;
|
|
19
|
-
export type SubscribeFn<T> = (config: T, onMessage: (msg: {
|
|
20
|
-
version: string;
|
|
21
|
-
}) => void) => () => void;
|
|
22
44
|
export declare function defineAdapter<TConfig, TPublicConfig extends Record<string, unknown>>(options: DefineAdapterOptions<TConfig, TPublicConfig>): SkewAdapterFactory<TConfig, TPublicConfig>;
|
|
23
45
|
export declare const defineNodeBroadcast: <T>(broadcast: BroadcastFn<T>) => BroadcastFn<T>;
|
|
24
46
|
export declare const defineWebSubscribe: <T>(subscribe: SubscribeFn<T>) => SubscribeFn<T>;
|
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
export function defineAdapter(options) {
|
|
2
|
+
const parseConfig = (config) => {
|
|
3
|
+
const result = options.schema.safeParse(config);
|
|
4
|
+
return result.success ? { _tag: "Ok", config: result.data } : { _tag: "Err", issues: result.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`) };
|
|
5
|
+
};
|
|
2
6
|
return (config) => ({
|
|
3
7
|
name: options.name,
|
|
4
8
|
config,
|
|
5
|
-
|
|
9
|
+
parseConfig,
|
|
6
10
|
toPublicConfig: options.toPublicConfig,
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
broadcast: () => {
|
|
11
|
-
throw new Error(`${options.name}.broadcast() - use node build`);
|
|
12
|
-
}
|
|
11
|
+
web: options.web,
|
|
12
|
+
dependencies: options.dependencies || [],
|
|
13
|
+
broadcast: options.broadcast
|
|
13
14
|
});
|
|
14
15
|
}
|
|
15
16
|
export const defineNodeBroadcast = (broadcast) => broadcast;
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
import { until, useDocumentVisibility, useIdle } from "@vueuse/core";
|
|
1
2
|
import { defineNuxtPlugin, reloadNuxtApp, useNuxtApp, useRuntimeConfig } from "nuxt/app";
|
|
2
3
|
import { logger } from "../../shared/logger.js";
|
|
3
4
|
const CHANNEL_NAME = "nuxt-skew-protection";
|
|
5
|
+
const IDLE_TIMEOUT_MS = 6e4;
|
|
4
6
|
export default defineNuxtPlugin({
|
|
5
7
|
name: "skew-protection:multi-tab",
|
|
6
8
|
setup() {
|
|
@@ -10,30 +12,20 @@ export default defineNuxtPlugin({
|
|
|
10
12
|
const config = useRuntimeConfig().public.skewProtection;
|
|
11
13
|
const reloadStrategy = config.reloadStrategy ?? "prompt";
|
|
12
14
|
if (reloadStrategy === "immediate" || reloadStrategy === "idle") {
|
|
15
|
+
let waitingForIdle = false;
|
|
13
16
|
nuxtApp.hooks.hook("skew:chunks-outdated", () => {
|
|
14
17
|
if (reloadStrategy === "immediate") {
|
|
15
18
|
logger.debug("[AutoReload] Chunks outdated, reloading immediately");
|
|
16
19
|
reloadNuxtApp({ force: true, persistState: true });
|
|
17
|
-
} else if (reloadStrategy === "idle") {
|
|
18
|
-
logger.debug("[AutoReload] Chunks outdated, waiting for idle");
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
reloadNuxtApp({ force: true, persistState: true });
|
|
27
|
-
}
|
|
28
|
-
};
|
|
29
|
-
document.addEventListener("visibilitychange", onVisibilityChange);
|
|
30
|
-
}
|
|
31
|
-
};
|
|
32
|
-
if ("requestIdleCallback" in window) {
|
|
33
|
-
requestIdleCallback(reload, { timeout: 1e4 });
|
|
34
|
-
} else {
|
|
35
|
-
setTimeout(reload, 5e3);
|
|
36
|
-
}
|
|
20
|
+
} else if (reloadStrategy === "idle" && !waitingForIdle) {
|
|
21
|
+
logger.debug("[AutoReload] Chunks outdated, waiting for idle or a hidden tab");
|
|
22
|
+
waitingForIdle = true;
|
|
23
|
+
const { idle, stop } = useIdle(IDLE_TIMEOUT_MS);
|
|
24
|
+
const visibility = useDocumentVisibility();
|
|
25
|
+
until(() => idle.value || visibility.value === "hidden").toBe(true).then(() => {
|
|
26
|
+
stop();
|
|
27
|
+
reloadNuxtApp({ force: true, persistState: true });
|
|
28
|
+
});
|
|
37
29
|
}
|
|
38
30
|
});
|
|
39
31
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { defineNuxtPlugin } from "nuxt/app";
|
|
2
|
+
import { buildAssetsURL } from "#internal/nuxt/paths";
|
|
2
3
|
import { logger } from "../../shared/logger.js";
|
|
3
4
|
import { useRuntimeConfigSkewProtection } from "../composables/useRuntimeConfigSkewProtection.js";
|
|
4
5
|
import { useSkewProtection } from "../composables/useSkewProtection.js";
|
|
@@ -11,6 +12,13 @@ function normalizePath(pathOrUrl) {
|
|
|
11
12
|
return pathOrUrl.replace(RE_LEADING_SLASH, "");
|
|
12
13
|
}
|
|
13
14
|
}
|
|
15
|
+
function parseSkewFile(value) {
|
|
16
|
+
const deletedChunks = typeof value === "object" && value !== null && "deletedChunks" in value ? value.deletedChunks : void 0;
|
|
17
|
+
if (typeof deletedChunks !== "object" || deletedChunks === null || Array.isArray(deletedChunks) || !Object.values(deletedChunks).every((chunks) => Array.isArray(chunks) && chunks.every((chunk) => typeof chunk === "string"))) {
|
|
18
|
+
throw new Error("Invalid skew file");
|
|
19
|
+
}
|
|
20
|
+
return deletedChunks;
|
|
21
|
+
}
|
|
14
22
|
export default defineNuxtPlugin({
|
|
15
23
|
name: "skew-protection:service-worker",
|
|
16
24
|
setup(nuxtApp) {
|
|
@@ -72,13 +80,16 @@ export default defineNuxtPlugin({
|
|
|
72
80
|
}, 5e3);
|
|
73
81
|
});
|
|
74
82
|
}
|
|
75
|
-
|
|
83
|
+
let activeSkewVersionId;
|
|
84
|
+
async function checkDeletedChunks(deletedChunks, passedReleases, versionId) {
|
|
76
85
|
if (deletedChunks.length === 0) {
|
|
77
86
|
logger.debug("[SW] No deleted chunks to check");
|
|
78
87
|
return;
|
|
79
88
|
}
|
|
80
89
|
logger.debug(`[SW] Checking ${deletedChunks.length} deleted chunks against loaded modules`);
|
|
81
90
|
const loadedModules = await getLoadedModules();
|
|
91
|
+
if (activeSkewVersionId !== versionId)
|
|
92
|
+
return;
|
|
82
93
|
if (loadedModules.length === 0) {
|
|
83
94
|
logger.debug("[SW] No loaded modules to check against");
|
|
84
95
|
return;
|
|
@@ -102,6 +113,7 @@ export default defineNuxtPlugin({
|
|
|
102
113
|
});
|
|
103
114
|
}
|
|
104
115
|
}
|
|
116
|
+
const checkedSkewVersions = /* @__PURE__ */ new Set();
|
|
105
117
|
onAppOutdated(async (_manifest) => {
|
|
106
118
|
logger.debug("[SW] App outdated event received");
|
|
107
119
|
const versions = _manifest?.skewProtection?.versions;
|
|
@@ -115,47 +127,55 @@ export default defineNuxtPlugin({
|
|
|
115
127
|
const currentIdx = sortedVersions.findIndex((v) => v.id === clientVersion);
|
|
116
128
|
const newIdx = sortedVersions.findIndex((v) => v.id === newVersionId);
|
|
117
129
|
logger.debug(`[SW] Version indices - current: ${currentIdx}, new: ${newIdx}`);
|
|
118
|
-
const allDeletedChunks = [];
|
|
119
130
|
const passedReleases = [];
|
|
120
131
|
if (currentIdx === -1) {
|
|
121
132
|
logger.debug("[SW] Current version not found in manifest, checking all versions");
|
|
122
|
-
|
|
123
|
-
passedReleases.push(version.id);
|
|
124
|
-
const versionData = versions[version.id];
|
|
125
|
-
if (versionData?.deletedChunks) {
|
|
126
|
-
allDeletedChunks.push(...versionData.deletedChunks);
|
|
127
|
-
}
|
|
128
|
-
}
|
|
133
|
+
passedReleases.push(...sortedVersions.map((v) => v.id));
|
|
129
134
|
} else if (newIdx === -1) {
|
|
130
135
|
logger.debug("[SW] New version not in manifest, checking all versions after current");
|
|
131
|
-
|
|
132
|
-
const version = sortedVersions[i];
|
|
133
|
-
if (version) {
|
|
134
|
-
passedReleases.push(version.id);
|
|
135
|
-
const versionData = versions[version.id];
|
|
136
|
-
if (versionData?.deletedChunks) {
|
|
137
|
-
allDeletedChunks.push(...versionData.deletedChunks);
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
}
|
|
136
|
+
passedReleases.push(...sortedVersions.slice(currentIdx + 1).map((v) => v.id));
|
|
141
137
|
} else {
|
|
142
138
|
logger.debug(`[SW] Checking versions between current (${currentIdx}) and new (${newIdx})`);
|
|
143
|
-
|
|
144
|
-
const version = sortedVersions[i];
|
|
145
|
-
if (version) {
|
|
146
|
-
passedReleases.push(version.id);
|
|
147
|
-
const versionData = versions[version.id];
|
|
148
|
-
if (versionData?.deletedChunks) {
|
|
149
|
-
allDeletedChunks.push(...versionData.deletedChunks);
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
}
|
|
139
|
+
passedReleases.push(...sortedVersions.slice(currentIdx + 1, newIdx + 1).map((v) => v.id));
|
|
153
140
|
}
|
|
154
|
-
|
|
155
|
-
|
|
141
|
+
if (checkedSkewVersions.has(newVersionId))
|
|
142
|
+
return;
|
|
143
|
+
activeSkewVersionId = newVersionId;
|
|
144
|
+
if (passedReleases.length === 0)
|
|
145
|
+
return;
|
|
146
|
+
checkedSkewVersions.add(newVersionId);
|
|
147
|
+
async function checkChunks(deletedChunksByVersion) {
|
|
148
|
+
const allDeletedChunks = passedReleases.flatMap((id) => deletedChunksByVersion[id] || []);
|
|
149
|
+
logger.debug(`[SW] Collected ${allDeletedChunks.length} deleted chunks across ${passedReleases.length} releases`);
|
|
150
|
+
if (allDeletedChunks.length === 0)
|
|
151
|
+
return;
|
|
156
152
|
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
157
|
-
|
|
153
|
+
if (activeSkewVersionId !== newVersionId)
|
|
154
|
+
return;
|
|
155
|
+
await checkDeletedChunks(allDeletedChunks, passedReleases, newVersionId);
|
|
156
|
+
}
|
|
157
|
+
const legacyVersions = versions;
|
|
158
|
+
if (passedReleases.every((id) => Array.isArray(legacyVersions[id]?.deletedChunks))) {
|
|
159
|
+
await checkChunks(Object.fromEntries(passedReleases.map((id) => [id, legacyVersions[id].deletedChunks])));
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
async function checkSkewFile(attempt) {
|
|
163
|
+
if (activeSkewVersionId !== newVersionId)
|
|
164
|
+
return;
|
|
165
|
+
const deletedChunksByVersion = await $fetch(buildAssetsURL(`builds/skew/${newVersionId}.json`)).then(parseSkewFile).catch((error) => {
|
|
166
|
+
if (activeSkewVersionId !== newVersionId)
|
|
167
|
+
return void 0;
|
|
168
|
+
const delay = Math.min(5e3 * 2 ** attempt, 3e5);
|
|
169
|
+
logger.warn(`[SW] Could not fetch deleted chunks for ${newVersionId}; retrying in ${delay}ms:`, error);
|
|
170
|
+
setTimeout(() => {
|
|
171
|
+
void checkSkewFile(attempt + 1).catch((error2) => logger.error("[SW] Chunk check failed:", error2));
|
|
172
|
+
}, delay);
|
|
173
|
+
return void 0;
|
|
174
|
+
});
|
|
175
|
+
if (deletedChunksByVersion && activeSkewVersionId === newVersionId)
|
|
176
|
+
await checkChunks(deletedChunksByVersion);
|
|
158
177
|
}
|
|
178
|
+
await checkSkewFile(0);
|
|
159
179
|
});
|
|
160
180
|
}
|
|
161
181
|
});
|
package/dist/runtime/types.d.ts
CHANGED
|
@@ -15,6 +15,7 @@ export interface NuxtSkewProtectionRuntimeConfig {
|
|
|
15
15
|
* `/route`, `/subscribe-stats`, `/admin/stats`). Defaults to `/__skew`. Set a
|
|
16
16
|
* sub-path (e.g. `/pro/__skew`) when the app is path-routed behind a worker
|
|
17
17
|
* that only owns part of the host, so the endpoints resolve to this app.
|
|
18
|
+
* It is the full public path, including `app.baseURL`.
|
|
18
19
|
*/
|
|
19
20
|
basePath: string;
|
|
20
21
|
assetRecovery: AssetRecoveryConfig;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nuxt-skew-protection",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "1.
|
|
4
|
+
"version": "1.6.0",
|
|
5
5
|
"description": "Solve Nuxt version skews with persistent assets and instant updates.",
|
|
6
6
|
"author": {
|
|
7
7
|
"name": "Harlan Wilton",
|
|
@@ -61,7 +61,8 @@
|
|
|
61
61
|
},
|
|
62
62
|
"files": [
|
|
63
63
|
"bin",
|
|
64
|
-
"dist"
|
|
64
|
+
"dist",
|
|
65
|
+
"skills"
|
|
65
66
|
],
|
|
66
67
|
"peerDependencies": {
|
|
67
68
|
"@nuxtjs/robots": ">=5.6.7",
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: nuxt-skew-protection
|
|
3
|
+
description: Keep old Nuxt build chunks available after a deploy and prompt open tabs to reload, with the nuxt-skew-protection module. Use when a task mentions version skew, ChunkLoadError, "Failed to fetch dynamically imported module", stale chunks 404 after deploy, update notifications, SkewNotification, useSkewProtection, isClientOutdated, the __nkpv cookie, /__skew routes, or the skewProtection config key.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# nuxt-skew-protection
|
|
7
|
+
|
|
8
|
+
Tested against `nuxt-skew-protection` 1.5.5 on Nuxt 4.5.2 (requires Nuxt `>=4.0.0`).
|
|
9
|
+
At build time the module stores every build's assets, then copies the chunks of earlier builds back into `.output/public`.
|
|
10
|
+
In the browser it detects a new deploy and tells you when the chunks the tab loaded are gone. Docs: https://nuxtseo.com/docs/skew-protection
|
|
11
|
+
|
|
12
|
+
## Setup
|
|
13
|
+
|
|
14
|
+
Add `nuxt-skew-protection` to `modules`. `@nuxtjs/robots` is a required peer. The module installs it as a module dependency, so do not add it to `modules` a second time.
|
|
15
|
+
|
|
16
|
+
Build history lives in storage. The default is the `fs` driver at `node_modules/.cache/nuxt-seo/skew-protection`, relative to the project root.
|
|
17
|
+
If CI starts from a clean checkout, every build is the first build: the build logs `No previous versions found in storage` and no old chunk survives.
|
|
18
|
+
Persist that directory, or configure a shared driver (`redis`, `upstash`, `cloudflare-kv-binding`). On GitHub Actions, give each deploy a new key so the cache saves:
|
|
19
|
+
|
|
20
|
+
```yaml
|
|
21
|
+
- uses: actions/cache@v4
|
|
22
|
+
with:
|
|
23
|
+
path: node_modules/.cache/nuxt-seo
|
|
24
|
+
key: nuxt-skew-${{ github.sha }}
|
|
25
|
+
restore-keys: nuxt-skew-
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Add a notification. Nothing shows until you render `<SkewNotification>` or call `useSkewProtection()`.
|
|
29
|
+
|
|
30
|
+
## Automatic behaviour
|
|
31
|
+
|
|
32
|
+
- **Build:** stores the assets, restores old chunks into `.output/public`, and adds `skewProtection.versions` to `/_nuxt/builds/latest.json`. Cleanup keeps 10 versions for 30 days (`maxNumberOfVersions`, `retentionDays`).
|
|
33
|
+
- **Cookie:** `__nkpv` holds the build id, for 7 days, `SameSite=Lax`. The server sets it only on requests with `sec-fetch-dest: document`. With `app.baseURL: '/app/'` the name becomes `__nkpv_app`.
|
|
34
|
+
- **Server context:** every request gets `event.context.skewVersion` from the cookie.
|
|
35
|
+
- **Service worker:** `/_nuxt-skew-sw.js` records which chunks the tab loaded.
|
|
36
|
+
- **Update strategy:** static output and Cloudflare Workers use `polling`, `cloudflare-durable` uses `ws`, and everything else uses `sse`. The client opens the connection when a component that uses the composable mounts.
|
|
37
|
+
- **Endpoints:** `/__skew/health`, `/__skew/sse`, and `/__skew/ws`, under `basePath`. With `app.baseURL: '/app/'` they sit at `/app/__skew/*`. A static build has none.
|
|
38
|
+
- **Multi tab:** a `BroadcastChannel` shares a detected deploy across tabs. Set `multiTab: false` to turn it off.
|
|
39
|
+
|
|
40
|
+
## Show an update prompt
|
|
41
|
+
|
|
42
|
+
`<SkewNotification>` is headless and renders inside `<ClientOnly>`. Put it in `app.vue` or a layout.
|
|
43
|
+
|
|
44
|
+
```vue
|
|
45
|
+
<template>
|
|
46
|
+
<SkewNotification v-slot="{ isCurrentChunksOutdated, dismiss, reload, timeAgo }">
|
|
47
|
+
<div v-if="isCurrentChunksOutdated" role="status">
|
|
48
|
+
New version released {{ timeAgo }}.
|
|
49
|
+
<button @click="reload">
|
|
50
|
+
Reload
|
|
51
|
+
</button>
|
|
52
|
+
<button @click="dismiss">
|
|
53
|
+
Not now
|
|
54
|
+
</button>
|
|
55
|
+
</div>
|
|
56
|
+
</SkewNotification>
|
|
57
|
+
</template>
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Pick the slot prop by intent:
|
|
61
|
+
|
|
62
|
+
- `isCurrentChunksOutdated`: the deploy deleted a chunk this tab loaded. Use it for the prompt.
|
|
63
|
+
- `isAppOutdated`: any new deploy. On a prerendered page this is always `false`, because the HTML carries a build id from build time.
|
|
64
|
+
- `isOpen`: either of the two.
|
|
65
|
+
|
|
66
|
+
`dismiss()` hides the prompt until the next deploy. `reload()` calls `reloadNuxtApp({ force: true, persistState: true })`.
|
|
67
|
+
To preview the UI, pass `force-open`. There is no `open` prop.
|
|
68
|
+
|
|
69
|
+
To reload without a prompt, set `reloadStrategy`:
|
|
70
|
+
|
|
71
|
+
- `'immediate'`: reload when chunks go stale.
|
|
72
|
+
- `'idle'`: reload after 60 seconds without user input, or as soon as the tab is hidden.
|
|
73
|
+
- `false`: do nothing. Handle `skew:chunks-outdated` yourself.
|
|
74
|
+
|
|
75
|
+
## React in code
|
|
76
|
+
|
|
77
|
+
`useSkewProtection()` is auto-imported. It returns refs and registers callbacks that the module removes on unmount.
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
const { onCurrentChunksOutdated, onAppOutdated, isAppOutdated, clientVersion } = useSkewProtection()
|
|
81
|
+
|
|
82
|
+
onCurrentChunksOutdated(({ invalidatedModules, passedReleases }) => {
|
|
83
|
+
// the tab runs deleted code; save state, then reload
|
|
84
|
+
})
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
If the update was already detected, a callback runs at registration.
|
|
88
|
+
`useSkewProtection({ lazy: true })` does not connect on mount. Call `connect()` yourself.
|
|
89
|
+
|
|
90
|
+
## Reject stale clients on the server
|
|
91
|
+
|
|
92
|
+
The server helpers are not auto-imported. Import them from `nuxt-skew-protection/server`:
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
import { isClientOutdated } from 'nuxt-skew-protection/server'
|
|
96
|
+
|
|
97
|
+
export default defineEventHandler((event) => {
|
|
98
|
+
if (isClientOutdated(event)) {
|
|
99
|
+
setResponseStatus(event, 409)
|
|
100
|
+
return { error: 'Client outdated', requiresReload: true }
|
|
101
|
+
}
|
|
102
|
+
return { ok: true }
|
|
103
|
+
})
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
`isClientOutdated` is `false` when the request has no cookie. The same entry exports `getClientVersion`, `getSkewProtectionCookie`, and `setSkewProtectionCookie`.
|
|
107
|
+
|
|
108
|
+
## Cloudflare
|
|
109
|
+
|
|
110
|
+
- `cloudflare-module` polls by default. Workers hold no SSE stream and no WebSocket.
|
|
111
|
+
- Real time needs `nitro.preset: 'cloudflare-durable'` and `nitro.experimental.websocket: true`.
|
|
112
|
+
- For KV storage, set `storage: { driver: 'cloudflare-kv-binding' }`. The build reads the `SKEW_PROTECTION` binding id from `nitro.cloudflare.wrangler.kv_namespaces` or `wrangler.json(c)`/`wrangler.toml`. With `@nuxthub/core`, set `storage.namespaceId`, or the build throws.
|
|
113
|
+
- On `cloudflare-module` and `cloudflare-durable`, the module adds your build asset path to `assets.run_worker_first`. Those requests count as Worker invocations.
|
|
114
|
+
|
|
115
|
+
## Traps
|
|
116
|
+
|
|
117
|
+
- **A headless browser test sees no updates.** Bot detection from `@nuxtjs/robots` matches `HeadlessChrome` and skips the SSE or WebSocket connection. Override the user agent in the test.
|
|
118
|
+
- **`useActiveConnections()` exists only with `connectionTracking: true`.** It needs `sse` or `ws`, and stats reach only connections that call `authorize()` in the Nitro hook `skew:authorize-stats`. See https://nuxtseo.com/docs/skew-protection/guides/live-connections
|
|
119
|
+
- **`sse` or `ws` on `nuxt generate` falls back to polling** with a warning. Polling uses Nuxt `experimental.checkOutdatedBuildInterval`, which defaults to one hour.
|
|
120
|
+
- **Vercel native skew protection turns off asset storage.** When `VERCEL_SKEW_PROTECTION_ENABLED=1` and `VERCEL_DEPLOYMENT_ID` are set, `bundleAssets` defaults to `false`.
|
|
121
|
+
- **A route rule that caches HTML with `max-age` and no `s-maxage` drops the cookie** for that route. The build warns. Use `s-maxage` for a CDN, or `private` for the browser only.
|
|
122
|
+
- **The cookie lasts 7 days.** It is not a session cookie. Use that duration in a cookie consent list.
|
|
123
|
+
|
|
124
|
+
## Version limits
|
|
125
|
+
|
|
126
|
+
1.x renamed these. The package binary rewrites them in place: `pnpm exec nuxt-skew-protection migrate`.
|
|
127
|
+
|
|
128
|
+
| 0.x | 1.x |
|
|
129
|
+
| --- | --- |
|
|
130
|
+
| `skew-protection:chunks-outdated` hook | `skew:chunks-outdated` |
|
|
131
|
+
| `isOutdated` | `isAppOutdated` |
|
|
132
|
+
| `bundlePreviousDeploymentChunks` | `bundleAssets` |
|
|
133
|
+
| `/_skew/*` routes | `/__skew/*` |
|
|
134
|
+
| `import { checkForUpdates } from '#skew-protection'` | `useSkewProtection().checkForUpdates` |
|
|
135
|
+
|
|
136
|
+
## Config
|
|
137
|
+
|
|
138
|
+
- `bundleAssets` (`true`): set `false` when your CDN already keeps old `/_nuxt/` files.
|
|
139
|
+
- `cookie`: set `false` to drop the cookie. `isClientOutdated` then always returns `false`.
|
|
140
|
+
- `basePath` (`/__skew`): the full public endpoint prefix, including `app.baseURL`. Auto-detected; set it only for custom routing.
|
|
141
|
+
- `updateStrategy`: pass `pusherAdapter({ key, cluster, appId, secret })` from `nuxt-skew-protection/adapters/pusher`, or `ablyAdapter({ key, authUrl })` from `nuxt-skew-protection/adapters/ably`, for a hosted realtime provider. Install `pusher-js` or `ably`. The build validates the config and broadcasts each new build id. For another provider, write one with `defineAdapter` from `nuxt-skew-protection/adapters`: https://nuxtseo.com/docs/skew-protection/providers/external
|
|
142
|
+
- Other options: https://nuxtseo.com/docs/skew-protection/api/config
|
|
143
|
+
|
|
144
|
+
## Debug
|
|
145
|
+
|
|
146
|
+
- `GET /__skew/health` returns `{ ok, version, uptime }`. Compare `version` with the client build id.
|
|
147
|
+
- `/_nuxt/builds/latest.json` lists every stored version under `skewProtection.versions`. One entry after a second deploy means storage did not persist.
|
|
148
|
+
- `debug: true` logs detection, service worker, and storage steps. Nuxt DevTools has a Skew Protection tab.
|