@serwist/turbopack 9.5.7 → 9.5.8

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 (43) hide show
  1. package/dist/chunks/index.schema-RVDaKxz4.js +189 -0
  2. package/dist/chunks/index.schema-RVDaKxz4.js.map +1 -0
  3. package/dist/index.d.mts +96 -0
  4. package/dist/index.d.mts.map +1 -0
  5. package/dist/index.mjs +166 -0
  6. package/dist/index.mjs.map +1 -0
  7. package/dist/index.react.d.mts +42 -0
  8. package/dist/index.react.d.mts.map +1 -0
  9. package/dist/index.react.mjs +73 -0
  10. package/dist/index.react.mjs.map +1 -0
  11. package/dist/index.schema.d.mts +311 -0
  12. package/dist/index.schema.d.mts.map +1 -0
  13. package/dist/index.schema.mjs +2 -0
  14. package/dist/index.worker.d.mts +18 -0
  15. package/dist/index.worker.d.mts.map +1 -0
  16. package/dist/index.worker.mjs +227 -0
  17. package/dist/index.worker.mjs.map +1 -0
  18. package/package.json +31 -32
  19. package/dist/chunks/index.schema.js +0 -185
  20. package/dist/index.d.ts +0 -22
  21. package/dist/index.d.ts.map +0 -1
  22. package/dist/index.js +0 -190
  23. package/dist/index.react.d.ts +0 -25
  24. package/dist/index.react.d.ts.map +0 -1
  25. package/dist/index.react.js +0 -88
  26. package/dist/index.schema.d.ts +0 -301
  27. package/dist/index.schema.d.ts.map +0 -1
  28. package/dist/index.schema.js +0 -8
  29. package/dist/index.worker.d.ts +0 -14
  30. package/dist/index.worker.d.ts.map +0 -1
  31. package/dist/index.worker.js +0 -261
  32. package/dist/lib/constants.d.ts +0 -2
  33. package/dist/lib/constants.d.ts.map +0 -1
  34. package/dist/lib/context.d.ts +0 -7
  35. package/dist/lib/context.d.ts.map +0 -1
  36. package/dist/lib/index.d.ts +0 -3
  37. package/dist/lib/index.d.ts.map +0 -1
  38. package/dist/lib/logger.d.ts +0 -8
  39. package/dist/lib/logger.d.ts.map +0 -1
  40. package/dist/lib/utils.d.ts +0 -3
  41. package/dist/lib/utils.d.ts.map +0 -1
  42. package/dist/types.d.ts +0 -72
  43. package/dist/types.d.ts.map +0 -1
