nuxt-skew-protection 1.6.1 → 2.0.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 (61) hide show
  1. package/README.md +13 -12
  2. package/dist/module.d.mts +2 -1
  3. package/dist/module.json +2 -2
  4. package/dist/module.mjs +54 -34
  5. package/dist/runtime/adapters/ably/index.d.ts +1 -1
  6. package/dist/runtime/adapters/ably/index.js +3 -3
  7. package/dist/runtime/adapters/ably/types.d.ts +9 -9
  8. package/dist/runtime/adapters/ably/types.js +8 -8
  9. package/dist/runtime/adapters/index.d.ts +1 -1
  10. package/dist/runtime/adapters/pusher/index.d.ts +1 -1
  11. package/dist/runtime/adapters/pusher/index.js +3 -3
  12. package/dist/runtime/adapters/pusher/types.d.ts +10 -10
  13. package/dist/runtime/adapters/pusher/types.js +13 -12
  14. package/dist/runtime/adapters/types.d.ts +38 -3
  15. package/dist/runtime/adapters/types.js +42 -4
  16. package/dist/runtime/app/components/SkewNotification.d.vue.ts +2 -2
  17. package/dist/runtime/app/components/SkewNotification.vue.d.ts +2 -2
  18. package/dist/runtime/app/composables/useSkewProtection.js +39 -6
  19. package/dist/runtime/app/index.d.ts +6 -0
  20. package/dist/runtime/app/index.js +3 -0
  21. package/dist/runtime/app/plugins/multi-tab.client.js +10 -4
  22. package/dist/runtime/app/plugins/sw-track-user-modules.client.js +19 -7
  23. package/dist/runtime/app/types.d.ts +1 -0
  24. package/dist/runtime/app/utils/bot-detection-none.d.ts +1 -0
  25. package/dist/runtime/app/utils/bot-detection-none.js +3 -0
  26. package/dist/runtime/app/utils/bot-detection-robots.d.ts +1 -0
  27. package/dist/runtime/app/utils/bot-detection-robots.js +4 -0
  28. package/dist/runtime/app/utils/create-skew-connection.js +133 -12
  29. package/dist/runtime/server/imports/cookie.js +1 -1
  30. package/dist/runtime/server/imports/getRuntimeConfigSkewProtection.d.ts +3 -4
  31. package/dist/runtime/server/imports/getRuntimeConfigSkewProtection.js +3 -3
  32. package/dist/runtime/server/imports/utils.js +2 -2
  33. package/dist/runtime/server/middleware/set-skew-protection-cookie.d.ts +1 -1
  34. package/dist/runtime/server/middleware/set-skew-protection-cookie.js +3 -4
  35. package/dist/runtime/server/middleware/vercel-skew.d.ts +1 -1
  36. package/dist/runtime/server/middleware/vercel-skew.js +3 -4
  37. package/dist/runtime/server/plugins/connection-tracking-cloudflare-durable.js +12 -4
  38. package/dist/runtime/server/plugins/html-cache-headers-nitro3.d.ts +2 -0
  39. package/dist/runtime/server/plugins/html-cache-headers-nitro3.js +29 -0
  40. package/dist/runtime/server/plugins/html-cache-headers.js +13 -3
  41. package/dist/runtime/server/routes/__skew/admin/stats.get.d.ts +1 -1
  42. package/dist/runtime/server/routes/__skew/admin/stats.get.js +6 -6
  43. package/dist/runtime/server/routes/__skew/health.get.d.ts +5 -1
  44. package/dist/runtime/server/routes/__skew/health.get.js +3 -4
  45. package/dist/runtime/server/routes/__skew/route.post.d.ts +3 -1
  46. package/dist/runtime/server/routes/__skew/route.post.js +1 -1
  47. package/dist/runtime/server/routes/__skew/sse.js +5 -3
  48. package/dist/runtime/server/routes/__skew/subscribe-stats.post.d.ts +3 -1
  49. package/dist/runtime/server/routes/__skew/subscribe-stats.post.js +2 -2
  50. package/dist/runtime/server/routes/__skew-devtools/debug-production.get.d.ts +15 -1
  51. package/dist/runtime/server/routes/__skew-devtools/debug-production.get.js +20 -4
  52. package/dist/runtime/server/routes/__skew-devtools/debug.get.d.ts +14 -1
  53. package/dist/runtime/server/routes/__skew-devtools/debug.get.js +4 -6
  54. package/dist/runtime/server/utils/site-config-installed.d.ts +2 -0
  55. package/dist/runtime/server/utils/site-config-installed.js +4 -0
  56. package/dist/runtime/server/utils/site-config-none.d.ts +2 -0
  57. package/dist/runtime/server/utils/site-config-none.js +3 -0
  58. package/dist/runtime/server/utils/vercel-cookie-path.d.ts +1 -2
  59. package/dist/runtime/server/utils/vercel-cookie-path.js +3 -1
  60. package/package.json +49 -36
  61. package/skills/nuxt-skew-protection/SKILL.md +40 -10
