nuxt-skew-protection 0.3.9 → 0.4.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.
Files changed (31) hide show
  1. package/README.md +1 -0
  2. package/dist/module.d.mts +5 -3
  3. package/dist/module.json +1 -1
  4. package/dist/module.mjs +191 -45
  5. package/dist/runtime/adapters/ably/index.d.ts +7 -0
  6. package/dist/runtime/adapters/ably/index.js +7 -0
  7. package/dist/runtime/adapters/ably/node.d.ts +5 -0
  8. package/dist/runtime/adapters/ably/node.js +9 -0
  9. package/dist/runtime/adapters/ably/types.d.ts +7 -0
  10. package/dist/runtime/adapters/ably/types.js +6 -0
  11. package/dist/runtime/adapters/ably/web.d.ts +5 -0
  12. package/dist/runtime/adapters/ably/web.js +21 -0
  13. package/dist/runtime/adapters/index.d.ts +4 -0
  14. package/dist/runtime/adapters/index.js +1 -0
  15. package/dist/runtime/adapters/logger.d.ts +1 -0
  16. package/dist/runtime/adapters/logger.js +6 -0
  17. package/dist/runtime/adapters/pusher/index.d.ts +10 -0
  18. package/dist/runtime/adapters/pusher/index.js +7 -0
  19. package/dist/runtime/adapters/pusher/node.d.ts +8 -0
  20. package/dist/runtime/adapters/pusher/node.js +26 -0
  21. package/dist/runtime/adapters/pusher/types.d.ts +10 -0
  22. package/dist/runtime/adapters/pusher/types.js +12 -0
  23. package/dist/runtime/adapters/pusher/web.d.ts +8 -0
  24. package/dist/runtime/adapters/pusher/web.js +22 -0
  25. package/dist/runtime/adapters/types.d.ts +23 -0
  26. package/dist/runtime/adapters/types.js +18 -0
  27. package/dist/runtime/app/plugins/check-updates-adapter.client.d.ts +2 -0
  28. package/dist/runtime/app/plugins/check-updates-adapter.client.js +42 -0
  29. package/dist/runtime/app/utils/backoff-queue.d.ts +10 -0
  30. package/dist/runtime/app/utils/backoff-queue.js +16 -0
  31. package/package.json +27 -5
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
+ - 🔌 **Third-Party Adapters** - Real-time updates on any platform (including static sites) via [Pusher](https://pusher.com) or [Ably](https://ably.com).
27
28
 
28
29
  ## Installation
29
30
 
package/dist/module.d.mts CHANGED
@@ -1,5 +1,6 @@
1
1
  import * as _nuxt_schema from '@nuxt/schema';
2
2
  import { CookieSerializeOptions } from 'cookie-es';
3
+ import { SkewAdapter } from '../dist/runtime/adapters/types.js';
3
4
  import { NuxtSkewProtectionRuntimeConfig } from '../dist/runtime/types.js';
4
5
 
5
6
  interface ModuleOptions {
@@ -22,11 +23,12 @@ interface ModuleOptions {
22
23
  /**
23
24
  * Strategy for checking for version updates
24
25
  * - 'polling': Nuxt's native polling of builds/latest.json (default)
25
- * - 'sse': Use Server-Sent Events for real-time updates (requires sse: true)
26
- * - 'ws': Use WebSocket via Cloudflare Durable Objects (requires durableObjects: true)
26
+ * - 'sse': Use Server-Sent Events for real-time updates
27
+ * - 'ws': Use WebSocket (requires cloudflare-durable preset or experimental.websocket)
28
+ * - SkewAdapter: Third-party WebSocket provider (Pusher, Ably)
27
29
  * @default Static: 'polling', Node: 'sse', Cloudflare: 'ws'
28
30
  */
29
- checkForUpdateStrategy: 'polling' | 'sse' | 'ws';
31
+ updateStrategy?: 'polling' | 'sse' | 'ws' | SkewAdapter;
30
32
  /**
31
33
  * Cookie configuration for storing deployment version
32
34
  */
package/dist/module.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "nuxt": ">=4.0.0"
5
5
  },
6
6
  "configKey": "skewProtection",
7
- "version": "0.3.9",
7
+ "version": "0.4.0",
8
8
  "builder": {
9
9
  "@nuxt/module-builder": "1.0.2",
10
10
  "unbuild": "3.6.1"
package/dist/module.mjs CHANGED
@@ -1,11 +1,12 @@
1
1
  import { writeFileSync, unlinkSync, existsSync, readFileSync, promises } from 'node:fs';
2
- import { useLogger, useNuxt, tryUseNuxt, defineNuxtModule, createResolver, hasNuxtModule, addTypeTemplate, addComponent, addImports, addPlugin, addServerHandler } from '@nuxt/kit';
2
+ import { useLogger, useNuxt, tryUseNuxt, defineNuxtModule, createResolver, hasNuxtModule, addTypeTemplate, addComponent, addImports, addPlugin, addServerHandler, 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';
6
6
  import * as p from '@clack/prompts';
7
7
  import { $fetch } from 'ofetch';
8
8
  import { isTest, isCI, provider, env } from 'std-env';
9
+ import { isSkewAdapter } from '../dist/runtime/adapters/types.js';
9
10
  import { join } from 'node:path';
10
11
  import { tmpdir } from 'node:os';
11
12
  import { x } from 'tinyexec';
@@ -299,6 +300,18 @@ async function getVersionManifest(storage) {
299
300
  async function setVersionManifest(manifest, storage) {
300
301
  await storage.setItem("version-manifest.json", manifest);
301
302
  }
303
+ function formatBytes(bytes) {
304
+ if (bytes < 1024)
305
+ return `${bytes}B`;
306
+ if (bytes < 1024 * 1024)
307
+ return `${(bytes / 1024).toFixed(1)}KB`;
308
+ return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
309
+ }
310
+ function formatDuration(ms) {
311
+ if (ms < 1e3)
312
+ return `${ms}ms`;
313
+ return `${(ms / 1e3).toFixed(2)}s`;
314
+ }
302
315
  function createAssetManager(options) {
303
316
  const storage = createStorage({
304
317
  driver: options.driver
@@ -306,29 +319,41 @@ function createAssetManager(options) {
306
319
  const retentionDays = options.retentionDays || 7;
307
320
  const maxNumberOfVersions = options.maxNumberOfVersions || 20;
308
321
  async function getAssetsFromBuild(outputDir) {
322
+ const startTime = Date.now();
309
323
  const nuxtDir = join$1(outputDir, "public", "_nuxt");
324
+ logger.debug(`Scanning build assets from ${nuxtDir}`);
310
325
  const assets = [];
311
326
  const nuxtFiles = await getFilesRecursively(nuxtDir);
312
327
  for (const file of nuxtFiles) {
313
328
  const relativePath = file.replace(nuxtDir, "");
314
329
  assets.push(`_nuxt${relativePath}`);
315
330
  }
331
+ logger.debug(`Found ${assets.length} assets in ${formatDuration(Date.now() - startTime)}`);
316
332
  return assets;
317
333
  }
318
334
  async function updateVersionsManifest(buildId, assets) {
335
+ const startTime = Date.now();
336
+ logger.debug(`updateVersionsManifest: starting for ${buildId}`);
319
337
  const now = /* @__PURE__ */ new Date();
320
338
  const expires = new Date(now.getTime() + retentionDays * 24 * 60 * 60 * 1e3);
339
+ const manifestStart = Date.now();
321
340
  const manifest = await getVersionManifest(storage);
341
+ logger.debug(`updateVersionsManifest: loaded manifest in ${formatDuration(Date.now() - manifestStart)} (${Object.keys(manifest.versions).length} versions)`);
322
342
  const isExistingVersion = !!manifest.versions[buildId];
323
343
  manifest.current = buildId;
324
344
  manifest.versions[buildId] = {
325
345
  timestamp: now.toISOString(),
326
346
  expires: expires.toISOString(),
327
347
  assets,
328
- // deletedChunks will be calculated after deduplication in storeAssetsInStorage
348
+ // Store original assets for deletedChunks calculation (assets array gets modified by deduplication)
349
+ originalAssets: [...assets],
350
+ // deletedChunks will be calculated in storeAssetsInStorage
329
351
  deletedChunks: []
330
352
  };
353
+ const saveStart = Date.now();
331
354
  await setVersionManifest(manifest, storage);
355
+ logger.debug(`updateVersionsManifest: saved manifest in ${formatDuration(Date.now() - saveStart)}`);
356
+ logger.debug(`updateVersionsManifest: total ${formatDuration(Date.now() - startTime)}`);
332
357
  return { manifest, isExistingVersion };
333
358
  }
334
359
  async function cleanupExpiredVersions() {
@@ -400,32 +425,49 @@ function createAssetManager(options) {
400
425
  }
401
426
  }
402
427
  async function storeAssetsInStorage(buildId, outputDir, assets) {
428
+ const startTime = Date.now();
429
+ logger.debug(`storeAssetsInStorage: starting for ${buildId} (${assets.length} assets)`);
403
430
  const publicDir = join$1(outputDir, "public");
431
+ const manifestStart = Date.now();
404
432
  const manifest = await getVersionManifest(storage);
433
+ logger.debug(`storeAssetsInStorage: loaded manifest in ${formatDuration(Date.now() - manifestStart)}`);
405
434
  if (!manifest.fileIdToVersion) {
406
435
  manifest.fileIdToVersion = {};
407
436
  }
408
437
  const fileIdToVersion = manifest.fileIdToVersion;
438
+ const existingFileIds = Object.keys(fileIdToVersion).length;
439
+ logger.debug(`storeAssetsInStorage: fileIdToVersion has ${existingFileIds} entries`);
409
440
  const currentVersion = manifest.versions[buildId];
410
441
  if (currentVersion) {
411
442
  const previousVersionId = getPreviousVersion(manifest, buildId);
412
- const previousAssets = previousVersionId ? manifest.versions[previousVersionId]?.assets || [] : [];
443
+ const previousVersion = previousVersionId ? manifest.versions[previousVersionId] : null;
444
+ const previousAssets = previousVersion?.originalAssets || previousVersion?.assets || [];
413
445
  currentVersion.deletedChunks = calculateDeletedChunks(assets, previousAssets);
414
- }
415
- await processBatch(assets, 50, async (asset) => {
446
+ logger.debug(`storeAssetsInStorage: calculated ${currentVersion.deletedChunks.length} deleted chunks vs ${previousVersionId || "none"}`);
447
+ }
448
+ let storedCount = 0;
449
+ let deduplicatedCount = 0;
450
+ let totalBytes = 0;
451
+ let skippedCount = 0;
452
+ const storeStart = Date.now();
453
+ await processBatch(assets, 25, async (asset) => {
416
454
  const fileId = extractFileId(asset);
455
+ if (fileId && fileIdToVersion[fileId] === buildId) {
456
+ skippedCount++;
457
+ return;
458
+ }
417
459
  const assetPath = join$1(publicDir, asset);
418
460
  const assetData = await promises.readFile(assetPath).catch((error) => {
419
- if (options.debug) {
420
- logger.warn(`Failed to read ${assetPath}:`, error);
421
- }
461
+ logger.debug(`Failed to read ${assetPath}: ${error}`);
422
462
  return null;
423
463
  });
424
464
  if (assetData) {
465
+ totalBytes += assetData.byteLength;
425
466
  const storageKey = `${buildId}/${asset}`;
426
467
  await storage.setItemRaw(storageKey, assetData).catch((error) => {
427
468
  logger.error(`Failed to store ${storageKey}:`, error?.message || error);
428
469
  });
470
+ storedCount++;
429
471
  if (fileId && fileIdToVersion[fileId] && fileIdToVersion[fileId] !== buildId) {
430
472
  const previousVersionId = fileIdToVersion[fileId];
431
473
  if (manifest.versions[previousVersionId]) {
@@ -436,10 +478,9 @@ function createAssetManager(options) {
436
478
  previousAssets.splice(assetIndex, 1);
437
479
  const oldStorageKey = `${previousVersionId}/${oldAssetPath}`;
438
480
  await storage.removeItem(oldStorageKey).catch((error) => {
439
- if (options.debug) {
440
- logger.warn(`Failed to remove duplicate asset ${oldStorageKey}:`, error);
441
- }
481
+ logger.debug(`Failed to remove duplicate asset ${oldStorageKey}: ${error}`);
442
482
  });
483
+ deduplicatedCount++;
443
484
  }
444
485
  }
445
486
  }
@@ -448,7 +489,12 @@ function createAssetManager(options) {
448
489
  }
449
490
  }
450
491
  });
492
+ logger.debug(`storeAssetsInStorage: stored ${storedCount} assets (${formatBytes(totalBytes)}) in ${formatDuration(Date.now() - storeStart)}`);
493
+ logger.debug(`storeAssetsInStorage: deduplicated ${deduplicatedCount}, skipped ${skippedCount}`);
494
+ const saveStart = Date.now();
451
495
  await setVersionManifest(manifest, storage);
496
+ logger.debug(`storeAssetsInStorage: saved manifest in ${formatDuration(Date.now() - saveStart)}`);
497
+ logger.debug(`storeAssetsInStorage: total ${formatDuration(Date.now() - startTime)}`);
452
498
  }
453
499
  async function listExistingVersions() {
454
500
  const manifest = await getVersionManifest(storage);
@@ -461,16 +507,21 @@ function createAssetManager(options) {
461
507
  }));
462
508
  }
463
509
  async function restoreOldAssetsToPublic(currentBuildId, outputDir, currentAssets = [], isExistingVersion = false) {
510
+ const startTime = Date.now();
511
+ logger.debug(`restoreOldAssetsToPublic: starting for ${currentBuildId}`);
512
+ const manifestStart = Date.now();
464
513
  const manifest = await getVersionManifest(storage);
514
+ logger.debug(`restoreOldAssetsToPublic: loaded manifest in ${formatDuration(Date.now() - manifestStart)}`);
465
515
  if (!manifest || !manifest.versions) {
516
+ logger.debug(`restoreOldAssetsToPublic: no manifest or versions, skipping`);
466
517
  return;
467
518
  }
468
519
  if (isExistingVersion) {
469
- if (options.debug) {
470
- logger.info(`Build ID ${currentBuildId} already exists, skipping restore`);
471
- }
520
+ logger.debug(`restoreOldAssetsToPublic: build ${currentBuildId} already exists, skipping restore`);
472
521
  return;
473
522
  }
523
+ const versionCount = Object.keys(manifest.versions).length - 1;
524
+ logger.debug(`restoreOldAssetsToPublic: checking ${versionCount} previous versions`);
474
525
  const publicDir = join$1(outputDir, "public");
475
526
  const restoredAssets = [];
476
527
  const currentAssetsSet = new Set(currentAssets);
@@ -481,24 +532,37 @@ function createAssetManager(options) {
481
532
  currentFileIds.add(fileId);
482
533
  }
483
534
  }
535
+ logger.debug(`restoreOldAssetsToPublic: current build has ${currentAssets.length} assets, ${currentFileIds.size} unique fileIds`);
484
536
  const now = Date.now();
485
537
  const assetTasks = [];
538
+ let skippedSamePath = 0;
539
+ let skippedSameFileId = 0;
486
540
  for (const [versionId, versionData] of Object.entries(manifest.versions)) {
487
541
  if (versionId === currentBuildId) {
488
542
  continue;
489
543
  }
490
544
  for (const asset of versionData.assets) {
491
545
  if (currentAssetsSet.has(asset)) {
546
+ skippedSamePath++;
492
547
  continue;
493
548
  }
494
549
  const fileId = extractFileId(asset);
495
550
  if (fileId && currentFileIds.has(fileId)) {
551
+ skippedSameFileId++;
496
552
  continue;
497
553
  }
498
554
  assetTasks.push({ versionId, asset, versionData });
499
555
  }
500
556
  }
501
- const batchResults = await processBatch(assetTasks, 50, async ({ versionId, asset, versionData }) => {
557
+ logger.debug(`restoreOldAssetsToPublic: ${assetTasks.length} assets to restore (skipped: ${skippedSamePath} same path, ${skippedSameFileId} same fileId)`);
558
+ if (assetTasks.length === 0) {
559
+ logger.debug(`restoreOldAssetsToPublic: nothing to restore, total ${formatDuration(Date.now() - startTime)}`);
560
+ return;
561
+ }
562
+ const restoreStart = Date.now();
563
+ let totalBytes = 0;
564
+ let failedCount = 0;
565
+ const batchResults = await processBatch(assetTasks, 25, async ({ versionId, asset, versionData }) => {
502
566
  const storageKey = `${versionId}/${asset}`;
503
567
  return await storage.getItemRaw(storageKey).then(async (assetData) => {
504
568
  if (assetData) {
@@ -513,6 +577,7 @@ function createAssetManager(options) {
513
577
  dataToWrite = Buffer.from(assetData);
514
578
  }
515
579
  await promises.writeFile(targetPath, dataToWrite);
580
+ totalBytes += dataToWrite.byteLength;
516
581
  const versionTimestamp = new Date(versionData.timestamp).getTime();
517
582
  const ageMs = now - versionTimestamp;
518
583
  const ageMinutes = Math.floor(ageMs / 6e4);
@@ -537,25 +602,34 @@ function createAssetManager(options) {
537
602
  }
538
603
  return null;
539
604
  }).catch((error) => {
540
- if (options.debug) {
541
- logger.warn(`Failed to restore asset ${asset} from version ${versionId}:`, error);
542
- }
605
+ failedCount++;
606
+ logger.debug(`Failed to restore asset ${asset} from version ${versionId}: ${error}`);
543
607
  return null;
544
608
  });
545
609
  });
546
610
  restoredAssets.push(...batchResults.filter((r) => r !== null));
547
- if (restoredAssets.length > 0) {
548
- restoredAssets.forEach((item, index) => {
549
- const isLast = index === restoredAssets.length - 1;
611
+ logger.debug(`restoreOldAssetsToPublic: restored ${restoredAssets.length} assets (${formatBytes(totalBytes)}) in ${formatDuration(Date.now() - restoreStart)}${failedCount > 0 ? `, ${failedCount} failed` : ""}`);
612
+ const restoredByVersion = /* @__PURE__ */ new Map();
613
+ for (const item of restoredAssets) {
614
+ restoredByVersion.set(item.versionId, (restoredByVersion.get(item.versionId) || 0) + 1);
615
+ }
616
+ const otherVersions = Object.entries(manifest.versions).filter(([id]) => id !== currentBuildId);
617
+ if (otherVersions.length > 0) {
618
+ otherVersions.forEach(([versionId, versionData], index) => {
619
+ const isLast = index === otherVersions.length - 1;
550
620
  const prefix = isLast ? " \u2514\u2500" : " \u251C\u2500";
551
- const sizeKB = (item.size / 1024).toFixed(2);
552
- const displayPath = `public/${item.asset}`;
553
- const sizeInfo = `(${sizeKB} kB)`;
554
- const versionInfo = `[${item.versionId.slice(0, 8)}]`;
555
- const ageInfo = `(${item.age})`;
556
- logger.log(colors.gray(`${prefix} ${displayPath} ${sizeInfo} ${versionInfo} ${ageInfo}`));
621
+ const versionTimestamp = new Date(versionData.timestamp).getTime();
622
+ const ageMs = now - versionTimestamp;
623
+ const ageMinutes = Math.floor(ageMs / 6e4);
624
+ const ageHours = Math.floor(ageMinutes / 60);
625
+ const ageDays = Math.floor(ageHours / 24);
626
+ const ageStr = ageDays > 0 ? `${ageDays}d ago` : ageHours > 0 ? `${ageHours}h ago` : ageMinutes > 0 ? `${ageMinutes}m ago` : "just now";
627
+ const restored = restoredByVersion.get(versionId) || 0;
628
+ const total = versionData.originalAssets?.length || versionData.assets.length;
629
+ logger.log(colors.gray(`${prefix} ${versionId.slice(0, 8)} (${restored}/${total} files restored, ${ageStr})`));
557
630
  });
558
631
  }
632
+ logger.debug(`restoreOldAssetsToPublic: total ${formatDuration(Date.now() - startTime)}`);
559
633
  }
560
634
  async function augmentBuildMetadata(buildId, outputDir) {
561
635
  const manifest = await getVersionManifest(storage);
@@ -647,7 +721,8 @@ const module$1 = defineNuxtModule({
647
721
  nuxt.options.runtimeConfig.public = nuxt.options.runtimeConfig.public || {};
648
722
  nuxt.options.runtimeConfig.public.skewProtection = {
649
723
  cookie: options.cookie,
650
- debug: options.debug
724
+ debug: options.debug,
725
+ version
651
726
  };
652
727
  const nitroPreset = resolveNitroPreset(nuxt.options.nitro);
653
728
  const isNuxtHub = hasNuxtModule("@nuxthub/core");
@@ -726,8 +801,21 @@ export {}
726
801
  if (!nuxt.options.dev) {
727
802
  const isCloudflareRuntime = nitroPreset?.includes("cloudflare");
728
803
  const isVercel = nitroPreset?.includes("vercel") || process.env.VERCEL_SKEW_PROTECTION_ENABLED === "1";
729
- if (!options.checkForUpdateStrategy) {
730
- options.checkForUpdateStrategy = isStaticPreset(nuxt) ? "polling" : isCloudflareRuntime ? "ws" : options.checkForUpdateStrategy || "sse";
804
+ const isStatic = isStaticPreset(nuxt);
805
+ const isAdapter = isSkewAdapter(options.updateStrategy);
806
+ let resolvedStrategy = "polling";
807
+ if (isAdapter) {
808
+ resolvedStrategy = "adapter";
809
+ } else if (options.updateStrategy === "ws") {
810
+ resolvedStrategy = "ws";
811
+ } else if (options.updateStrategy === "sse") {
812
+ resolvedStrategy = "sse";
813
+ } else if (!options.updateStrategy) {
814
+ resolvedStrategy = isStatic ? "polling" : isCloudflareRuntime ? "ws" : "sse";
815
+ }
816
+ if (isStatic && resolvedStrategy !== "polling" && resolvedStrategy !== "adapter") {
817
+ logger.warn(`Strategy "${resolvedStrategy}" requires a server but static generation detected. Falling back to polling.`);
818
+ resolvedStrategy = "polling";
731
819
  }
732
820
  if (isVercel) {
733
821
  addServerHandler({
@@ -774,11 +862,12 @@ export {}
774
862
  const oldestTimestamp = Math.min(...timestamps);
775
863
  const daysSince = Math.floor((Date.now() - oldestTimestamp) / (1e3 * 60 * 60 * 24));
776
864
  const timeInfo = daysSince > 0 ? `${daysSince} day${daysSince > 1 ? "s" : ""} ago` : "today";
777
- logger.log(colors.cyan(`Initialising Nuxt Skew Protection v${version}...`));
778
- logger.log(` ${totalReleases} releases stored (oldest from ${timeInfo})`);
779
865
  const storageInfo = options.storage.base ? `${colors.green(options.storage.driver)} ${colors.gray(`(${options.storage.base})`)}` : colors.green(options.storage.driver);
780
- logger.log(` Database: ${storageInfo}`);
781
- logger.log(` Storing ${colors.yellow(assets.length.toString())} assets in storage...`);
866
+ if (totalReleases === 1) {
867
+ logger.warn(`No previous versions found in storage. This is either the first deployment or storage is misconfigured. https://nuxtseo.com/docs/skew-protection/storage-configuration`);
868
+ } else {
869
+ logger.log(`Storing ${colors.yellow(assets.length.toString())} assets for ${colors.cyan(buildId.slice(0, 8))} (${totalReleases} releases, oldest from ${timeInfo}) [${storageInfo}]`);
870
+ }
782
871
  await assetManager.storeAssetsInStorage(buildId, outputDir, assets).catch((error) => {
783
872
  logger.error(`Failed to store assets:`, error instanceof Error ? error.message : error);
784
873
  throw error;
@@ -787,9 +876,10 @@ export {}
787
876
  const versionCount = existingVersions.filter((v) => v.id !== buildId).length;
788
877
  logger.success(`Successfully stored ${assets.length} assets for latest release`);
789
878
  if (versionCount > 0) {
879
+ const updatedManifest = await assetManager.getManifest();
790
880
  let totalAssets = 0;
791
881
  const versionSizes = [];
792
- for (const [vId, vData] of Object.entries(manifest.versions)) {
882
+ for (const [vId, vData] of Object.entries(updatedManifest.versions)) {
793
883
  if (vId !== buildId) {
794
884
  totalAssets += vData.assets.length;
795
885
  versionSizes.push(`${vId.slice(0, 8)}:${vData.assets.length}`);
@@ -807,27 +897,83 @@ export {}
807
897
  });
808
898
  });
809
899
  }
810
- if (options.checkForUpdateStrategy === "ws") {
900
+ if (resolvedStrategy === "adapter" && isAdapter) {
901
+ const adapter = options.updateStrategy;
902
+ nuxt.options.runtimeConfig.public.skewProtection.adapterName = adapter.name;
903
+ const result = adapter.schema.safeParse(adapter.config);
904
+ if (!result.success) {
905
+ const errors = result.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join(", ");
906
+ throw new Error(`${adapter.name} adapter config invalid: ${errors}`);
907
+ }
908
+ if (adapter.name === "pusher") {
909
+ if (!await tryResolveModule("pusher-js", nuxt.options.rootDir)) {
910
+ const msg = `The pusher adapter requires \`pusher-js\`. Install with: npx nypm add pusher-js`;
911
+ if (!nuxt.options.dev && !nuxt.options._prepare) {
912
+ throw new Error(msg);
913
+ } else {
914
+ logger.warn(msg);
915
+ }
916
+ }
917
+ } else if (adapter.name === "ably") {
918
+ if (!await tryResolveModule("ably", nuxt.options.rootDir)) {
919
+ const msg = `The ably adapter requires \`ably\`. Install with: npx nypm add ably`;
920
+ if (!nuxt.options.dev && !nuxt.options._prepare) {
921
+ throw new Error(msg);
922
+ } else {
923
+ logger.warn(msg);
924
+ }
925
+ }
926
+ }
927
+ const template = addTemplate({
928
+ filename: "skew-adapter.mjs",
929
+ getContents: () => `import { subscribe } from 'nuxt-skew-protection/adapters/${adapter.name}/web'
930
+ export const config = ${JSON.stringify(adapter.config)}
931
+ export { subscribe }`
932
+ });
933
+ nuxt.options.alias["#skew-adapter"] = template.dst;
934
+ addPlugin({
935
+ src: resolver.resolve("./runtime/app/plugins/check-updates-adapter.client"),
936
+ mode: "client"
937
+ });
938
+ if (!nuxt.options.dev && !nuxt.options._prepare) {
939
+ nuxt.hook("close", async () => {
940
+ const buildId = nuxt.options.runtimeConfig.app.buildId || nuxt.options.buildId;
941
+ const channel = adapter.config.channel || "skew-protection";
942
+ logger.log(`Broadcasting update ${colors.cyan(buildId.slice(0, 8))} via ${colors.green(adapter.name)} (channel: ${colors.gray(channel)})`);
943
+ let broadcastFn;
944
+ switch (adapter.name) {
945
+ case "pusher": {
946
+ const { broadcast } = await import('../dist/runtime/adapters/pusher/node.js');
947
+ broadcastFn = broadcast;
948
+ break;
949
+ }
950
+ case "ably": {
951
+ const { broadcast } = await import('../dist/runtime/adapters/ably/node.js');
952
+ broadcastFn = broadcast;
953
+ break;
954
+ }
955
+ default:
956
+ logger.warn(`No broadcast implementation for adapter: ${adapter.name}`);
957
+ return;
958
+ }
959
+ await broadcastFn(adapter.config, buildId).then(() => logger.success(`Broadcast complete`)).catch((err) => logger.error(`Broadcast failed: ${err.message}`));
960
+ });
961
+ }
962
+ } else if (resolvedStrategy === "ws") {
811
963
  if (!nuxt.options.nitro?.experimental?.websocket) {
812
964
  logger.warn("You need to enable `experimental.websocket` in your Nitro config to use WebSockets. Falling back to polling.");
813
- options.checkForUpdateStrategy = "polling";
814
965
  } else if (isCloudflareRuntime && nitroPreset !== "cloudflare-durable") {
815
966
  logger.warn("Websockets are only supported in Cloudflare using `cloudflare-durable` preset. Falling back to polling.");
816
- options.checkForUpdateStrategy = "polling";
817
967
  } else {
818
968
  addServerHandler({
819
969
  route: "/_skew/ws",
820
- handler: resolver.resolve(`./runtime/server/routes/_skew/ws`)
970
+ handler: resolver.resolve("./runtime/server/routes/_skew/ws")
821
971
  });
822
972
  addPlugin(resolver.resolve("./runtime/app/plugins/check-updates-websocket.client"));
823
973
  }
824
- } else if (options.checkForUpdateStrategy === "sse") {
825
- if (isStaticPreset(nuxt) || isCloudflareRuntime) {
826
- logger.warn("SSE not supported for static sites or Cloudflare Workers. Falling back to polling.");
827
- options.checkForUpdateStrategy = "polling";
828
- } else if (isCloudflareRuntime) {
974
+ } else if (resolvedStrategy === "sse") {
975
+ if (isCloudflareRuntime) {
829
976
  logger.warn("SSE not supported on Cloudflare Workers (no persistent connections). Falling back to polling.");
830
- options.checkForUpdateStrategy = "polling";
831
977
  } else {
832
978
  addServerHandler({
833
979
  route: "/_skew/sse",
@@ -0,0 +1,7 @@
1
+ export type { AblyAdapterConfig } from './types.js';
2
+ export { ablyConfigSchema } from './types.js';
3
+ export declare const ablyAdapter: import("..").SkewAdapterFactory<{
4
+ key: string;
5
+ channel?: string | undefined;
6
+ event?: string | undefined;
7
+ }>;
@@ -0,0 +1,7 @@
1
+ import { defineAdapter } from "../types.js";
2
+ import { ablyConfigSchema } from "./types.js";
3
+ export { ablyConfigSchema } from "./types.js";
4
+ export const ablyAdapter = defineAdapter({
5
+ name: "ably",
6
+ schema: ablyConfigSchema
7
+ });
@@ -0,0 +1,5 @@
1
+ export declare const broadcast: import("../types.js").BroadcastFn<{
2
+ key: string;
3
+ channel?: string | undefined;
4
+ event?: string | undefined;
5
+ }>;
@@ -0,0 +1,9 @@
1
+ import { Rest } from "ably";
2
+ import { defineNodeBroadcast } from "../types.js";
3
+ export const broadcast = defineNodeBroadcast(async (config, version) => {
4
+ const ably = new Rest({ key: config.key });
5
+ const channelName = config.channel || "skew-protection";
6
+ const eventName = config.event || "VersionUpdated";
7
+ const channel = ably.channels.get(channelName);
8
+ await channel.publish(eventName, { version });
9
+ });
@@ -0,0 +1,7 @@
1
+ import { z } from 'zod';
2
+ export declare const ablyConfigSchema: z.ZodObject<{
3
+ key: z.ZodString;
4
+ channel: z.ZodOptional<z.ZodString>;
5
+ event: z.ZodOptional<z.ZodString>;
6
+ }, z.core.$strip>;
7
+ export type AblyAdapterConfig = z.infer<typeof ablyConfigSchema>;
@@ -0,0 +1,6 @@
1
+ import { z } from "zod";
2
+ export const ablyConfigSchema = z.object({
3
+ key: z.string().min(1, "Ably key is required"),
4
+ channel: z.string().optional(),
5
+ event: z.string().optional()
6
+ });
@@ -0,0 +1,5 @@
1
+ export declare const subscribe: import("../types.js").SubscribeFn<{
2
+ key: string;
3
+ channel?: string | undefined;
4
+ event?: string | undefined;
5
+ }>;
@@ -0,0 +1,21 @@
1
+ import { onNuxtReady } from "nuxt/app";
2
+ import { defineWebSubscribe } from "../types.js";
3
+ export const subscribe = defineWebSubscribe((config, onMessage) => {
4
+ let cleanup;
5
+ onNuxtReady(async () => {
6
+ const { Realtime } = await import("ably");
7
+ const ably = new Realtime({ key: config.key });
8
+ const channelName = config.channel || "skew-protection";
9
+ const eventName = config.event || "VersionUpdated";
10
+ const channel = ably.channels.get(channelName);
11
+ await channel.subscribe(eventName, (message) => {
12
+ const data = typeof message.data === "string" ? JSON.parse(message.data) : message.data;
13
+ onMessage({ version: data.version });
14
+ });
15
+ cleanup = () => {
16
+ channel.unsubscribe();
17
+ ably.close();
18
+ };
19
+ });
20
+ return () => cleanup?.();
21
+ });
@@ -0,0 +1,4 @@
1
+ export type { AblyAdapterConfig } from './ably/types.js';
2
+ export type { PusherAdapterConfig } from './pusher/types.js';
3
+ export type { SkewAdapter, SkewAdapterFactory } from './types.js';
4
+ export { isSkewAdapter } from './types.js';
@@ -0,0 +1 @@
1
+ export { isSkewAdapter } from "./types.js";
@@ -0,0 +1 @@
1
+ export declare const logger: import("consola").ConsolaInstance;
@@ -0,0 +1,6 @@
1
+ import { createConsola } from "consola";
2
+ export const logger = createConsola({
3
+ defaults: {
4
+ tag: "nuxt-skew-protection"
5
+ }
6
+ });
@@ -0,0 +1,10 @@
1
+ export type { PusherAdapterConfig } from './types.js';
2
+ export { pusherConfigSchema } from './types.js';
3
+ export declare const pusherAdapter: import("..").SkewAdapterFactory<{
4
+ key: string;
5
+ cluster: string;
6
+ appId: string;
7
+ secret: string;
8
+ channel?: string | undefined;
9
+ event?: string | undefined;
10
+ }>;
@@ -0,0 +1,7 @@
1
+ import { defineAdapter } from "../types.js";
2
+ import { pusherConfigSchema } from "./types.js";
3
+ export { pusherConfigSchema } from "./types.js";
4
+ export const pusherAdapter = defineAdapter({
5
+ name: "pusher",
6
+ schema: pusherConfigSchema
7
+ });
@@ -0,0 +1,8 @@
1
+ export declare const broadcast: import("../types.js").BroadcastFn<{
2
+ key: string;
3
+ cluster: string;
4
+ appId: string;
5
+ secret: string;
6
+ channel?: string | undefined;
7
+ event?: string | undefined;
8
+ }>;
@@ -0,0 +1,26 @@
1
+ import { createHash, createHmac } from "node:crypto";
2
+ import { defineNodeBroadcast } from "../types.js";
3
+ export const broadcast = defineNodeBroadcast(async (config, version) => {
4
+ const channelName = config.channel || "skew-protection";
5
+ const eventName = config.event || "VersionUpdated";
6
+ const body = JSON.stringify({
7
+ name: eventName,
8
+ channel: channelName,
9
+ data: JSON.stringify({ version })
10
+ });
11
+ const timestamp = Math.floor(Date.now() / 1e3);
12
+ const bodyMd5 = createHash("md5").update(body).digest("hex");
13
+ const stringToSign = `POST
14
+ /apps/${config.appId}/events
15
+ auth_key=${config.key}&auth_timestamp=${timestamp}&auth_version=1.0&body_md5=${bodyMd5}`;
16
+ const signature = createHmac("sha256", config.secret).update(stringToSign).digest("hex");
17
+ const url = `https://api-${config.cluster}.pusher.com/apps/${config.appId}/events?auth_key=${config.key}&auth_timestamp=${timestamp}&auth_version=1.0&body_md5=${bodyMd5}&auth_signature=${signature}`;
18
+ const response = await fetch(url, {
19
+ method: "POST",
20
+ headers: { "Content-Type": "application/json" },
21
+ body
22
+ });
23
+ if (!response.ok) {
24
+ throw new Error(`Pusher broadcast failed: ${response.status} ${await response.text()}`);
25
+ }
26
+ });
@@ -0,0 +1,10 @@
1
+ import { z } from 'zod';
2
+ export declare const pusherConfigSchema: z.ZodObject<{
3
+ key: z.ZodString;
4
+ cluster: z.ZodString;
5
+ appId: z.ZodString;
6
+ secret: z.ZodString;
7
+ channel: z.ZodOptional<z.ZodString>;
8
+ event: z.ZodOptional<z.ZodString>;
9
+ }, z.core.$strip>;
10
+ export type PusherAdapterConfig = z.infer<typeof pusherConfigSchema>;
@@ -0,0 +1,12 @@
1
+ import { z } from "zod";
2
+ export const pusherConfigSchema = z.object({
3
+ // Client (subscribe)
4
+ key: z.string().min(1, "Pusher key is required"),
5
+ cluster: z.string().min(1, "Pusher cluster is required"),
6
+ // Server (broadcast)
7
+ appId: z.string().min(1, "Pusher appId is required"),
8
+ secret: z.string().min(1, "Pusher secret is required"),
9
+ // Optional
10
+ channel: z.string().optional(),
11
+ event: z.string().optional()
12
+ });
@@ -0,0 +1,8 @@
1
+ export declare const subscribe: import("../types.js").SubscribeFn<{
2
+ key: string;
3
+ cluster: string;
4
+ appId: string;
5
+ secret: string;
6
+ channel?: string | undefined;
7
+ event?: string | undefined;
8
+ }>;
@@ -0,0 +1,22 @@
1
+ import { onNuxtReady } from "nuxt/app";
2
+ import { defineWebSubscribe } from "../types.js";
3
+ export const subscribe = defineWebSubscribe((config, onMessage) => {
4
+ let cleanup;
5
+ onNuxtReady(async () => {
6
+ const Pusher = await import("pusher-js").then((m) => m.default || m);
7
+ const pusher = new Pusher(config.key, {
8
+ cluster: config.cluster
9
+ });
10
+ const channelName = config.channel || "skew-protection";
11
+ const eventName = config.event || "VersionUpdated";
12
+ const channel = pusher.subscribe(channelName);
13
+ channel.bind(eventName, (data) => {
14
+ onMessage({ version: data.version });
15
+ });
16
+ cleanup = () => {
17
+ channel.unbind(eventName);
18
+ pusher.unsubscribe(channelName);
19
+ };
20
+ });
21
+ return () => cleanup?.();
22
+ });
@@ -0,0 +1,23 @@
1
+ import type { z } from 'zod';
2
+ export interface SkewAdapter<TConfig = unknown> {
3
+ name: string;
4
+ config: TConfig;
5
+ schema: z.ZodType<TConfig>;
6
+ subscribe: (onMessage: (msg: {
7
+ version: string;
8
+ }) => void) => () => void;
9
+ broadcast: (version: string) => Promise<void>;
10
+ }
11
+ export type SkewAdapterFactory<T> = (config: T) => SkewAdapter<T>;
12
+ export interface DefineAdapterOptions<T> {
13
+ name: string;
14
+ schema: z.ZodType<T>;
15
+ }
16
+ export declare function defineAdapter<T>(options: DefineAdapterOptions<T>): SkewAdapterFactory<T>;
17
+ export type BroadcastFn<T> = (config: T, version: string) => Promise<void>;
18
+ export declare const defineNodeBroadcast: <T>(broadcast: BroadcastFn<T>) => BroadcastFn<T>;
19
+ export type SubscribeFn<T> = (config: T, onMessage: (msg: {
20
+ version: string;
21
+ }) => void) => () => void;
22
+ export declare const defineWebSubscribe: <T>(subscribe: SubscribeFn<T>) => SubscribeFn<T>;
23
+ export declare function isSkewAdapter(value: unknown): value is SkewAdapter;
@@ -0,0 +1,18 @@
1
+ export function defineAdapter(options) {
2
+ return (config) => ({
3
+ name: options.name,
4
+ config,
5
+ schema: options.schema,
6
+ subscribe: () => {
7
+ throw new Error(`${options.name}.subscribe() - use web build`);
8
+ },
9
+ broadcast: () => {
10
+ throw new Error(`${options.name}.broadcast() - use node build`);
11
+ }
12
+ });
13
+ }
14
+ export const defineNodeBroadcast = (broadcast) => broadcast;
15
+ export const defineWebSubscribe = (subscribe) => subscribe;
16
+ export function isSkewAdapter(value) {
17
+ return typeof value === "object" && value !== null && "name" in value && "subscribe" in value && "broadcast" in value && typeof value.subscribe === "function" && typeof value.broadcast === "function";
18
+ }
@@ -0,0 +1,2 @@
1
+ declare const _default: import("nuxt/app").Plugin<Record<string, unknown>> & import("nuxt/app").ObjectPlugin<Record<string, unknown>>;
2
+ export default _default;
@@ -0,0 +1,42 @@
1
+ import { config, subscribe } from "#skew-adapter";
2
+ import { defineNuxtPlugin, useRuntimeConfig } from "nuxt/app";
3
+ import { logger } from "../../shared/logger.js";
4
+ import { checkForUpdates, useSkewProtection } from "../composables/useSkewProtection.js";
5
+ import { createBackoffQueue } from "../utils/backoff-queue.js";
6
+ export default defineNuxtPlugin({
7
+ name: "skew-protection:adapter-updates",
8
+ setup(nuxtApp) {
9
+ const { clientVersion } = useSkewProtection();
10
+ const adapterName = useRuntimeConfig().public.skewProtection.adapterName;
11
+ const channel = config.channel || "skew-protection";
12
+ logger.debug(`[${adapterName}] Subscribing to channel: ${channel}`);
13
+ let cleanup = null;
14
+ const queue = createBackoffQueue({
15
+ delays: [0, 5e3, 3e4, 3e5],
16
+ onTick: () => nuxtApp.runWithContext(checkForUpdates)
17
+ });
18
+ nuxtApp.hook("app:mounted", () => {
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
+ }
41
+ }
42
+ });
@@ -0,0 +1,10 @@
1
+ export interface BackoffQueueOptions {
2
+ delays: number[];
3
+ onTick: (index: number) => void;
4
+ }
5
+ export interface BackoffQueue {
6
+ start: () => void;
7
+ clear: () => void;
8
+ isRunning: () => boolean;
9
+ }
10
+ export declare function createBackoffQueue(options: BackoffQueueOptions): BackoffQueue;
@@ -0,0 +1,16 @@
1
+ export function createBackoffQueue(options) {
2
+ const { delays, onTick } = options;
3
+ let timers = [];
4
+ const clear = () => {
5
+ timers.forEach(clearTimeout);
6
+ timers = [];
7
+ };
8
+ const start = () => {
9
+ clear();
10
+ delays.forEach((delay, i) => {
11
+ timers.push(setTimeout(() => onTick(i), delay));
12
+ });
13
+ };
14
+ const isRunning = () => timers.length > 0;
15
+ return { start, clear, isRunning };
16
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nuxt-skew-protection",
3
3
  "type": "module",
4
- "version": "0.3.9",
4
+ "version": "0.4.0",
5
5
  "description": "Solve Nuxt version skews with persistent assets and instant updates.",
6
6
  "author": {
7
7
  "name": "Harlan Wilton",
@@ -22,12 +22,31 @@
22
22
  "types": "./dist/types.d.mts",
23
23
  "import": "./dist/module.mjs"
24
24
  },
25
- "./server": "./dist/runtime/server/index.js"
25
+ "./server": "./dist/runtime/server/index.js",
26
+ "./adapters": "./dist/runtime/adapters/index.js",
27
+ "./adapters/pusher": "./dist/runtime/adapters/pusher/index.js",
28
+ "./adapters/pusher/web": "./dist/runtime/adapters/pusher/web.js",
29
+ "./adapters/pusher/node": "./dist/runtime/adapters/pusher/node.js",
30
+ "./adapters/ably": "./dist/runtime/adapters/ably/index.js",
31
+ "./adapters/ably/web": "./dist/runtime/adapters/ably/web.js",
32
+ "./adapters/ably/node": "./dist/runtime/adapters/ably/node.js"
26
33
  },
27
34
  "main": "./dist/module.mjs",
28
35
  "files": [
29
36
  "dist"
30
37
  ],
38
+ "peerDependencies": {
39
+ "ably": ">=2",
40
+ "pusher-js": ">=8"
41
+ },
42
+ "peerDependenciesMeta": {
43
+ "ably": {
44
+ "optional": true
45
+ },
46
+ "pusher-js": {
47
+ "optional": true
48
+ }
49
+ },
31
50
  "dependencies": {
32
51
  "@clack/prompts": "^0.11.0",
33
52
  "@nuxt/kit": "^4.2.2",
@@ -42,10 +61,12 @@
42
61
  "pkg-types": "^2.3.0",
43
62
  "std-env": "^3.10.0",
44
63
  "tinyexec": "^1.0.2",
45
- "ufo": "^1.6.1"
64
+ "ufo": "^1.6.1",
65
+ "unstorage": "^1.17.3",
66
+ "zod": "^4.1.13"
46
67
  },
47
68
  "devDependencies": {
48
- "@antfu/eslint-config": "^6.5.1",
69
+ "@antfu/eslint-config": "^6.6.1",
49
70
  "@arethetypeswrong/cli": "^0.18.2",
50
71
  "@nuxt/content": "^3.9.0",
51
72
  "@nuxt/devtools-ui-kit": "^3.1.1",
@@ -62,6 +83,7 @@
62
83
  "@unocss/preset-uno": "66.5.10",
63
84
  "@unocss/runtime": "66.5.10",
64
85
  "@vueuse/nuxt": "^14.1.0",
86
+ "ably": "^2.15.0",
65
87
  "better-sqlite3": "^12.5.0",
66
88
  "bumpp": "^10.3.2",
67
89
  "eslint": "^9.39.1",
@@ -72,10 +94,10 @@
72
94
  "ioredis": "^5.8.2",
73
95
  "nuxt": "^4.2.2",
74
96
  "playwright-core": "^1.57.0",
97
+ "pusher-js": "^8.4.0",
75
98
  "tsx": "^4.21.0",
76
99
  "typescript": "^5.9.3",
77
100
  "unocss": "66.5.10",
78
- "unstorage": "^1.17.3",
79
101
  "vitest": "^4.0.15",
80
102
  "vue": "^3.5.25",
81
103
  "vue-router": "^4.6.3",