@@ -0,0 +1,189 @@
1
+ import { createRequire } from "node:module";
2
+ import path from "node:path";
3
+ import { assertType, basePartial, globPartial, injectPartial } from "@serwist/build/schema";
4
+ import { bold, green, red, white, yellow } from "kolorist";
5
+ import { PHASE_DEVELOPMENT_SERVER, PHASE_PRODUCTION_BUILD } from "next/constants.js";
6
+ import z$1 from "zod";
7
+ import semver from "semver";
8
+ //#region \0rolldown/runtime.js
9
+ var __defProp = Object.defineProperty;
10
+ var __exportAll = (all, no_symbols) => {
11
+ let target = {};
12
+ for (var name in all) __defProp(target, name, {
13
+ get: all[name],
14
+ enumerable: true
15
+ });
16
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
17
+ return target;
18
+ };
19
+ //#endregion
20
+ //#region src/lib/constants.ts
21
+ const SUPPORTED_ESBUILD_OPTIONS = [
22
+ "sourcemap",
23
+ "legalComments",
24
+ "sourceRoot",
25
+ "sourcesContent",
26
+ "format",
27
+ "globalName",
28
+ "target",
29
+ "supported",
30
+ "define",
31
+ "treeShaking",
32
+ "minify",
33
+ "mangleProps",
34
+ "reserveProps",
35
+ "mangleQuoted",
36
+ "mangleCache",
37
+ "drop",
38
+ "dropLabels",
39
+ "minifyWhitespace",
40
+ "minifyIdentifiers",
41
+ "minifySyntax",
42
+ "lineLimit",
43
+ "charset",
44
+ "ignoreAnnotations",
45
+ "jsx",
46
+ "jsxFactory",
47
+ "jsxFragment",
48
+ "jsxImportSource",
49
+ "jsxDev",
50
+ "jsxSideEffects",
51
+ "pure",
52
+ "keepNames",
53
+ "absPaths",
54
+ "color",
55
+ "logLevel",
56
+ "logLimit",
57
+ "logOverride",
58
+ "tsconfigRaw",
59
+ "bundle",
60
+ "splitting",
61
+ "preserveSymlinks",
62
+ "external",
63
+ "packages",
64
+ "alias",
65
+ "loader",
66
+ "resolveExtensions",
67
+ "mainFields",
68
+ "conditions",
69
+ "allowOverwrite",
70
+ "tsconfig",
71
+ "outExtension",
72
+ "publicPath",
73
+ "inject",
74
+ "banner",
75
+ "footer",
76
+ "plugins"
77
+ ];
78
+ //#endregion
79
+ //#region src/lib/logger.ts
80
+ var logger_exports = /* @__PURE__ */ __exportAll({
81
+ NEXT_VERSION: () => NEXT_VERSION,
82
+ error: () => error,
83
+ event: () => event,
84
+ info: () => info,
85
+ wait: () => wait,
86
+ warn: () => warn
87
+ });
88
+ const NEXT_VERSION = createRequire(import.meta.url)("next/package.json").version;
89
+ const LOGGING_SPACE_PREFIX = semver.gte(NEXT_VERSION, "16.0.0") ? "" : " ";
90
+ const prefixedLog = (prefixType, ...message) => {
91
+ let prefix;
92
+ let consoleMethod;
93
+ switch (prefixType) {
94
+ case "wait":
95
+ prefix = `${white(bold("○"))} (serwist)`;
96
+ consoleMethod = "log";
97
+ break;
98
+ case "error":
99
+ prefix = `${red(bold("X"))} (serwist)`;
100
+ consoleMethod = "error";
101
+ break;
102
+ case "warn":
103
+ prefix = `${yellow(bold("⚠"))} (serwist)`;
104
+ consoleMethod = "warn";
105
+ break;
106
+ case "info":
107
+ prefix = `${white(bold("○"))} (serwist)`;
108
+ consoleMethod = "log";
109
+ break;
110
+ case "event":
111
+ prefix = `${green(bold("✓"))} (serwist)`;
112
+ consoleMethod = "log";
113
+ break;
114
+ }
115
+ if ((message[0] === "" || message[0] === void 0) && message.length === 1) message.shift();
116
+ if (message.length === 0) console[consoleMethod]("");
117
+ else console[consoleMethod](`${LOGGING_SPACE_PREFIX}${prefix}`, ...message);
118
+ };
119
+ const wait = (...message) => prefixedLog("wait", ...message);
120
+ const error = (...message) => prefixedLog("error", ...message);
121
+ const warn = (...message) => prefixedLog("warn", ...message);
122
+ const info = (...message) => prefixedLog("info", ...message);
123
+ const event = (...message) => prefixedLog("event", ...message);
124
+ //#endregion
125
+ //#region src/lib/utils.ts
126
+ const loadNextConfig = async (cwd, isDev) => {
127
+ const nextPhase = isDev ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_BUILD;
128
+ // webpackIgnore is only supported by Next.js 15 and above, but it is necessary
129
+ const nextConfig = await import(
130
+ /* webpackIgnore: true */
131
+ "next/dist/server/config.js"
132
+ );
133
+ return (typeof nextConfig.default === "function" ? nextConfig.default : nextConfig.default.default)(nextPhase, cwd, { silent: false });
134
+ };
135
+ const generateGlobPatterns = (distDir) => [`${distDir}static/**/*.{js,css,html,ico,apng,png,avif,jpg,jpeg,jfif,pjpeg,pjp,gif,svg,webp,json,webmanifest}`, "public/**/*"];
136
+ //#endregion
137
+ //#region src/index.schema.ts
138
+ const turboPartial = z$1.strictObject({
139
+ cwd: z$1.string().prefault(process.cwd()),
140
+ nextConfig: z$1.object({
141
+ assetPrefix: z$1.string().optional(),
142
+ basePath: z$1.string().optional(),
143
+ distDir: z$1.string().optional()
144
+ }).optional(),
145
+ useNativeEsbuild: z$1.boolean().prefault(process.platform === "win32"),
146
+ rebuildOnChange: z$1.boolean().prefault(true),
147
+ esbuildOptions: z$1.partialRecord(z$1.literal(SUPPORTED_ESBUILD_OPTIONS), z$1.any()).prefault({})
148
+ });
149
+ const injectManifestOptions = z$1.strictObject({
150
+ ...basePartial.shape,
151
+ ...globPartial.shape,
152
+ ...injectPartial.shape,
153
+ ...turboPartial.shape,
154
+ globPatterns: z$1.array(z$1.string()).optional(),
155
+ globDirectory: z$1.string().optional()
156
+ }).omit({ disablePrecacheManifest: true }).transform(async (input) => {
157
+ // webpackIgnore is only supported by Next.js 15 and above, but it is necessary
158
+ const nextConfig = semver.gte(NEXT_VERSION, "15.0.0") ? {
159
+ ...await loadNextConfig(input.cwd, process.env.NODE_ENV === "development"),
160
+ ...input.nextConfig
161
+ } : {
162
+ distDir: input.nextConfig?.distDir ?? ".next",
163
+ basePath: input.nextConfig?.basePath ?? "/",
164
+ assetPrefix: input.nextConfig?.assetPrefix ?? input.nextConfig?.basePath ?? ""
165
+ };
166
+ let distDir = nextConfig.distDir;
167
+ if (distDir[0] === "/") distDir = distDir.slice(1);
168
+ if (distDir[distDir.length - 1] !== "/") distDir += "/";
169
+ return {
170
+ ...input,
171
+ swSrc: path.isAbsolute(input.swSrc) ? input.swSrc : path.join(input.cwd, input.swSrc),
172
+ globPatterns: input.globPatterns ?? generateGlobPatterns(distDir),
173
+ globDirectory: input.globDirectory ?? input.cwd,
174
+ dontCacheBustURLsMatching: input.dontCacheBustURLsMatching ?? new RegExp(`^${distDir}static/`),
175
+ nextConfig: {
176
+ ...nextConfig,
177
+ distDir,
178
+ basePath: nextConfig.basePath || "/"
179
+ }
180
+ };
181
+ });
182
+ assertType();
183
+ assertType();
184
+ assertType();
185
+ assertType();
186
+ //#endregion
187
+ export { turboPartial as n, logger_exports as r, injectManifestOptions as t };
188
+
189
+ //# sourceMappingURL=index.schema-RVDaKxz4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.schema-RVDaKxz4.js","names":["z"],"sources":["../../src/lib/constants.ts","../../src/lib/logger.ts","../../src/lib/utils.ts","../../src/index.schema.ts"],"sourcesContent":["import type { BuildOptions } from \"esbuild-wasm\";\n\nexport const SUPPORTED_ESBUILD_OPTIONS = [\n // CommonOptions\n \"sourcemap\",\n \"legalComments\",\n \"sourceRoot\",\n \"sourcesContent\",\n \"format\",\n \"globalName\",\n \"target\",\n \"supported\",\n \"define\",\n \"treeShaking\",\n \"minify\",\n \"mangleProps\",\n \"reserveProps\",\n \"mangleQuoted\",\n \"mangleCache\",\n \"drop\",\n \"dropLabels\",\n \"minifyWhitespace\",\n \"minifyIdentifiers\",\n \"minifySyntax\",\n \"lineLimit\",\n \"charset\",\n \"ignoreAnnotations\",\n \"jsx\",\n \"jsxFactory\",\n \"jsxFragment\",\n \"jsxImportSource\",\n \"jsxDev\",\n \"jsxSideEffects\",\n \"pure\",\n \"keepNames\",\n \"absPaths\",\n \"color\",\n \"logLevel\",\n \"logLimit\",\n \"logOverride\",\n \"tsconfigRaw\",\n // BuildOptions\n \"bundle\",\n \"splitting\",\n \"preserveSymlinks\",\n \"external\",\n \"packages\",\n \"alias\",\n \"loader\",\n \"resolveExtensions\",\n \"mainFields\",\n \"conditions\",\n \"allowOverwrite\",\n \"tsconfig\",\n \"outExtension\",\n \"publicPath\",\n \"inject\",\n \"banner\",\n \"footer\",\n \"plugins\",\n] as const satisfies readonly (keyof BuildOptions)[];\n","import { createRequire } from \"node:module\";\nimport { bold, green, red, white, yellow } from \"kolorist\";\nimport semver from \"semver\";\n\nconst require = createRequire(import.meta.url);\n\nexport const NEXT_VERSION = require(\"next/package.json\").version as string;\n\nconst LOGGING_SPACE_PREFIX = semver.gte(NEXT_VERSION, \"16.0.0\") ? \"\" : \" \";\n\nexport type LoggingMethods = \"wait\" | \"error\" | \"warn\" | \"info\" | \"event\";\n\nconst prefixedLog = (prefixType: LoggingMethods, ...message: any[]) => {\n let prefix: string;\n let consoleMethod: keyof Console;\n\n switch (prefixType) {\n case \"wait\":\n prefix = `${white(bold(\"○\"))} (serwist)`;\n consoleMethod = \"log\";\n break;\n case \"error\":\n prefix = `${red(bold(\"X\"))} (serwist)`;\n consoleMethod = \"error\";\n break;\n case \"warn\":\n prefix = `${yellow(bold(\"⚠\"))} (serwist)`;\n consoleMethod = \"warn\";\n break;\n case \"info\":\n prefix = `${white(bold(\"○\"))} (serwist)`;\n consoleMethod = \"log\";\n break;\n case \"event\":\n prefix = `${green(bold(\"✓\"))} (serwist)`;\n consoleMethod = \"log\";\n break;\n }\n\n if ((message[0] === \"\" || message[0] === undefined) && message.length === 1) {\n message.shift();\n }\n\n // If there's no message, don't print the prefix but a new line\n if (message.length === 0) {\n console[consoleMethod](\"\");\n } else {\n console[consoleMethod](`${LOGGING_SPACE_PREFIX}${prefix}`, ...message);\n }\n};\n\nexport const wait = (...message: any[]) => prefixedLog(\"wait\", ...message);\n\nexport const error = (...message: any[]) => prefixedLog(\"error\", ...message);\n\nexport const warn = (...message: any[]) => prefixedLog(\"warn\", ...message);\n\nexport const info = (...message: any[]) => prefixedLog(\"info\", ...message);\n\nexport const event = (...message: any[]) => prefixedLog(\"event\", ...message);\n","import { PHASE_DEVELOPMENT_SERVER, PHASE_PRODUCTION_BUILD } from \"next/constants.js\";\n\nexport const loadNextConfig = async (cwd: string, isDev: boolean) => {\n const nextPhase = isDev ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_BUILD;\n // webpackIgnore is only supported by Next.js 15 and above, but it is necessary\n // for loading `next/dist/server/config.js`.\n const nextConfig = await import(/* webpackIgnore: true */ \"next/dist/server/config.js\");\n // 1) what does `default.default` even mean\n const loadConfig =\n typeof nextConfig.default === \"function\" ? (nextConfig.default as unknown as typeof nextConfig.default.default) : nextConfig.default.default;\n return loadConfig(nextPhase, cwd, { silent: false });\n};\n\nexport const generateGlobPatterns = (distDir: string) => [\n `${distDir}static/**/*.{js,css,html,ico,apng,png,avif,jpg,jpeg,jfif,pjpeg,pjp,gif,svg,webp,json,webmanifest}`,\n \"public/**/*\",\n];\n","import path from \"node:path\";\nimport { assertType, basePartial, type Equals, globPartial, injectPartial } from \"@serwist/build/schema\";\nimport semver from \"semver\";\nimport z from \"zod\";\nimport { SUPPORTED_ESBUILD_OPTIONS } from \"./lib/constants.js\";\nimport { NEXT_VERSION } from \"./lib/logger.js\";\nimport { generateGlobPatterns, loadNextConfig } from \"./lib/utils.js\";\nimport type { InjectManifestOptions, InjectManifestOptionsComplete, TurboPartial, TurboResolved } from \"./types.js\";\n\nexport const turboPartial = z.strictObject({\n cwd: z.string().prefault(process.cwd()),\n nextConfig: z\n .object({\n assetPrefix: z.string().optional(),\n basePath: z.string().optional(),\n distDir: z.string().optional(),\n })\n .optional(),\n useNativeEsbuild: z.boolean().prefault(process.platform === \"win32\"),\n rebuildOnChange: z.boolean().prefault(true),\n esbuildOptions: z.partialRecord(z.literal(SUPPORTED_ESBUILD_OPTIONS), z.any()).prefault({}),\n});\n\nexport const injectManifestOptions = z\n .strictObject({\n ...basePartial.shape,\n ...globPartial.shape,\n ...injectPartial.shape,\n ...turboPartial.shape,\n globPatterns: z.array(z.string()).optional(),\n globDirectory: z.string().optional(),\n })\n .omit({ disablePrecacheManifest: true })\n .transform(async (input) => {\n // TODO: remove in semver check in Serwist 10\n // webpackIgnore is only supported by Next.js 15 and above, but it is necessary\n // for loading `next/dist/server/config.js`.\n const nextConfig = semver.gte(NEXT_VERSION, \"15.0.0\")\n ? {\n ...(await loadNextConfig(input.cwd, process.env.NODE_ENV === \"development\")),\n ...input.nextConfig,\n }\n : {\n distDir: input.nextConfig?.distDir ?? \".next\",\n basePath: input.nextConfig?.basePath ?? \"/\",\n assetPrefix: input.nextConfig?.assetPrefix ?? input.nextConfig?.basePath ?? \"\",\n };\n let distDir = nextConfig.distDir;\n if (distDir[0] === \"/\") distDir = distDir.slice(1);\n if (distDir[distDir.length - 1] !== \"/\") distDir += \"/\";\n return {\n ...input,\n swSrc: path.isAbsolute(input.swSrc) ? input.swSrc : path.join(input.cwd, input.swSrc),\n globPatterns: input.globPatterns ?? generateGlobPatterns(distDir),\n globDirectory: input.globDirectory ?? input.cwd,\n dontCacheBustURLsMatching: input.dontCacheBustURLsMatching ?? new RegExp(`^${distDir}static/`),\n nextConfig: {\n ...nextConfig,\n distDir,\n // Next.js, by default, set `basePath` to an empty string.\n basePath: nextConfig.basePath || \"/\",\n },\n };\n });\n\nassertType<Equals<TurboPartial, z.input<typeof turboPartial>>>();\nassertType<Equals<TurboResolved, z.output<typeof turboPartial>>>();\nassertType<Equals<InjectManifestOptions, z.input<typeof injectManifestOptions>>>();\nassertType<Equals<InjectManifestOptionsComplete, z.output<typeof injectManifestOptions>>>();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAEA,MAAa,4BAA4B;CAEvC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CA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AAY,YAAY;EAC7E;CACL,IAAI,UAAU,WAAW;AACzB,KAAI,QAAQ,OAAO,IAAK,WAAU,QAAQ,MAAM,EAAE;AAClD,KAAI,QAAQ,QAAQ,SAAS,OAAO,IAAK,YAAW;AACpD,QAAO;EACL,GAAG;EACH,OAAO,KAAK,WAAW,MAAM,MAAM,GAAG,MAAM,QAAQ,KAAK,KAAK,MAAM,KAAK,MAAM,MAAM;EACrF,cAAc,MAAM,gBAAgB,qBAAqB,QAAQ;EACjE,eAAe,MAAM,iBAAiB,MAAM;EAC5C,2BAA2B,MAAM,6BAA6B,IAAI,OAAO,IAAI,QAAQ,SAAS;EAC9F,YAAY;GACV,GAAG;GACH;GAEA,UAAU,WAAW,YAAY;GAClC;EACF;EACD;AAEJ,YAAgE;AAChE,YAAkE;AAClE,YAAkF;AAClF,YAA2F"}
@@ -0,0 +1,96 @@
1
+ import { BasePartial, GlobPartial, InjectPartial, OptionalGlobDirectoryPartial } from "@serwist/build";
2
+ import { Prettify } from "@serwist/utils";
3
+ import { NextResponse } from "next/server.js";
4
+ import { NextConfig } from "next";
5
+ import { BuildOptions } from "esbuild";
6
+ import { BuildOptions as BuildOptions$1 } from "esbuild-wasm";
7
+
8
+ //#region src/lib/constants.d.ts
9
+ declare const SUPPORTED_ESBUILD_OPTIONS: readonly ["sourcemap", "legalComments", "sourceRoot", "sourcesContent", "format", "globalName", "target", "supported", "define", "treeShaking", "minify", "mangleProps", "reserveProps", "mangleQuoted", "mangleCache", "drop", "dropLabels", "minifyWhitespace", "minifyIdentifiers", "minifySyntax", "lineLimit", "charset", "ignoreAnnotations", "jsx", "jsxFactory", "jsxFragment", "jsxImportSource", "jsxDev", "jsxSideEffects", "pure", "keepNames", "absPaths", "color", "logLevel", "logLimit", "logOverride", "tsconfigRaw", "bundle", "splitting", "preserveSymlinks", "external", "packages", "alias", "loader", "resolveExtensions", "mainFields", "conditions", "allowOverwrite", "tsconfig", "outExtension", "publicPath", "inject", "banner", "footer", "plugins"];
10
+ //#endregion
11
+ //#region src/types.d.ts
12
+ type EsbuildSupportedOptions = (typeof SUPPORTED_ESBUILD_OPTIONS)[number];
13
+ type EsbuildWasmOptions = Prettify<any extends BuildOptions$1 ? never : Pick<BuildOptions$1, EsbuildSupportedOptions>>;
14
+ type EsbuildNativeOptions = Prettify<any extends BuildOptions ? never : Pick<BuildOptions, EsbuildSupportedOptions>>;
15
+ interface NextConfig$1 extends Pick<NextConfig, "basePath" | "distDir"> {
16
+ /**
17
+ * The Next.js `assetPrefix` config option.
18
+ *
19
+ * @see https://nextjs.org/docs/app/api-reference/config/next-config-js/assetPrefix
20
+ */
21
+ assetPrefix?: string;
22
+ /**
23
+ * The Next.js `basePath` config option.
24
+ *
25
+ * @default "/"
26
+ * @see https://nextjs.org/docs/app/api-reference/config/next-config-js/basePath
27
+ */
28
+ basePath?: string;
29
+ /**
30
+ * The Next.js `distDir` config option.
31
+ *
32
+ * @default ".next"
33
+ * @see https://nextjs.org/docs/app/api-reference/config/next-config-js/distDir
34
+ */
35
+ distDir?: string;
36
+ }
37
+ interface TurboPartial {
38
+ /**
39
+ * The path to your working directory.
40
+ *
41
+ * @default process.cwd()
42
+ */
43
+ cwd?: string;
44
+ /**
45
+ * A copy of your Next.js configuration. This option has been deprecated
46
+ * and is no longer necessary, as Serwist can load the Next.js configuration
47
+ * itself. It will be removed in Serwist 10.
48
+ *
49
+ * @deprecated
50
+ */
51
+ nextConfig?: Prettify<NextConfig$1>;
52
+ /**
53
+ * Whether to use the native `esbuild` package instead of
54
+ * `esbuild-wasm` for bundling the service worker. Defaults
55
+ * to `false` if not on Windows, `true` otherwise.
56
+ */
57
+ useNativeEsbuild?: boolean;
58
+ /**
59
+ * Whether to automatically rebuild when source file changes
60
+ * while in development mode.
61
+ *
62
+ * @default true
63
+ */
64
+ rebuildOnChange?: boolean;
65
+ /**
66
+ * Options to configure the esbuild instance used to bundle
67
+ * the service worker.
68
+ */
69
+ esbuildOptions?: EsbuildNativeOptions | EsbuildWasmOptions;
70
+ }
71
+ type InjectManifestOptions = Prettify<Omit<BasePartial & GlobPartial & InjectPartial & OptionalGlobDirectoryPartial & TurboPartial, "disablePrecacheManifest">>;
72
+ //#endregion
73
+ //#region src/index.d.ts
74
+ /**
75
+ * Creates a Route Handler for Serwist files.
76
+ * @param options Options for {@linkcode getFileManifestEntries}.
77
+ */
78
+ declare const createSerwistRoute: (options: InjectManifestOptions) => {
79
+ dynamic: "force-static";
80
+ dynamicParams: false;
81
+ revalidate: false;
82
+ generateStaticParams: () => Promise<{
83
+ path: string;
84
+ }[]>;
85
+ GET: (_: Request, {
86
+ params
87
+ }: {
88
+ params: Promise<{
89
+ path: string;
90
+ }>;
91
+ }) => Promise<NextResponse<unknown>>;
92
+ };
93
+ declare const withSerwist: (nextConfig?: NextConfig) => NextConfig;
94
+ //#endregion
95
+ export { createSerwistRoute, withSerwist };
96
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/lib/constants.ts","../src/types.ts","../src/index.ts"],"mappings":";;;;;;;;cAEa,yBAAA;;;KCcD,uBAAA,WAAkC,yBAAA;AAAA,KAElC,kBAAA,GAAqB,QAAA,aAAqB,cAAA,WAA8B,IAAA,CAAK,cAAA,EAAqB,uBAAA;AAAA,KAElG,oBAAA,GAAuB,QAAA,aAAqB,YAAA,WAAgC,IAAA,CAAK,YAAA,EAAuB,uBAAA;AAAA,UAEnG,YAAA,SAAmB,IAAA,CAAK,UAAA;;;;;;EAMvC,WAAA;EAZU;;;;;AAEZ;EAiBE,QAAA;;;;;;;EAOA,OAAA;AAAA;AAAA,UAGe,YAAA;EA3BqC;;;;;EAiCpD,GAAA;EA/BU;;;;;;;EAuCV,UAAA,GAAa,QAAA,CAAS,YAAA;EAvCmB;;;;;EA6CzC,gBAAA;EA7CkH;;;AAEpH;;;EAkDE,eAAA;EAlDkC;;;;EAuDlC,cAAA,GAAiB,oBAAA,GAAuB,kBAAA;AAAA;AAAA,KAK9B,qBAAA,GAAwB,QAAA,CAClC,IAAA,CAAK,WAAA,GAAc,WAAA,GAAc,aAAA,GAAgB,4BAAA,GAA+B,YAAA;;;;;;;cCtBrE,kBAAA,GAAsB,OAAA,EAAS,qBAAA;;;;;;;WAoGpB,OAAA;IAAO;EAAA;IAAgB,MAAA,EAAQ,OAAA;MAAU,IAAA;IAAA;EAAA,MAAiB,OAAA,CAAA,YAAA;AAAA;AAAA,cAqBrE,WAAA,GAAe,UAAA,GAAY,UAAA,KAAkB,UAAA"}
package/dist/index.mjs ADDED
@@ -0,0 +1,166 @@
1
+ import { r as logger_exports, t as injectManifestOptions } from "./chunks/index.schema-RVDaKxz4.js";
2
+ import crypto from "node:crypto";
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { getFileManifestEntries, rebasePath } from "@serwist/build";
6
+ import { SerwistConfigError, validationErrorMap } from "@serwist/build/schema";
7
+ import { browserslistToEsbuild } from "@serwist/utils";
8
+ import browserslist from "browserslist";
9
+ import { cyan, dim, yellow } from "kolorist";
10
+ import { MODERN_BROWSERSLIST_TARGET } from "next/constants.js";
11
+ import { NextResponse } from "next/server.js";
12
+ import { z } from "zod";
13
+ //#region src/index.ts
14
+ let esbuildWasm = null;
15
+ let esbuildNative = null;
16
+ const logSerwistResult = (filePath, buildResult) => {
17
+ const { count, size, warnings } = buildResult;
18
+ const hasWarnings = warnings && warnings.length > 0;
19
+ if (filePath === "sw.js" && (hasWarnings || count > 0)) logger_exports[hasWarnings ? "warn" : "event"](`${cyan(count)} precache entries ${dim(`(${(size / 1024).toFixed(2)} KiB)`)}${hasWarnings ? `\n${yellow([
20
+ "⚠ warnings",
21
+ ...warnings.map((w) => ` ${w}`),
22
+ ""
23
+ ].join("\n"))}` : ""}`);
24
+ };
25
+ const validateGetManifestOptions = async (input) => {
26
+ const result = await injectManifestOptions.spa(input, { error: validationErrorMap });
27
+ if (!result.success) throw new SerwistConfigError({
28
+ moduleName: "@serwist/turbopack",
29
+ message: z.prettifyError(result.error)
30
+ });
31
+ return result.data;
32
+ };
33
+ const isDev = process.env.NODE_ENV === "development";
34
+ const contentTypeMap = {
35
+ ".js": "application/javascript",
36
+ ".map": "application/json; charset=UTF-8"
37
+ };
38
+ /**
39
+ * Creates a Route Handler for Serwist files.
40
+ * @param options Options for {@linkcode getFileManifestEntries}.
41
+ */
42
+ const createSerwistRoute = (options) => {
43
+ const dynamic = "force-static", dynamicParams = false, revalidate = false;
44
+ const validation = validateGetManifestOptions(options).then((config) => {
45
+ return {
46
+ ...config,
47
+ disablePrecacheManifest: isDev,
48
+ additionalPrecacheEntries: isDev ? [] : config.additionalPrecacheEntries,
49
+ globIgnores: [...config.globIgnores, rebasePath({
50
+ file: config.swSrc,
51
+ baseDirectory: config.globDirectory
52
+ })],
53
+ manifestTransforms: [...config.manifestTransforms ?? [], async (manifestEntries) => {
54
+ return {
55
+ manifest: manifestEntries.map((m) => {
56
+ if (m.url.startsWith(config.nextConfig.distDir)) m.url = `${config.nextConfig.assetPrefix}/_next/${m.url.slice(config.nextConfig.distDir.length)}`;
57
+ if (m.url.startsWith("public/")) m.url = path.posix.join(config.nextConfig.basePath, m.url.slice(7));
58
+ return m;
59
+ }),
60
+ warnings: []
61
+ };
62
+ }]
63
+ };
64
+ });
65
+ let lastHash = null;
66
+ let map = null;
67
+ const loadMap = async (filePath) => {
68
+ const config = await validation;
69
+ const { count, size, manifestEntries, warnings } = await getFileManifestEntries(config);
70
+ const injectionPoint = config.injectionPoint || "";
71
+ const manifestString = manifestEntries === void 0 ? "undefined" : JSON.stringify(manifestEntries, null, 2);
72
+ const log = (type, ...message) => {
73
+ if (filePath === "sw.js") logger_exports[type](...message);
74
+ };
75
+ let esbuild;
76
+ if (config.useNativeEsbuild) {
77
+ log("info", "Using esbuild to bundle the service worker.");
78
+ if (!esbuildNative) esbuildNative = import(
79
+ /* webpackIgnore: true */
80
+ "esbuild"
81
+ );
82
+ esbuild = await esbuildNative;
83
+ } else {
84
+ log("info", "Using esbuild-wasm to bundle the service worker.");
85
+ if (!esbuildWasm) esbuildWasm = import(
86
+ /* webpackIgnore: true */
87
+ "esbuild-wasm"
88
+ );
89
+ esbuild = await esbuildWasm;
90
+ }
91
+ logSerwistResult(filePath, {
92
+ count,
93
+ size,
94
+ warnings
95
+ });
96
+ const result = await esbuild.build({
97
+ sourcemap: true,
98
+ format: "esm",
99
+ treeShaking: true,
100
+ minify: !isDev,
101
+ bundle: true,
102
+ ...config.esbuildOptions,
103
+ target: config.esbuildOptions?.target ?? browserslistToEsbuild(browserslist, config.cwd, MODERN_BROWSERSLIST_TARGET),
104
+ platform: "browser",
105
+ define: {
106
+ ...config.esbuildOptions.define,
107
+ ...injectionPoint ? { [injectionPoint]: manifestString } : {}
108
+ },
109
+ outdir: config.cwd,
110
+ write: false,
111
+ entryNames: "[name]",
112
+ assetNames: "[name]-[hash]",
113
+ chunkNames: "[name]-[hash]",
114
+ entryPoints: [{
115
+ in: config.swSrc,
116
+ out: "sw"
117
+ }]
118
+ });
119
+ if (result.errors.length) {
120
+ console.error("Failed to build the service worker.", result.errors);
121
+ throw new Error();
122
+ }
123
+ if (result.warnings.length) console.warn(result.warnings);
124
+ return new Map(result.outputFiles.map((e) => [e.path, e.text]));
125
+ };
126
+ const generateStaticParams = async () => {
127
+ const config = await validation;
128
+ if (!map) map = await loadMap("root");
129
+ return [...map.keys()].map((e) => ({ path: path.relative(config.cwd, e) }));
130
+ };
131
+ const GET = async (_, { params }) => {
132
+ const { path: filePath } = await params;
133
+ const config = await validation;
134
+ if (isDev && config.rebuildOnChange) {
135
+ const swContent = fs.readFileSync(config.swSrc, "utf-8");
136
+ const currentHash = crypto.createHash("sha256").update(swContent).digest("hex");
137
+ if (!map || lastHash !== currentHash) {
138
+ map = await loadMap(filePath);
139
+ lastHash = currentHash;
140
+ }
141
+ } else if (!map) map = await loadMap(filePath);
142
+ return new NextResponse(map.get(path.join(config.cwd, filePath)), { headers: {
143
+ "Content-Type": contentTypeMap[path.extname(filePath)] || "text/plain",
144
+ "Service-Worker-Allowed": "/"
145
+ } });
146
+ };
147
+ return {
148
+ dynamic,
149
+ dynamicParams,
150
+ revalidate,
151
+ generateStaticParams,
152
+ GET
153
+ };
154
+ };
155
+ const withSerwist = (nextConfig = {}) => ({
156
+ ...nextConfig,
157
+ serverExternalPackages: [
158
+ ...nextConfig.serverExternalPackages ?? [],
159
+ "esbuild",
160
+ "esbuild-wasm"
161
+ ]
162
+ });
163
+ //#endregion
164
+ export { createSerwistRoute, withSerwist };
165
+
166
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["// Workaround for Next.js + Turbopack, while plugins are still\n// not supported. This relies on Next.js Route Handlers and file\n// name determinism.\nimport crypto from \"node:crypto\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { type BuildResult, getFileManifestEntries, rebasePath } from \"@serwist/build\";\nimport { SerwistConfigError, validationErrorMap } from \"@serwist/build/schema\";\nimport { browserslistToEsbuild } from \"@serwist/utils\";\nimport browserslist from \"browserslist\";\nimport { cyan, dim, yellow } from \"kolorist\";\nimport type { NextConfig } from \"next\";\nimport { MODERN_BROWSERSLIST_TARGET } from \"next/constants.js\";\nimport { NextResponse } from \"next/server.js\";\nimport { z } from \"zod\";\nimport { injectManifestOptions } from \"./index.schema.js\";\nimport { logger } from \"./lib/index.js\";\nimport type { LoggingMethods } from \"./lib/logger.js\";\nimport type { InjectManifestOptions, InjectManifestOptionsComplete } from \"./types.js\";\n\nlet esbuildWasm: Promise<typeof import(\"esbuild-wasm\")> | null = null;\nlet esbuildNative: Promise<typeof import(\"esbuild\")> | null = null;\n\nconst logSerwistResult = (filePath: string, buildResult: Pick<BuildResult, \"count\" | \"size\" | \"warnings\">) => {\n const { count, size, warnings } = buildResult;\n const hasWarnings = warnings && warnings.length > 0;\n // The route is reinitiated for each `path` param, so we only log results\n // if we're prerendering for sw.js.\n if (filePath === \"sw.js\" && (hasWarnings || count > 0)) {\n logger[hasWarnings ? \"warn\" : \"event\"](\n `${cyan(count)} precache entries ${dim(`(${(size / 1024).toFixed(2)} KiB)`)}${\n hasWarnings ? `\\n${yellow([\"⚠ warnings\", ...warnings.map((w) => ` ${w}`), \"\"].join(\"\\n\"))}` : \"\"\n }`,\n );\n }\n};\n\nconst validateGetManifestOptions = async (input: unknown): Promise<InjectManifestOptionsComplete> => {\n const result = await injectManifestOptions.spa(input, {\n error: validationErrorMap,\n });\n if (!result.success) {\n throw new SerwistConfigError({\n moduleName: \"@serwist/turbopack\",\n message: z.prettifyError(result.error),\n });\n }\n return result.data;\n};\n\nconst isDev = process.env.NODE_ENV === \"development\";\n\nconst contentTypeMap: Record<string, string> = {\n \".js\": \"application/javascript\",\n \".map\": \"application/json; charset=UTF-8\",\n};\n\n/**\n * Creates a Route Handler for Serwist files.\n * @param options Options for {@linkcode getFileManifestEntries}.\n */\nexport const createSerwistRoute = (options: InjectManifestOptions) => {\n const dynamic = \"force-static\" as const,\n dynamicParams = false as const,\n revalidate = false as const;\n const validation = validateGetManifestOptions(options).then((config) => {\n return {\n ...config,\n disablePrecacheManifest: isDev,\n additionalPrecacheEntries: isDev ? [] : config.additionalPrecacheEntries,\n globIgnores: [\n ...config.globIgnores,\n // Make sure we leave swSrc out of the precache manifest.\n rebasePath({\n file: config.swSrc,\n baseDirectory: config.globDirectory,\n }),\n ],\n manifestTransforms: [\n ...(config.manifestTransforms ?? []),\n async (manifestEntries) => {\n const manifest = manifestEntries.map((m) => {\n // Replace all references to \"$(distDir)\" with \"$(assetPrefix)/_next/\".\n if (m.url.startsWith(config.nextConfig.distDir)) {\n m.url = `${config.nextConfig.assetPrefix}/_next/${m.url.slice(config.nextConfig.distDir.length)}`;\n }\n // Replace all references to public/ with \"$(basePath)/\".\n if (m.url.startsWith(\"public/\")) {\n m.url = path.posix.join(config.nextConfig.basePath, m.url.slice(7));\n }\n return m;\n });\n return { manifest, warnings: [] };\n },\n ],\n };\n });\n let lastHash: string | null = null;\n let map: Map<string, string> | null = null;\n // NOTE: ALL FILES MUST HAVE DETERMINISTIC NAMES. THIS IS BECAUSE\n // THE FOLLOWING MAP IS LOADED SEPARATELY FOR `generateStaticParams`\n // AND EVERY `GET` REQUEST TO EACH OF THE FILES.\n const loadMap = async (filePath: string) => {\n const config = await validation;\n const { count, size, manifestEntries, warnings } = await getFileManifestEntries(config);\n // See https://github.com/GoogleChrome/workbox/issues/2230\n const injectionPoint = config.injectionPoint || \"\";\n const manifestString = manifestEntries === undefined ? \"undefined\" : JSON.stringify(manifestEntries, null, 2);\n const log = (type: LoggingMethods, ...message: any[]) => {\n if (filePath === \"sw.js\") {\n logger[type](...message);\n }\n };\n let esbuild: typeof import(\"esbuild\");\n if (config.useNativeEsbuild) {\n log(\"info\", \"Using esbuild to bundle the service worker.\");\n if (!esbuildNative) esbuildNative = import(/* webpackIgnore: true */ \"esbuild\");\n esbuild = await esbuildNative;\n } else {\n log(\"info\", \"Using esbuild-wasm to bundle the service worker.\");\n if (!esbuildWasm) esbuildWasm = import(/* webpackIgnore: true */ \"esbuild-wasm\");\n esbuild = await esbuildWasm;\n }\n logSerwistResult(filePath, { count, size, warnings });\n const result = await esbuild.build({\n sourcemap: true,\n format: \"esm\",\n treeShaking: true,\n minify: !isDev,\n bundle: true,\n ...config.esbuildOptions,\n target: config.esbuildOptions?.target ?? browserslistToEsbuild(browserslist, config.cwd, MODERN_BROWSERSLIST_TARGET),\n platform: \"browser\",\n define: {\n ...config.esbuildOptions.define,\n ...(injectionPoint ? { [injectionPoint]: manifestString } : {}),\n },\n outdir: config.cwd,\n write: false,\n entryNames: \"[name]\",\n // Asset and chunk names must be at the top, as our path is `/serwist/[path]`,\n // not `/serwist/[...path]`, meaning that we can't resolve paths deeper\n // than one level.\n assetNames: \"[name]-[hash]\",\n chunkNames: \"[name]-[hash]\",\n entryPoints: [{ in: config.swSrc, out: \"sw\" }],\n });\n if (result.errors.length) {\n console.error(\"Failed to build the service worker.\", result.errors);\n throw new Error();\n }\n if (result.warnings.length) {\n console.warn(result.warnings);\n }\n return new Map(result.outputFiles.map((e) => [e.path, e.text]));\n };\n const generateStaticParams = async () => {\n const config = await validation;\n if (!map) map = await loadMap(\"root\");\n return [...map.keys()].map((e) => ({ path: path.relative(config.cwd, e) }));\n };\n const GET = async (_: Request, { params }: { params: Promise<{ path: string }> }) => {\n const { path: filePath } = await params;\n const config = await validation;\n if (isDev && config.rebuildOnChange) {\n const swContent = fs.readFileSync(config.swSrc, \"utf-8\");\n const currentHash = crypto.createHash(\"sha256\").update(swContent).digest(\"hex\");\n if (!map || lastHash !== currentHash) {\n map = await loadMap(filePath);\n lastHash = currentHash;\n }\n } else if (!map) map = await loadMap(filePath);\n return new NextResponse(map.get(path.join(config.cwd, filePath)), {\n headers: {\n \"Content-Type\": contentTypeMap[path.extname(filePath)] || \"text/plain\",\n \"Service-Worker-Allowed\": \"/\",\n },\n });\n };\n return { dynamic, dynamicParams, revalidate, generateStaticParams, GET };\n};\n\nexport const withSerwist = (nextConfig: NextConfig = {}): NextConfig => ({\n ...nextConfig,\n serverExternalPackages: [...(nextConfig.serverExternalPackages ?? []), \"esbuild\", \"esbuild-wasm\"],\n});\n"],"mappings":";;;;;;;;;;;;;AAoBA,IAAI,cAA6D;AACjE,IAAI,gBAA0D;AAE9D,MAAM,oBAAoB,UAAkB,gBAAkE;CAC5G,MAAM,EAAE,OAAO,MAAM,aAAa;CAClC,MAAM,cAAc,YAAY,SAAS,SAAS;AAGlD,KAAI,aAAa,YAAY,eAAe,QAAQ,GAClD,gBAAO,cAAc,SAAS,SAC5B,GAAG,KAAK,MAAM,CAAC,oBAAoB,IAAI,KAAK,OAAO,MAAM,QAAQ,EAAE,CAAC,OAAO,GACzE,cAAc,KAAK,OAAO;EAAC;EAAc,GAAG,SAAS,KAAK,MAAM,KAAK,IAAI;EAAE;EAAG,CAAC,KAAK,KAAK,CAAC,KAAK,KAElG;;AAIL,MAAM,6BAA6B,OAAO,UAA2D;CAC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IAAI,MAAM,CAAC,CAAC,KAAK,OAAO,EAAE,MAAM,KAAK,SAAS,OAAO,KAAK,EAAE,EAAE,EAAE;;CAE7E,MAAM,MAAM,OAAO,GAAY,EAAE,aAAoD;EACnF,MAAM,EAAE,MAAM,aAAa,MAAM;EACjC,MAAM,SAAS,MAAM;AACrB,MAAI,SAAS,OAAO,iBAAiB;GACnC,MAAM,YAAY,GAAG,aAAa,OAAO,OAAO,QAAQ;GACxD,MAAM,cAAc,OAAO,WAAW,SAAS,CAAC,OAAO,UAAU,CAAC,OAAO,MAAM;AAC/E,OAAI,CAAC,OAAO,aAAa,aAAa;AACpC,UAAM,MAAM,QAAQ,SAAS;AAC7B,eAAW;;aAEJ,CAAC,IAAK,OAAM,MAAM,QAAQ,SAAS;AAC9C,SAAO,IAAI,aAAa,IAAI,IAAI,KAAK,KAAK,OAAO,KAAK,SAAS,CAAC,EAAE,EAChE,SAAS;GACP,gBAAgB,eAAe,KAAK,QAAQ,SAAS,KAAK;GAC1D,0BAA0B;GAC3B,EACF,CAAC;;AAEJ,QAAO;EAAE;EAAS;EAAe;EAAY;EAAsB;EAAK;;AAG1E,MAAa,eAAe,aAAyB,EAAE,MAAkB;CACvE,GAAG;CACH,wBAAwB;EAAC,GAAI,WAAW,0BAA0B,EAAE;EAAG;EAAW;EAAe;CAClG"}
@@ -0,0 +1,42 @@
1
+ import { Serwist } from "@serwist/window";
2
+ import * as _$react from "react";
3
+ import { ReactNode } from "react";
4
+
5
+ //#region src/lib/context.d.ts
6
+ interface SerwistContextValues {
7
+ serwist: Serwist | null;
8
+ }
9
+ declare const useSerwist: () => SerwistContextValues;
10
+ //#endregion
11
+ //#region src/index.react.d.ts
12
+ interface SerwistProviderProps {
13
+ swUrl: string;
14
+ disable?: boolean;
15
+ register?: boolean;
16
+ cacheOnNavigation?: boolean;
17
+ reloadOnOnline?: boolean;
18
+ options?: RegistrationOptions;
19
+ children?: ReactNode;
20
+ }
21
+ declare global {
22
+ interface Window {
23
+ serwist: Serwist;
24
+ }
25
+ }
26
+ /**
27
+ * `@serwist/window` provider for Next.js apps.
28
+ * @param options
29
+ * @returns
30
+ */
31
+ declare function SerwistProvider({
32
+ swUrl,
33
+ disable,
34
+ register,
35
+ cacheOnNavigation,
36
+ reloadOnOnline,
37
+ options,
38
+ children
39
+ }: SerwistProviderProps): _$react.JSX.Element;
40
+ //#endregion
41
+ export { SerwistProvider, SerwistProviderProps, useSerwist };
42
+ //# sourceMappingURL=index.react.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.react.d.mts","names":[],"sources":["../src/lib/context.ts","../src/index.react.tsx"],"mappings":";;;;;UAGiB,oBAAA;EACf,OAAA,EAAS,OAAA;AAAA;AAAA,cAKE,UAAA,QAAU,oBAAA;;;UCJN,oBAAA;EACf,KAAA;EACA,OAAA;EACA,QAAA;EACA,iBAAA;EACA,cAAA;EACA,OAAA,GAAU,mBAAA;EACV,QAAA,GAAW,SAAA;AAAA;AAAA,QAGL,MAAA;EAAA,UACI,MAAA;IACR,OAAA,EAAS,OAAA;EAAA;AAAA;;AAZb;;;;iBAqBgB,eAAA,CAAA;EACd,KAAA;EACA,OAAA;EACA,QAAA;EACA,iBAAA;EACA,cAAA;EACA,OAAA;EACA;AAAA,GACC,oBAAA,GAAoB,OAAA,CAAA,GAAA,CAAA,OAAA"}
@@ -0,0 +1,73 @@
1
+ import { Serwist } from "@serwist/window";
2
+ import { isCurrentPageOutOfScope } from "@serwist/window/internal";
3
+ import { createContext, useContext, useEffect, useState } from "react";
4
+ //#region src/lib/context.ts
5
+ const SerwistContext = createContext(null);
6
+ const useSerwist = () => {
7
+ const context = useContext(SerwistContext);
8
+ if (!context) throw new Error("[useSerwist]: 'SerwistContext' is not available.");
9
+ return context;
10
+ };
11
+ //#endregion
12
+ //#region src/index.react.tsx
13
+ /**
14
+ * `@serwist/window` provider for Next.js apps.
15
+ * @param options
16
+ * @returns
17
+ */
18
+ function SerwistProvider({ swUrl, disable = false, register = true, cacheOnNavigation = true, reloadOnOnline = true, options, children }) {
19
+ const [serwist] = useState(() => {
20
+ if (typeof window === "undefined") return null;
21
+ if (disable) return null;
22
+ const scope = options?.scope || "/";
23
+ if (!(window.serwist && window.serwist instanceof Serwist) && "serviceWorker" in navigator) {
24
+ window.serwist = new Serwist(swUrl, {
25
+ ...options,
26
+ scope,
27
+ type: options?.type || "module"
28
+ });
29
+ if (register && !isCurrentPageOutOfScope(scope)) window.serwist.register();
30
+ }
31
+ return window.serwist ?? null;
32
+ });
33
+ useEffect(() => {
34
+ const cacheUrls = async (url) => {
35
+ if (!window.navigator.onLine || !url) return;
36
+ serwist?.messageSW({
37
+ type: "CACHE_URLS",
38
+ payload: { urlsToCache: [url] }
39
+ });
40
+ };
41
+ const cacheCurrentPathname = () => cacheUrls(window.location.pathname);
42
+ const pushState = history.pushState;
43
+ const replaceState = history.replaceState;
44
+ if (cacheOnNavigation) {
45
+ history.pushState = (...args) => {
46
+ pushState.apply(history, args);
47
+ cacheUrls(args[2]);
48
+ };
49
+ history.replaceState = (...args) => {
50
+ replaceState.apply(history, args);
51
+ cacheUrls(args[2]);
52
+ };
53
+ window.addEventListener("online", cacheCurrentPathname);
54
+ }
55
+ return () => {
56
+ history.pushState = pushState;
57
+ history.replaceState = replaceState;
58
+ window.removeEventListener("online", cacheCurrentPathname);
59
+ };
60
+ }, [serwist, cacheOnNavigation]);
61
+ useEffect(() => {
62
+ const reload = () => location.reload();
63
+ if (reloadOnOnline) window.addEventListener("online", reload);
64
+ return () => {
65
+ window.removeEventListener("online", reload);
66
+ };
67
+ }, [reloadOnOnline]);
68
+ return <SerwistContext.Provider value={{ serwist }}>{children}</SerwistContext.Provider>;
69
+ }
70
+ //#endregion
71
+ export { SerwistProvider, useSerwist };
72
+
73
+ //# sourceMappingURL=index.react.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.react.mjs","names":[],"sources":["../src/lib/context.ts","../src/index.react.tsx"],"sourcesContent":["import type { Serwist } from \"@serwist/window\";\nimport { createContext, useContext } from \"react\";\n\nexport interface SerwistContextValues {\n serwist: Serwist | null;\n}\n\nexport const SerwistContext = createContext<SerwistContextValues>(null!);\n\nexport const useSerwist = () => {\n const context = useContext(SerwistContext);\n if (!context) {\n throw new Error(\"[useSerwist]: 'SerwistContext' is not available.\");\n }\n return context;\n};\n","import { Serwist } from \"@serwist/window\";\nimport { isCurrentPageOutOfScope } from \"@serwist/window/internal\";\nimport { type ReactNode, useEffect, useState } from \"react\";\nimport { SerwistContext, useSerwist } from \"./lib/context.js\";\n\nexport interface SerwistProviderProps {\n swUrl: string;\n disable?: boolean;\n register?: boolean;\n cacheOnNavigation?: boolean;\n reloadOnOnline?: boolean;\n options?: RegistrationOptions;\n children?: ReactNode;\n}\n\ndeclare global {\n interface Window {\n serwist: Serwist;\n }\n}\n\n/**\n * `@serwist/window` provider for Next.js apps.\n * @param options\n * @returns\n */\nexport function SerwistProvider({\n swUrl,\n disable = false,\n register = true,\n cacheOnNavigation = true,\n reloadOnOnline = true,\n options,\n children,\n}: SerwistProviderProps) {\n const [serwist] = useState(() => {\n if (typeof window === \"undefined\") return null;\n if (disable) return null;\n const scope = options?.scope || \"/\";\n if (!(window.serwist && window.serwist instanceof Serwist) && \"serviceWorker\" in navigator) {\n window.serwist = new Serwist(swUrl, { ...options, scope, type: options?.type || \"module\" });\n if (register && !isCurrentPageOutOfScope(scope)) {\n void window.serwist.register();\n }\n }\n return window.serwist ?? null;\n });\n useEffect(() => {\n const cacheUrls = async (url?: string | URL | null | undefined) => {\n if (!window.navigator.onLine || !url) {\n return;\n }\n serwist?.messageSW({\n type: \"CACHE_URLS\",\n payload: { urlsToCache: [url] },\n });\n };\n const cacheCurrentPathname = () => cacheUrls(window.location.pathname);\n const pushState = history.pushState;\n const replaceState = history.replaceState;\n\n if (cacheOnNavigation) {\n history.pushState = (...args) => {\n pushState.apply(history, args);\n cacheUrls(args[2]);\n };\n history.replaceState = (...args) => {\n replaceState.apply(history, args);\n cacheUrls(args[2]);\n };\n window.addEventListener(\"online\", cacheCurrentPathname);\n }\n\n return () => {\n history.pushState = pushState;\n history.replaceState = replaceState;\n window.removeEventListener(\"online\", cacheCurrentPathname);\n };\n }, [serwist, cacheOnNavigation]);\n useEffect(() => {\n const reload = () => location.reload();\n if (reloadOnOnline) {\n window.addEventListener(\"online\", reload);\n }\n return () => {\n window.removeEventListener(\"online\", reload);\n };\n }, [reloadOnOnline]);\n return <SerwistContext.Provider value={{ serwist }}>{children}</SerwistContext.Provider>;\n}\n\nexport { useSerwist };\n"],"mappings":";;;;AAOA,MAAa,iBAAiB,cAAoC,KAAM;AAExE,MAAa,mBAAmB;CAC9B,MAAM,UAAU,WAAW,eAAe;AAC1C,KAAI,CAAC,QACH,OAAM,IAAI,MAAM,mDAAmD;AAErE,QAAO;;;;;;;;;ACYT,SAAgB,gBAAgB,EAC9B,OACA,UAAU,OACV,WAAW,MACX,oBAAoB,MACpB,iBAAiB,MACjB,SACA,YACuB;CACvB,MAAM,CAAC,WAAW,eAAe;AAC/B,MAAI,OAAO,WAAW,YAAa,QAAO;AAC1C,MAAI,QAAS,QAAO;EACpB,MAAM,QAAQ,SAAS,SAAS;AAChC,MAAI,EAAE,OAAO,WAAW,OAAO,mBAAmB,YAAY,mBAAmB,WAAW;AAC1F,UAAO,UAAU,IAAI,QAAQ,OAAO;IAAE,GAAG;IAAS;IAAO,MAAM,SAAS,QAAQ;IAAU,CAAC;AAC3F,OAAI,YAAY,CAAC,wBAAwB,MAAM,CACxC,QAAO,QAAQ,UAAU;;AAGlC,SAAO,OAAO,WAAW;GACzB;AACF,iBAAgB;EACd,MAAM,YAAY,OAAO,QAA0C;AACjE,OAAI,CAAC,OAAO,UAAU,UAAU,CAAC,IAC/B;AAEF,YAAS,UAAU;IACjB,MAAM;IACN,SAAS,EAAE,aAAa,CAAC,IAAI,EAAE;IAChC,CAAC;;EAEJ,MAAM,6BAA6B,UAAU,OAAO,SAAS,SAAS;EACtE,MAAM,YAAY,QAAQ;EAC1B,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