package/README.md CHANGED
@@ -1,15 +1,10 @@
1
- # Nuxt Skew Protection
1
+ <h1><a href="https://nuxtseo.com"><img src=".github/assets/icon.svg" width="40" height="40" alt="Nuxt SEO" align="top"></a> Nuxt Skew Protection</h1>
2
2
 
3
3
  [![npm version][npm-version-src]][npm-version-href]
4
4
  [![npm downloads][npm-downloads-src]][npm-downloads-href]
5
+ [![License][license-src]][license-href]
5
6
  [![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>
7
+ [![Skill repository on skilld.dev][skilld-src]][skilld-href]
13
8
 
14
9
  > Keep old build assets available and notify users when their app needs an update.
15
10
 
@@ -39,7 +34,7 @@ Nuxt Skew Protection keeps previous build assets available across deployments an
39
34
  Add `nuxt-skew-protection` to your project:
40
35
 
41
36
  ```bash
42
- npx nuxi@latest module add nuxt-skew-protection
37
+ npx nuxt module add nuxt-skew-protection
43
38
  ```
44
39
 
45
40
  > [!TIP]
@@ -62,11 +57,17 @@ npx nuxi@latest module add nuxt-skew-protection
62
57
  [MIT License](https://github.com/harlan-zw/nuxt-skew-protection/blob/main/LICENSE.md)
63
58
 
64
59
  <!-- Badges -->
65
- [npm-version-src]: https://img.shields.io/npm/v/nuxt-skew-protection/latest.svg?style=flat&colorA=18181B&colorB=28CF8D
60
+ [npm-version-src]: https://img.shields.io/npm/v/nuxt-skew-protection/latest.svg?style=flat&labelColor=16152b&color=00a63e
66
61
  [npm-version-href]: https://npmjs.com/package/nuxt-skew-protection
67
62
 
68
- [npm-downloads-src]: https://img.shields.io/npm/dm/nuxt-skew-protection.svg?style=flat&colorA=18181B&colorB=28CF8D
63
+ [npm-downloads-src]: https://img.shields.io/npm/dm/nuxt-skew-protection.svg?style=flat&labelColor=16152b&color=00a63e
69
64
  [npm-downloads-href]: https://npmjs.com/package/nuxt-skew-protection
70
65
 
71
- [nuxt-src]: https://img.shields.io/badge/Nuxt-18181B?logo=nuxt
66
+ [license-src]: https://img.shields.io/github/license/harlan-zw/nuxt-skew-protection.svg?style=flat&labelColor=16152b&color=00a63e
67
+ [license-href]: https://github.com/harlan-zw/nuxt-skew-protection/blob/main/LICENSE.md
68
+
69
+ [nuxt-src]: https://img.shields.io/badge/Nuxt-16152b?logo=nuxt&style=flat
72
70
  [nuxt-href]: https://nuxt.com
71
+
72
+ [skilld-src]: https://skilld.dev/b/harlan-zw/nuxt-skew-protection?style=flat&labelColor=16152b&color=00a63e&logoColor=ffffff
73
+ [skilld-href]: https://skilld.dev/gh/harlan-zw/nuxt-skew-protection
package/dist/module.d.mts CHANGED
@@ -26,7 +26,7 @@ interface ModuleOptions {
26
26
  * - 'sse': Use Server-Sent Events for real-time updates
27
27
  * - 'ws': Use WebSocket (requires cloudflare-durable preset or experimental.websocket)
28
28
  * - SkewAdapter: Third-party WebSocket provider (Pusher, Ably)
29
- * @default Static: 'polling', Node: 'sse', Cloudflare: 'ws'
29
+ * @default 'polling'
30
30
  */
31
31
  updateStrategy?: 'polling' | 'sse' | 'ws' | SkewAdapter;
32
32
  /**
@@ -106,6 +106,7 @@ interface ModuleOptions {
106
106
  /**
107
107
  * Coordinate version updates across browser tabs via BroadcastChannel.
108
108
  * When enabled, a version update detected in one tab notifies all others.
109
+ * Visible tabs share one push connection when connection tracking is disabled.
109
110
  * @default true
110
111
  */
111
112
  multiTab?: boolean;
package/dist/module.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "nuxt-skew-protection",
3
3
  "compatibility": {
4
- "nuxt": ">=4.0.0"
4
+ "nuxt": "^4.6.0 || ^5.0.0-0"
5
5
  },
6
6
  "configKey": "skewProtection",
7
- "version": "1.6.1",
7
+ "version": "2.0.0",
8
8
  "builder": {
9
9
  "@nuxt/module-builder": "1.0.3",
10
10
  "unbuild": "3.6.1"
package/dist/module.mjs CHANGED
@@ -1,12 +1,11 @@
1
1
  import { existsSync, promises } from 'node:fs';
2
- import { useLogger, useNuxt, defineNuxtModule, createResolver, hasNuxtModule, addTypeTemplate, addComponent, addImports, addServerHandler, addPlugin, tryResolveModule, resolvePath, addTemplate } from '@nuxt/kit';
2
+ import { mkdtemp, writeFile, rm, readFile } from 'node:fs/promises';
3
+ import { useLogger, useNuxt, defineNuxtModule, createResolver, getNitroVersion, hasNuxtModule, addTypeTemplate, addComponent, addImports, addNitroPlugin, addServerHandler, addPlugin, tryResolveModule, resolvePath, addTemplate } from '@nuxt/kit';
3
4
  import { colors } from 'consola/utils';
4
- import { setupNitroRuntimeCompatibility, resolveNitroPreset, renderNitroTypeAugmentations, isNuxtGenerate } from 'nuxtseo-shared/kit';
5
- import { readPackageJSON } from 'pkg-types';
5
+ import { setupNitroRuntimeCompatibility, setupRuntimeAliases, resolveNitroPreset, renderNitroTypeAugmentations, isNuxtGenerate } from 'nuxtseo-shared/kit';
6
6
  import { cachingRouteRules, skewCacheCeilingSeconds, htmlCacheCapability } from '../dist/runtime/server/utils/html-cache-policy.js';
7
7
  import { join } from 'node:path';
8
8
  import { spawn } from 'node:child_process';
9
- import { mkdtemp, writeFile, rm } from 'node:fs/promises';
10
9
  import { tmpdir } from 'node:os';
11
10
  import { defineDriver, createStorage } from 'unstorage';
12
11
  import { isSkewAdapter } from '../dist/runtime/adapters/index.js';
@@ -33,14 +32,8 @@ function resolveBundleAssets(options, env = process.env) {
33
32
  bundleAssets: true
34
33
  };
35
34
  }
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";
35
+ function resolveDefaultUpdateStrategy(_input) {
36
+ return "polling";
44
37
  }
45
38
 
46
39
  const SKEW_SEGMENT = "__skew";
@@ -868,19 +861,21 @@ const module$1 = defineNuxtModule({
868
861
  meta: {
869
862
  name: "nuxt-skew-protection",
870
863
  compatibility: {
871
- nuxt: ">=4.0.0"
864
+ nuxt: "^4.6.0 || ^5.0.0-0"
872
865
  },
873
866
  configKey: "skewProtection"
874
867
  },
875
868
  moduleDependencies: {
876
869
  "@nuxtjs/robots": {
877
- version: ">=5.6.7"
870
+ version: ">=7.0.0",
871
+ optional: true
878
872
  },
879
873
  "nuxt-site-config": {
880
- version: ">=4.0"
874
+ version: ">=5.0.0",
875
+ optional: true
881
876
  },
882
877
  "nuxtseo-shared": {
883
- version: ">=0.8.0"
878
+ version: ">=6.0.0"
884
879
  }
885
880
  },
886
881
  defaults: {
@@ -896,7 +891,7 @@ const module$1 = defineNuxtModule({
896
891
  // 7 days
897
892
  },
898
893
  storage: {
899
- driver: "fs",
894
+ driver: "fs-lite",
900
895
  base: "node_modules/.cache/nuxt-seo/skew-protection"
901
896
  },
902
897
  debug: false,
@@ -905,13 +900,35 @@ const module$1 = defineNuxtModule({
905
900
  },
906
901
  async setup(options, nuxt) {
907
902
  const resolver = createResolver(import.meta.url);
908
- const { version } = await readPackageJSON(resolver.resolve("../package.json"));
903
+ const { version } = JSON.parse(await readFile(resolver.resolve("../package.json"), "utf8"));
909
904
  logger.level = options.debug || nuxt.options.debug ? 4 : 3;
910
905
  if (options.enabled === false) {
911
906
  logger.debug("The module is disabled, skipping setup.");
912
907
  return;
913
908
  }
909
+ if (nuxt.options.experimental.appManifest === false)
910
+ throw new Error("nuxt-skew-protection requires experimental.appManifest. Enable it or disable the module.");
914
911
  const nitroCompatibility = setupNitroRuntimeCompatibility(nuxt);
912
+ setupRuntimeAliases({ namespace: "#skew-protection", app: resolver.resolve("./runtime/app"), server: resolver.resolve("./runtime/server") }, nuxt);
913
+ nuxt.hook("nitro:config", (nitroConfig) => {
914
+ if (getNitroVersion(nuxt) === 3) {
915
+ const nativeConfig = nitroConfig;
916
+ if (nativeConfig.noExternals !== true)
917
+ nativeConfig.noExternals = [...nativeConfig.noExternals || [], "nuxt-skew-protection"];
918
+ } else {
919
+ const externals = nitroConfig.externals ||= {};
920
+ externals.inline ||= [];
921
+ externals.inline.push(resolver.resolve("./runtime"));
922
+ }
923
+ });
924
+ nuxt.options.alias["#skew-protection/bot-detection"] = resolver.resolve("./runtime/app/utils/bot-detection-none");
925
+ nuxt.options.alias["#skew-protection/site-config"] = resolver.resolve("./runtime/server/utils/site-config-none");
926
+ nuxt.hook("modules:done", () => {
927
+ if (hasNuxtModule("@nuxtjs/robots"))
928
+ nuxt.options.alias["#skew-protection/bot-detection"] = resolver.resolve("./runtime/app/utils/bot-detection-robots");
929
+ if (hasNuxtModule("nuxt-site-config"))
930
+ nuxt.options.alias["#skew-protection/site-config"] = resolver.resolve("./runtime/server/utils/site-config-installed");
931
+ });
915
932
  const explicitBasePath = options.basePath;
916
933
  const basePathExplicit = !!explicitBasePath;
917
934
  const basePath = resolveBasePath({ basePath: explicitBasePath, app: nuxt.options.app });
@@ -1045,23 +1062,26 @@ skewVersion?: string`,
1045
1062
  route?: string
1046
1063
  ip?: string
1047
1064
  send: (data: unknown) => void
1065
+ peer?: unknown
1048
1066
  }) => void
1049
- 'skew:connection:route-update': (payload: { id: string, route: string }) => void
1050
- 'skew:connection:close': (payload: { id: string }) => void
1067
+ 'skew:connection:route-update': (payload: { id: string, route: string, peer?: unknown }) => void
1068
+ 'skew:connection:close': (payload: { id: string, peer?: unknown }) => void
1051
1069
  /** event is an HTTP event for SSE, or headers for WebSocket connections. */
1052
- 'skew:subscribe-stats': (payload: { id: string, event?: ${nitroCompatibility.eventType} | { headers?: Headers } }) => void
1070
+ 'skew:subscribe-stats': (payload: { id: string, peer?: unknown, event?: RequestEvent | ${nitroCompatibility.eventType} | { headers?: Headers } }) => void
1053
1071
  /** event is an HTTP event for SSE, or headers for WebSocket connections. */
1054
- 'skew:authorize-stats': (payload: { event?: ${nitroCompatibility.eventType} | { headers?: Headers }, authorize: () => void }) => void
1072
+ 'skew:authorize-stats': (payload: { id?: string, event?: RequestEvent | ${nitroCompatibility.eventType} | { headers?: Headers }, authorize: () => void }) => void
1055
1073
  'skew:stats': (callback: (stats: { total: number, versions: Record<string, number>, routes: Record<string, number> }) => void) => void`
1056
1074
  });
1057
1075
  return `// Generated by nuxt-skew-protection
1058
1076
 
1077
+ import type { RequestEvent } from 'nuxt/server'
1078
+
1059
1079
  ${nitroTypes}
1060
1080
 
1061
1081
  export {}
1062
1082
  `;
1063
1083
  }
1064
- }, { nitro: true });
1084
+ }, { nuxt: true, nitro: true });
1065
1085
  addComponent({
1066
1086
  name: "SkewNotification",
1067
1087
  filePath: resolver.resolve(`./runtime/app/components/SkewNotification.vue`)
@@ -1075,10 +1095,8 @@ export {}
1075
1095
  name: "useActiveConnections",
1076
1096
  from: resolver.resolve("./runtime/app/composables/useActiveConnections")
1077
1097
  });
1078
- nuxt.options.nitro = nuxt.options.nitro || {};
1079
- nuxt.options.nitro.plugins = nuxt.options.nitro.plugins || [];
1080
1098
  const connectionTrackingPlugin = nitroPreset === "cloudflare-durable" ? "./runtime/server/plugins/connection-tracking-cloudflare-durable" : "./runtime/server/plugins/connection-tracking";
1081
- nuxt.options.nitro.plugins.push(resolver.resolve(connectionTrackingPlugin));
1099
+ addNitroPlugin(resolver.resolve(connectionTrackingPlugin));
1082
1100
  }
1083
1101
  nuxt.options.alias["#skew-protection"] = resolver.resolve("./runtime");
1084
1102
  nuxt.options.alias["nuxt-skew-protection/server"] = resolver.resolve("./runtime/server");
@@ -1129,9 +1147,7 @@ export {}
1129
1147
  logger.warn(`${caching.length} route rule${caching.length > 1 ? "s" : ""} ask a shared cache to store HTML. That cannot work on Vercel. Vercel skew protection sets a \`__vdpl\` cookie on every document. Shared caches skip any response that sets a cookie.`);
1130
1148
  }
1131
1149
  } else {
1132
- nuxt.options.nitro = nuxt.options.nitro || {};
1133
- nuxt.options.nitro.plugins = nuxt.options.nitro.plugins || [];
1134
- nuxt.options.nitro.plugins.push(resolver.resolve("./runtime/server/plugins/html-cache-headers"));
1150
+ addNitroPlugin(resolver.resolve(getNitroVersion(nuxt) === 3 ? "./runtime/server/plugins/html-cache-headers-nitro3" : "./runtime/server/plugins/html-cache-headers"));
1135
1151
  if (caching.length) {
1136
1152
  const ceiling = skewCacheCeilingSeconds(options.retentionDays || 7);
1137
1153
  for (const { route, seconds, source, fromMaxAgeAlone } of caching) {
@@ -1205,7 +1221,7 @@ export {}
1205
1221
  } else if (options.updateStrategy === "sse") {
1206
1222
  resolvedStrategy = "sse";
1207
1223
  } else if (!options.updateStrategy) {
1208
- resolvedStrategy = resolveDefaultUpdateStrategy({ isStatic, nitroPreset });
1224
+ resolvedStrategy = resolveDefaultUpdateStrategy();
1209
1225
  }
1210
1226
  if (isStatic && resolvedStrategy !== "polling" && resolvedStrategy !== "adapter") {
1211
1227
  logger.warn(`Strategy "${resolvedStrategy}" requires a server but static generation detected. Falling back to polling.`);
@@ -1241,9 +1257,13 @@ export {}
1241
1257
  handler: resolver.resolve("./runtime/server/routes/__skew/admin/stats.get")
1242
1258
  });
1243
1259
  }
1244
- addPlugin({
1245
- src: resolver.resolve("./runtime/app/plugins/sw-track-user-modules.client"),
1246
- mode: "client"
1260
+ nuxt.hook("modules:done", () => {
1261
+ if (hasNuxtModule("@vite-pwa/nuxt") || hasNuxtModule("@nuxtjs/pwa"))
1262
+ return;
1263
+ addPlugin({
1264
+ src: resolver.resolve("./runtime/app/plugins/sw-track-user-modules.client"),
1265
+ mode: "client"
1266
+ });
1247
1267
  });
1248
1268
  if (options.multiTab !== false || options.reloadStrategy && options.reloadStrategy !== "prompt") {
1249
1269
  addPlugin({
@@ -1283,7 +1303,7 @@ export {}
1283
1303
  const daysSince = Math.floor((Date.now() - oldestTimestamp) / (1e3 * 60 * 60 * 24));
1284
1304
  const timeInfo = daysSince > 0 ? `${daysSince} day${daysSince > 1 ? "s" : ""} ago` : "today";
1285
1305
  const storageInfo = options.storage.base ? `${colors.green(options.storage.driver)} ${colors.gray(`(${options.storage.base})`)}` : colors.green(options.storage.driver);
1286
- if (totalReleases === 1 && options.storage.driver === "fs") {
1306
+ if (totalReleases === 1 && ["fs", "fs-lite"].includes(options.storage.driver)) {
1287
1307
  logger.info("Initialized local storage with its first release.");
1288
1308
  } else if (totalReleases === 1) {
1289
1309
  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`);
@@ -1,5 +1,5 @@
1
1
  import type { SkewAdapterFactory } from '../types.js';
2
2
  import type { AblyAdapterConfig, AblyClientConfig } from './types.js';
3
3
  export type { AblyAdapterConfig } from './types.js';
4
- export { ablyConfigSchema } from './types.js';
4
+ export { parseAblyConfig } from './types.js';
5
5
  export declare const ablyAdapter: SkewAdapterFactory<AblyAdapterConfig, AblyClientConfig>;
@@ -1,14 +1,14 @@
1
1
  import { fileURLToPath } from "node:url";
2
2
  import { defineAdapter } from "../types.js";
3
- import { ablyConfigSchema } from "./types.js";
4
- export { ablyConfigSchema } from "./types.js";
3
+ import { parseAblyConfig } from "./types.js";
4
+ export { parseAblyConfig } from "./types.js";
5
5
  export const ablyAdapter = defineAdapter({
6
6
  name: "ably",
7
7
  web: fileURLToPath(new URL("./web", import.meta.url)),
8
8
  dependencies: ["ably"],
9
9
  // Lazy, so loading nuxt.config does not load the server SDK.
10
10
  broadcast: (config, version) => import("./node.js").then((m) => m.broadcast(config, version)),
11
- schema: ablyConfigSchema,
11
+ schema: parseAblyConfig,
12
12
  toPublicConfig: ({ authUrl, clientId, channel, event }) => ({
13
13
  authUrl,
14
14
  ...clientId ? { clientId } : {},
@@ -1,10 +1,10 @@
1
- import { z } from 'zod';
2
- export declare const ablyConfigSchema: z.ZodObject<{
3
- key: z.ZodString;
4
- authUrl: z.ZodString;
5
- clientId: z.ZodOptional<z.ZodString>;
6
- channel: z.ZodOptional<z.ZodString>;
7
- event: z.ZodOptional<z.ZodString>;
8
- }, z.core.$strip>;
9
- export type AblyAdapterConfig = z.infer<typeof ablyConfigSchema>;
1
+ import type { AdapterConfigResult } from '../types.js';
2
+ export interface AblyAdapterConfig {
3
+ key: string;
4
+ authUrl: string;
5
+ clientId?: string;
6
+ channel?: string;
7
+ event?: string;
8
+ }
10
9
  export type AblyClientConfig = Pick<AblyAdapterConfig, 'authUrl' | 'clientId' | 'channel' | 'event'>;
10
+ export declare function parseAblyConfig(input: unknown): AdapterConfigResult<AblyAdapterConfig>;
@@ -1,8 +1,8 @@
1
- import { z } from "zod";
2
- export const ablyConfigSchema = z.object({
3
- key: z.string().min(1, "Ably key is required"),
4
- authUrl: z.string().min(1, "Ably authUrl is required"),
5
- clientId: z.string().optional(),
6
- channel: z.string().optional(),
7
- event: z.string().optional()
8
- });
1
+ import { parseStringConfig } from "../types.js";
2
+ export function parseAblyConfig(input) {
3
+ return parseStringConfig(
4
+ input,
5
+ { key: "Ably key is required", authUrl: "Ably authUrl is required" },
6
+ ["clientId", "channel", "event"]
7
+ );
8
+ }
@@ -2,5 +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 { AdapterConfigResult, BroadcastFn, DefineAdapterOptions, SkewAdapter, SkewAdapterFactory, SubscribeFn } from './types.js';
5
+ export type { AdapterConfigParser, AdapterConfigResult, AdapterConfigSchema, BroadcastFn, DefineAdapterOptions, SkewAdapter, SkewAdapterFactory, StandardSchemaV1, SubscribeFn } from './types.js';
6
6
  export { defineAdapter, defineNodeBroadcast, defineWebSubscribe } from './types.js';
@@ -1,5 +1,5 @@
1
1
  import type { SkewAdapterFactory } from '../types.js';
2
2
  import type { PusherAdapterConfig, PusherClientConfig } from './types.js';
3
3
  export type { PusherAdapterConfig } from './types.js';
4
- export { pusherConfigSchema } from './types.js';
4
+ export { parsePusherConfig } from './types.js';
5
5
  export declare const pusherAdapter: SkewAdapterFactory<PusherAdapterConfig, PusherClientConfig>;
@@ -1,14 +1,14 @@
1
1
  import { fileURLToPath } from "node:url";
2
2
  import { defineAdapter } from "../types.js";
3
- import { pusherConfigSchema } from "./types.js";
4
- export { pusherConfigSchema } from "./types.js";
3
+ import { parsePusherConfig } from "./types.js";
4
+ export { parsePusherConfig } from "./types.js";
5
5
  export const pusherAdapter = defineAdapter({
6
6
  name: "pusher",
7
7
  web: fileURLToPath(new URL("./web", import.meta.url)),
8
8
  dependencies: ["pusher-js"],
9
9
  // Lazy, so loading nuxt.config does not load the server SDK.
10
10
  broadcast: (config, version) => import("./node.js").then((m) => m.broadcast(config, version)),
11
- schema: pusherConfigSchema,
11
+ schema: parsePusherConfig,
12
12
  toPublicConfig: ({ key, cluster, channel, event }) => ({
13
13
  key,
14
14
  cluster,
@@ -1,11 +1,11 @@
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>;
1
+ import type { AdapterConfigResult } from '../types.js';
2
+ export interface PusherAdapterConfig {
3
+ key: string;
4
+ cluster: string;
5
+ appId: string;
6
+ secret: string;
7
+ channel?: string;
8
+ event?: string;
9
+ }
11
10
  export type PusherClientConfig = Pick<PusherAdapterConfig, 'key' | 'cluster' | 'channel' | 'event'>;
11
+ export declare function parsePusherConfig(input: unknown): AdapterConfigResult<PusherAdapterConfig>;
@@ -1,12 +1,13 @@
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
- });
1
+ import { parseStringConfig } from "../types.js";
2
+ export function parsePusherConfig(input) {
3
+ return parseStringConfig(
4
+ input,
5
+ {
6
+ key: "Pusher key is required",
7
+ cluster: "Pusher cluster is required",
8
+ appId: "Pusher appId is required",
9
+ secret: "Pusher secret is required"
10
+ },
11
+ ["channel", "event"]
12
+ );
13
+ }
@@ -1,4 +1,3 @@
1
- import type { z } from 'zod';
2
1
  export type AdapterConfigResult<TConfig> = {
3
2
  _tag: 'Ok';
4
3
  config: TConfig;
@@ -6,6 +5,36 @@ export type AdapterConfigResult<TConfig> = {
6
5
  _tag: 'Err';
7
6
  issues: string[];
8
7
  };
8
+ export type AdapterConfigParser<TConfig> = (config: unknown) => AdapterConfigResult<TConfig>;
9
+ type StandardSchemaResult<TOutput> = {
10
+ readonly value: TOutput;
11
+ readonly issues?: undefined;
12
+ } | {
13
+ readonly issues: ReadonlyArray<{
14
+ readonly message: string;
15
+ readonly path?: ReadonlyArray<PropertyKey | {
16
+ readonly key: PropertyKey;
17
+ }> | undefined;
18
+ }>;
19
+ };
20
+ /**
21
+ * The part of the Standard Schema interface (https://standardschema.dev) that
22
+ * `defineAdapter` reads. zod, Valibot and ArkType schemas implement it, so the
23
+ * module validates adapter config without a dependency on any of them.
24
+ */
25
+ export interface StandardSchemaV1<TOutput = unknown> {
26
+ readonly '~standard': {
27
+ readonly version: 1;
28
+ readonly vendor: string;
29
+ readonly validate: (value: unknown) => StandardSchemaResult<TOutput> | Promise<StandardSchemaResult<TOutput>>;
30
+ readonly types?: {
31
+ readonly input: unknown;
32
+ readonly output: TOutput;
33
+ } | undefined;
34
+ };
35
+ }
36
+ /** A parse function, or a Standard Schema such as a zod object. */
37
+ export type AdapterConfigSchema<TConfig> = AdapterConfigParser<TConfig> | StandardSchemaV1<TConfig>;
9
38
  export type BroadcastFn<T> = (config: T, version: string) => Promise<void>;
10
39
  export type SubscribeFn<T> = (config: T, onMessage: (msg: {
11
40
  version: string;
@@ -19,7 +48,7 @@ export interface SkewAdapter<TConfig = unknown, TPublicConfig extends Record<str
19
48
  name: string;
20
49
  config: TConfig;
21
50
  /** Validate `config` at build time. */
22
- parseConfig: (config: unknown) => AdapterConfigResult<TConfig>;
51
+ parseConfig: AdapterConfigParser<TConfig>;
23
52
  /** The part of `config` that ships to the browser. Never include secrets. */
24
53
  toPublicConfig: (config: TConfig) => TPublicConfig;
25
54
  /**
@@ -35,12 +64,18 @@ export interface SkewAdapter<TConfig = unknown, TPublicConfig extends Record<str
35
64
  export type SkewAdapterFactory<TConfig, TPublicConfig extends Record<string, unknown> = Record<string, unknown>> = (config: TConfig) => SkewAdapter<TConfig, TPublicConfig>;
36
65
  export interface DefineAdapterOptions<TConfig, TPublicConfig extends Record<string, unknown>> {
37
66
  name: string;
38
- schema: z.ZodType<TConfig>;
67
+ schema: AdapterConfigSchema<TConfig>;
39
68
  toPublicConfig: (config: TConfig) => TPublicConfig;
40
69
  web: string;
41
70
  dependencies?: string[];
42
71
  broadcast: BroadcastFn<TConfig>;
43
72
  }
44
73
  export declare function defineAdapter<TConfig, TPublicConfig extends Record<string, unknown>>(options: DefineAdapterOptions<TConfig, TPublicConfig>): SkewAdapterFactory<TConfig, TPublicConfig>;
74
+ /**
75
+ * Parses an object whose fields are all strings: each `required` key maps to
76
+ * its error message, and `optional` keys may be absent. Unknown keys are dropped.
77
+ */
78
+ export declare function parseStringConfig<TRequired extends string, TOptional extends string>(input: unknown, required: Record<TRequired, string>, optional: readonly TOptional[]): AdapterConfigResult<Record<TRequired, string> & Partial<Record<TOptional, string>>>;
45
79
  export declare const defineNodeBroadcast: <T>(broadcast: BroadcastFn<T>) => BroadcastFn<T>;
46
80
  export declare const defineWebSubscribe: <T>(subscribe: SubscribeFn<T>) => SubscribeFn<T>;
81
+ export {};
@@ -1,8 +1,24 @@
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}`) };
1
+ function toConfigParser(schema) {
2
+ if (!("~standard" in schema))
3
+ return schema;
4
+ return (config) => {
5
+ const result = schema["~standard"].validate(config);
6
+ if (result instanceof Promise)
7
+ return { _tag: "Err", issues: ["config: async schemas are not supported, use a synchronous schema"] };
8
+ if (result.issues) {
9
+ return {
10
+ _tag: "Err",
11
+ issues: result.issues.map(({ message, path }) => {
12
+ const key = path?.map((segment) => String(typeof segment === "object" ? segment.key : segment)).join(".");
13
+ return `${key || "config"}: ${message}`;
14
+ })
15
+ };
16
+ }
17
+ return { _tag: "Ok", config: result.value };
5
18
  };
19
+ }
20
+ export function defineAdapter(options) {
21
+ const parseConfig = toConfigParser(options.schema);
6
22
  return (config) => ({
7
23
  name: options.name,
8
24
  config,
@@ -13,5 +29,27 @@ export function defineAdapter(options) {
13
29
  broadcast: options.broadcast
14
30
  });
15
31
  }
32
+ export function parseStringConfig(input, required, optional) {
33
+ if (typeof input !== "object" || input === null || Array.isArray(input))
34
+ return { _tag: "Err", issues: ["config: expected an object"] };
35
+ const fields = input;
36
+ const config = {};
37
+ const issues = [];
38
+ for (const [key, message] of Object.entries(required)) {
39
+ const value = fields[key];
40
+ if (typeof value === "string" && value.length > 0)
41
+ config[key] = value;
42
+ else
43
+ issues.push(`${key}: ${message}`);
44
+ }
45
+ for (const key of optional) {
46
+ const value = fields[key];
47
+ if (typeof value === "string")
48
+ config[key] = value;
49
+ else if (value !== void 0)
50
+ issues.push(`${key}: expected a string`);
51
+ }
52
+ return issues.length ? { _tag: "Err", issues } : { _tag: "Ok", config };
53
+ }
16
54
  export const defineNodeBroadcast = (broadcast) => broadcast;
17
55
  export const defineWebSubscribe = (subscribe) => subscribe;
@@ -7,7 +7,7 @@ interface Props {
7
7
  }
8
8
  declare function handleDismiss(): void;
9
9
  declare function handleReload(): Promise<void>;
10
- declare var __VLS_8: {
10
+ declare var __VLS_7: {
11
11
  version: any;
12
12
  isPrerendered: boolean;
13
13
  isCurrentChunksOutdated: boolean;
@@ -24,7 +24,7 @@ declare var __VLS_8: {
24
24
  } | null;
25
25
  };
26
26
  type __VLS_Slots = {} & {
27
- default?: (props: typeof __VLS_8) => any;
27
+ default?: (props: typeof __VLS_7) => any;
28
28
  };
29
29
  declare const __VLS_base: import("vue").DefineComponent<Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {
30
30
  dismiss: () => any;
@@ -7,7 +7,7 @@ interface Props {
7
7
  }
8
8
  declare function handleDismiss(): void;
9
9
  declare function handleReload(): Promise<void>;
10
- declare var __VLS_8: {
10
+ declare var __VLS_7: {
11
11
  version: any;
12
12
  isPrerendered: boolean;
13
13
  isCurrentChunksOutdated: boolean;
@@ -24,7 +24,7 @@ declare var __VLS_8: {
24
24
  } | null;
25
25
  };
26
26
  type __VLS_Slots = {} & {
27
- default?: (props: typeof __VLS_8) => any;
27
+ default?: (props: typeof __VLS_7) => any;
28
28
  };
29
29
  declare const __VLS_base: import("vue").DefineComponent<Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {
30
30
  dismiss: () => any;