@posthog/nextjs-config 1.1.0 → 1.1.1

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.
@@ -1,5 +1,4 @@
1
- import { NextConfig } from 'next';
2
-
1
+ import type { NextConfig } from 'next';
3
2
  type NextFuncConfig = (phase: string, { defaultConfig }: {
4
3
  defaultConfig: NextConfig;
5
4
  }) => NextConfig;
@@ -7,7 +6,7 @@ type NextAsyncConfig = (phase: string, { defaultConfig }: {
7
6
  defaultConfig: NextConfig;
8
7
  }) => Promise<NextConfig>;
9
8
  type UserProvidedConfig = NextConfig | NextFuncConfig | NextAsyncConfig;
10
- type PostHogNextConfig = {
9
+ export type PostHogNextConfig = {
11
10
  personalApiKey: string;
12
11
  envId: string;
13
12
  host?: string;
@@ -19,7 +18,7 @@ type PostHogNextConfig = {
19
18
  deleteAfterUpload?: boolean;
20
19
  };
21
20
  };
22
- type PostHogNextConfigComplete = {
21
+ export type PostHogNextConfigComplete = {
23
22
  personalApiKey: string;
24
23
  envId: string;
25
24
  host: string;
@@ -31,6 +30,5 @@ type PostHogNextConfigComplete = {
31
30
  deleteAfterUpload: boolean;
32
31
  };
33
32
  };
34
- declare function withPostHogConfig(userNextConfig: UserProvidedConfig, posthogConfig: PostHogNextConfig): NextConfig;
35
-
36
- export { type PostHogNextConfig, type PostHogNextConfigComplete, withPostHogConfig };
33
+ export declare function withPostHogConfig(userNextConfig: UserProvidedConfig, posthogConfig: PostHogNextConfig): NextConfig;
34
+ export {};
package/dist/config.js ADDED
@@ -0,0 +1,86 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.d = (exports1, definition)=>{
5
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
6
+ enumerable: true,
7
+ get: definition[key]
8
+ });
9
+ };
10
+ })();
11
+ (()=>{
12
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
13
+ })();
14
+ (()=>{
15
+ __webpack_require__.r = (exports1)=>{
16
+ if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
17
+ value: 'Module'
18
+ });
19
+ Object.defineProperty(exports1, '__esModule', {
20
+ value: true
21
+ });
22
+ };
23
+ })();
24
+ var __webpack_exports__ = {};
25
+ __webpack_require__.r(__webpack_exports__);
26
+ __webpack_require__.d(__webpack_exports__, {
27
+ withPostHogConfig: ()=>withPostHogConfig
28
+ });
29
+ const external_webpack_plugin_js_namespaceObject = require("./webpack-plugin.js");
30
+ function withPostHogConfig(userNextConfig, posthogConfig) {
31
+ const posthogNextConfigComplete = resolvePostHogConfig(posthogConfig);
32
+ return async (phase, param)=>{
33
+ let { defaultConfig } = param;
34
+ const { webpack: userWebPackConfig, distDir, ...userConfig } = await resolveUserConfig(userNextConfig, phase, defaultConfig);
35
+ const defaultWebpackConfig = userWebPackConfig || ((config)=>config);
36
+ const sourceMapEnabled = posthogNextConfigComplete.sourcemaps.enabled;
37
+ return {
38
+ ...userConfig,
39
+ distDir,
40
+ productionBrowserSourceMaps: sourceMapEnabled,
41
+ webpack: (config, options)=>{
42
+ const webpackConfig = defaultWebpackConfig(config, options);
43
+ if (webpackConfig && options.isServer && sourceMapEnabled) webpackConfig.devtool = 'source-map';
44
+ if (sourceMapEnabled) {
45
+ webpackConfig.plugins = webpackConfig.plugins || [];
46
+ webpackConfig.plugins.push(new external_webpack_plugin_js_namespaceObject.SourcemapWebpackPlugin(posthogNextConfigComplete, options.isServer, options.nextRuntime, distDir));
47
+ }
48
+ return webpackConfig;
49
+ }
50
+ };
51
+ };
52
+ }
53
+ function resolveUserConfig(userNextConfig, phase, defaultConfig) {
54
+ if ('function' == typeof userNextConfig) {
55
+ const maybePromise = userNextConfig(phase, {
56
+ defaultConfig
57
+ });
58
+ if (maybePromise instanceof Promise) return maybePromise;
59
+ return Promise.resolve(maybePromise);
60
+ }
61
+ if ('object' == typeof userNextConfig) return Promise.resolve(userNextConfig);
62
+ throw new Error('Invalid user config');
63
+ }
64
+ function resolvePostHogConfig(posthogProvidedConfig) {
65
+ const { personalApiKey, envId, host, verbose, sourcemaps = {} } = posthogProvidedConfig;
66
+ var _sourcemaps_enabled, _sourcemaps_deleteAfterUpload;
67
+ return {
68
+ personalApiKey,
69
+ envId,
70
+ host: null != host ? host : 'https://us.posthog.com',
71
+ verbose: null != verbose ? verbose : true,
72
+ sourcemaps: {
73
+ enabled: null != (_sourcemaps_enabled = sourcemaps.enabled) ? _sourcemaps_enabled : 'production' == process.env.NODE_ENV,
74
+ project: sourcemaps.project,
75
+ version: sourcemaps.version,
76
+ deleteAfterUpload: null != (_sourcemaps_deleteAfterUpload = sourcemaps.deleteAfterUpload) ? _sourcemaps_deleteAfterUpload : true
77
+ }
78
+ };
79
+ }
80
+ exports.withPostHogConfig = __webpack_exports__.withPostHogConfig;
81
+ for(var __webpack_i__ in __webpack_exports__)if (-1 === [
82
+ "withPostHogConfig"
83
+ ].indexOf(__webpack_i__)) exports[__webpack_i__] = __webpack_exports__[__webpack_i__];
84
+ Object.defineProperty(exports, '__esModule', {
85
+ value: true
86
+ });
@@ -0,0 +1,52 @@
1
+ import { SourcemapWebpackPlugin } from "./webpack-plugin.mjs";
2
+ function withPostHogConfig(userNextConfig, posthogConfig) {
3
+ const posthogNextConfigComplete = resolvePostHogConfig(posthogConfig);
4
+ return async (phase, param)=>{
5
+ let { defaultConfig } = param;
6
+ const { webpack: userWebPackConfig, distDir, ...userConfig } = await resolveUserConfig(userNextConfig, phase, defaultConfig);
7
+ const defaultWebpackConfig = userWebPackConfig || ((config)=>config);
8
+ const sourceMapEnabled = posthogNextConfigComplete.sourcemaps.enabled;
9
+ return {
10
+ ...userConfig,
11
+ distDir,
12
+ productionBrowserSourceMaps: sourceMapEnabled,
13
+ webpack: (config, options)=>{
14
+ const webpackConfig = defaultWebpackConfig(config, options);
15
+ if (webpackConfig && options.isServer && sourceMapEnabled) webpackConfig.devtool = 'source-map';
16
+ if (sourceMapEnabled) {
17
+ webpackConfig.plugins = webpackConfig.plugins || [];
18
+ webpackConfig.plugins.push(new SourcemapWebpackPlugin(posthogNextConfigComplete, options.isServer, options.nextRuntime, distDir));
19
+ }
20
+ return webpackConfig;
21
+ }
22
+ };
23
+ };
24
+ }
25
+ function resolveUserConfig(userNextConfig, phase, defaultConfig) {
26
+ if ('function' == typeof userNextConfig) {
27
+ const maybePromise = userNextConfig(phase, {
28
+ defaultConfig
29
+ });
30
+ if (maybePromise instanceof Promise) return maybePromise;
31
+ return Promise.resolve(maybePromise);
32
+ }
33
+ if ('object' == typeof userNextConfig) return Promise.resolve(userNextConfig);
34
+ throw new Error('Invalid user config');
35
+ }
36
+ function resolvePostHogConfig(posthogProvidedConfig) {
37
+ const { personalApiKey, envId, host, verbose, sourcemaps = {} } = posthogProvidedConfig;
38
+ var _sourcemaps_enabled, _sourcemaps_deleteAfterUpload;
39
+ return {
40
+ personalApiKey,
41
+ envId,
42
+ host: null != host ? host : 'https://us.posthog.com',
43
+ verbose: null != verbose ? verbose : true,
44
+ sourcemaps: {
45
+ enabled: null != (_sourcemaps_enabled = sourcemaps.enabled) ? _sourcemaps_enabled : 'production' == process.env.NODE_ENV,
46
+ project: sourcemaps.project,
47
+ version: sourcemaps.version,
48
+ deleteAfterUpload: null != (_sourcemaps_deleteAfterUpload = sourcemaps.deleteAfterUpload) ? _sourcemaps_deleteAfterUpload : true
49
+ }
50
+ };
51
+ }
52
+ export { withPostHogConfig };
package/dist/index.d.ts CHANGED
@@ -1,36 +1 @@
1
- import { NextConfig } from 'next';
2
-
3
- type NextFuncConfig = (phase: string, { defaultConfig }: {
4
- defaultConfig: NextConfig;
5
- }) => NextConfig;
6
- type NextAsyncConfig = (phase: string, { defaultConfig }: {
7
- defaultConfig: NextConfig;
8
- }) => Promise<NextConfig>;
9
- type UserProvidedConfig = NextConfig | NextFuncConfig | NextAsyncConfig;
10
- type PostHogNextConfig = {
11
- personalApiKey: string;
12
- envId: string;
13
- host?: string;
14
- verbose?: boolean;
15
- sourcemaps?: {
16
- enabled?: boolean;
17
- project?: string;
18
- version?: string;
19
- deleteAfterUpload?: boolean;
20
- };
21
- };
22
- type PostHogNextConfigComplete = {
23
- personalApiKey: string;
24
- envId: string;
25
- host: string;
26
- verbose: boolean;
27
- sourcemaps: {
28
- enabled: boolean;
29
- project?: string;
30
- version?: string;
31
- deleteAfterUpload: boolean;
32
- };
33
- };
34
- declare function withPostHogConfig(userNextConfig: UserProvidedConfig, posthogConfig: PostHogNextConfig): NextConfig;
35
-
36
- export { type PostHogNextConfig, type PostHogNextConfigComplete, withPostHogConfig };
1
+ export * from './config';
package/dist/index.js CHANGED
@@ -1,295 +1,60 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __defProps = Object.defineProperties;
5
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
7
- var __getOwnPropNames = Object.getOwnPropertyNames;
8
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
9
- var __getProtoOf = Object.getPrototypeOf;
10
- var __hasOwnProp = Object.prototype.hasOwnProperty;
11
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
12
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
- var __spreadValues = (a, b) => {
14
- for (var prop in b || (b = {}))
15
- if (__hasOwnProp.call(b, prop))
16
- __defNormalProp(a, prop, b[prop]);
17
- if (__getOwnPropSymbols)
18
- for (var prop of __getOwnPropSymbols(b)) {
19
- if (__propIsEnum.call(b, prop))
20
- __defNormalProp(a, prop, b[prop]);
2
+ var __webpack_modules__ = {
3
+ "./config": function(module) {
4
+ module.exports = require("./config.js");
21
5
  }
22
- return a;
23
6
  };
24
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
25
- var __objRest = (source, exclude) => {
26
- var target = {};
27
- for (var prop in source)
28
- if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
29
- target[prop] = source[prop];
30
- if (source != null && __getOwnPropSymbols)
31
- for (var prop of __getOwnPropSymbols(source)) {
32
- if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
33
- target[prop] = source[prop];
34
- }
35
- return target;
36
- };
37
- var __export = (target, all) => {
38
- for (var name in all)
39
- __defProp(target, name, { get: all[name], enumerable: true });
40
- };
41
- var __copyProps = (to, from, except, desc) => {
42
- if (from && typeof from === "object" || typeof from === "function") {
43
- for (let key of __getOwnPropNames(from))
44
- if (!__hasOwnProp.call(to, key) && key !== except)
45
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
46
- }
47
- return to;
48
- };
49
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
50
- // If the importer is in node compatibility mode or this is not an ESM
51
- // file that has been converted to a CommonJS file using a Babel-
52
- // compatible transform (i.e. "__esModule" has not been set), then set
53
- // "default" to the CommonJS "module.exports" for node compatibility.
54
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
55
- mod
56
- ));
57
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
58
- var __async = (__this, __arguments, generator) => {
59
- return new Promise((resolve, reject) => {
60
- var fulfilled = (value) => {
61
- try {
62
- step(generator.next(value));
63
- } catch (e) {
64
- reject(e);
65
- }
7
+ var __webpack_module_cache__ = {};
8
+ function __webpack_require__(moduleId) {
9
+ var cachedModule = __webpack_module_cache__[moduleId];
10
+ if (void 0 !== cachedModule) return cachedModule.exports;
11
+ var module = __webpack_module_cache__[moduleId] = {
12
+ exports: {}
66
13
  };
67
- var rejected = (value) => {
68
- try {
69
- step(generator.throw(value));
70
- } catch (e) {
71
- reject(e);
72
- }
73
- };
74
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
75
- step((generator = generator.apply(__this, __arguments)).next());
76
- });
77
- };
78
-
79
- // src/index.ts
80
- var index_exports = {};
81
- __export(index_exports, {
82
- withPostHogConfig: () => withPostHogConfig
83
- });
84
- module.exports = __toCommonJS(index_exports);
85
-
86
- // src/webpack-plugin.ts
87
- var import_child_process = require("child_process");
88
- var import_path2 = __toESM(require("path"));
89
-
90
- // src/utils.ts
91
- var import_path = __toESM(require("path"));
92
- var import_fs = __toESM(require("fs"));
93
- function resolveBinaryPath(envPath, cwd, binName) {
94
- const envLocations = envPath.split(import_path.default.delimiter);
95
- const localLocations = buildLocalBinaryPaths(cwd);
96
- const directories = [.../* @__PURE__ */ new Set([...envLocations, ...localLocations])];
97
- for (const directory of directories) {
98
- const binaryPath = import_path.default.join(directory, binName);
99
- if (import_fs.default.existsSync(binaryPath)) {
100
- return binaryPath;
101
- }
102
- }
103
- throw new Error(`Binary ${binName} not found`);
14
+ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
15
+ return module.exports;
104
16
  }
105
- var buildLocalBinaryPaths = (cwd) => {
106
- const localPaths = getLocalPaths(import_path.default.resolve(cwd)).map(
107
- (localPath) => import_path.default.join(localPath, "node_modules/.bin")
108
- );
109
- return localPaths;
110
- };
111
- var getLocalPaths = (startPath) => {
112
- const paths = [];
113
- let currentPath = startPath;
114
- while (true) {
115
- paths.push(currentPath);
116
- const parentPath = import_path.default.resolve(currentPath, "..");
117
- if (parentPath === currentPath) {
118
- break;
119
- }
120
- currentPath = parentPath;
121
- }
122
- return paths;
123
- };
124
-
125
- // src/webpack-plugin.ts
126
- var SourcemapWebpackPlugin = class {
127
- constructor(posthogOptions, isServer, nextRuntime, distDir) {
128
- this.posthogOptions = posthogOptions;
129
- this.isServer = isServer;
130
- this.nextRuntime = nextRuntime;
131
- const resolvedDistDir = import_path2.default.resolve(distDir != null ? distDir : ".next");
132
- if (!this.posthogOptions.personalApiKey) {
133
- throw new Error(
134
- `Personal API key not provided. If you are using turbo, make sure to add env variables to your turbo config`
135
- );
136
- }
137
- if (!this.posthogOptions.envId) {
138
- throw new Error(
139
- `Environment ID not provided. If you are using turbo, make sure to add env variables to your turbo config`
140
- );
141
- }
142
- this.directory = this.isServer ? import_path2.default.join(resolvedDistDir, "server") : import_path2.default.join(resolvedDistDir, "static/chunks");
143
- }
144
- apply(compiler) {
145
- if (this.nextRuntime === "edge") {
146
- return;
147
- }
148
- const onDone = (_, callback) => __async(this, null, function* () {
149
- callback = callback || (() => {
150
- });
151
- try {
152
- yield this.runInject();
153
- yield this.runUpload();
154
- } catch (error) {
155
- const errorMessage = error instanceof Error ? error.message : error;
156
- return console.error("Error running PostHog sourcemap plugin:", errorMessage);
157
- }
158
- return callback();
159
- });
160
- if (compiler.hooks) {
161
- compiler.hooks.done.tapAsync("SourcemapWebpackPlugin", onDone);
162
- } else {
163
- compiler.plugin("done", onDone);
164
- }
165
- }
166
- runInject() {
167
- return __async(this, null, function* () {
168
- const cliOptions = [];
169
- cliOptions.push("sourcemap", "inject", "--directory", this.directory);
170
- yield callPosthogCli(cliOptions, process.env, this.posthogOptions.verbose);
171
- });
172
- }
173
- runUpload() {
174
- return __async(this, null, function* () {
175
- const cliOptions = [];
176
- if (this.posthogOptions.host) {
177
- cliOptions.push("--host", this.posthogOptions.host);
178
- }
179
- cliOptions.push("sourcemap", "upload");
180
- cliOptions.push("--directory", this.directory);
181
- if (this.posthogOptions.sourcemaps.project) {
182
- cliOptions.push("--project", this.posthogOptions.sourcemaps.project);
183
- }
184
- if (this.posthogOptions.sourcemaps.version) {
185
- cliOptions.push("--version", this.posthogOptions.sourcemaps.version);
186
- }
187
- if (this.posthogOptions.sourcemaps.deleteAfterUpload && !this.isServer) {
188
- cliOptions.push("--delete-after");
189
- }
190
- const envVars = __spreadProps(__spreadValues({}, process.env), {
191
- POSTHOG_CLI_TOKEN: this.posthogOptions.personalApiKey,
192
- POSTHOG_CLI_ENV_ID: this.posthogOptions.envId
193
- });
194
- yield callPosthogCli(cliOptions, envVars, this.posthogOptions.verbose);
195
- });
196
- }
197
- };
198
- function callPosthogCli(args, env, verbose) {
199
- return __async(this, null, function* () {
200
- var _a;
201
- let binaryLocation;
202
- try {
203
- binaryLocation = resolveBinaryPath((_a = process.env.PATH) != null ? _a : "", __dirname, "posthog-cli");
204
- } catch (e) {
205
- throw new Error(`Binary ${e} not found. Make sure postinstall script has been allowed for @posthog/cli`);
206
- }
207
- if (verbose) {
208
- console.log("running posthog-cli from ", binaryLocation);
209
- }
210
- const child = (0, import_child_process.spawn)(binaryLocation, [...args], {
211
- stdio: verbose ? "inherit" : "ignore",
212
- env,
213
- cwd: process.cwd()
214
- });
215
- yield new Promise((resolve, reject) => {
216
- child.on("close", (code) => {
217
- if (code === 0) {
218
- resolve();
219
- } else {
220
- reject(new Error(`Command failed with code ${code}`));
221
- }
222
- });
223
- child.on("error", (error) => {
224
- reject(error);
225
- });
226
- });
227
- });
228
- }
229
-
230
- // src/config.ts
231
- function withPostHogConfig(userNextConfig, posthogConfig) {
232
- const posthogNextConfigComplete = resolvePostHogConfig(posthogConfig);
233
- return (_0, _1) => __async(null, [_0, _1], function* (phase, { defaultConfig }) {
234
- const _a = yield resolveUserConfig(userNextConfig, phase, defaultConfig), {
235
- webpack: userWebPackConfig,
236
- distDir
237
- } = _a, userConfig = __objRest(_a, [
238
- "webpack",
239
- "distDir"
240
- ]);
241
- const defaultWebpackConfig = userWebPackConfig || ((config) => config);
242
- const sourceMapEnabled = posthogNextConfigComplete.sourcemaps.enabled;
243
- return __spreadProps(__spreadValues({}, userConfig), {
244
- distDir,
245
- productionBrowserSourceMaps: sourceMapEnabled,
246
- webpack: (config, options) => {
247
- const webpackConfig = defaultWebpackConfig(config, options);
248
- if (webpackConfig && options.isServer && sourceMapEnabled) {
249
- webpackConfig.devtool = "source-map";
250
- }
251
- if (sourceMapEnabled) {
252
- webpackConfig.plugins = webpackConfig.plugins || [];
253
- webpackConfig.plugins.push(
254
- new SourcemapWebpackPlugin(posthogNextConfigComplete, options.isServer, options.nextRuntime, distDir)
255
- );
256
- }
257
- return webpackConfig;
258
- }
259
- });
260
- });
261
- }
262
- function resolveUserConfig(userNextConfig, phase, defaultConfig) {
263
- if (typeof userNextConfig === "function") {
264
- const maybePromise = userNextConfig(phase, { defaultConfig });
265
- if (maybePromise instanceof Promise) {
266
- return maybePromise;
267
- } else {
268
- return Promise.resolve(maybePromise);
269
- }
270
- } else if (typeof userNextConfig === "object") {
271
- return Promise.resolve(userNextConfig);
272
- } else {
273
- throw new Error("Invalid user config");
274
- }
275
- }
276
- function resolvePostHogConfig(posthogProvidedConfig) {
277
- var _a, _b;
278
- const { personalApiKey, envId, host, verbose, sourcemaps = {} } = posthogProvidedConfig;
279
- return {
280
- personalApiKey,
281
- envId,
282
- host: host != null ? host : "https://us.posthog.com",
283
- verbose: verbose != null ? verbose : true,
284
- sourcemaps: {
285
- enabled: (_a = sourcemaps.enabled) != null ? _a : process.env.NODE_ENV == "production",
286
- project: sourcemaps.project,
287
- version: sourcemaps.version,
288
- deleteAfterUpload: (_b = sourcemaps.deleteAfterUpload) != null ? _b : true
289
- }
290
- };
291
- }
292
- // Annotate the CommonJS export names for ESM import in node:
293
- 0 && (module.exports = {
294
- withPostHogConfig
17
+ (()=>{
18
+ __webpack_require__.n = (module)=>{
19
+ var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
20
+ __webpack_require__.d(getter, {
21
+ a: getter
22
+ });
23
+ return getter;
24
+ };
25
+ })();
26
+ (()=>{
27
+ __webpack_require__.d = (exports1, definition)=>{
28
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
29
+ enumerable: true,
30
+ get: definition[key]
31
+ });
32
+ };
33
+ })();
34
+ (()=>{
35
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
36
+ })();
37
+ (()=>{
38
+ __webpack_require__.r = (exports1)=>{
39
+ if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
40
+ value: 'Module'
41
+ });
42
+ Object.defineProperty(exports1, '__esModule', {
43
+ value: true
44
+ });
45
+ };
46
+ })();
47
+ var __webpack_exports__ = {};
48
+ (()=>{
49
+ __webpack_require__.r(__webpack_exports__);
50
+ var _config__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("./config");
51
+ var __WEBPACK_REEXPORT_OBJECT__ = {};
52
+ for(var __WEBPACK_IMPORT_KEY__ in _config__WEBPACK_IMPORTED_MODULE_0__)if ("default" !== __WEBPACK_IMPORT_KEY__) __WEBPACK_REEXPORT_OBJECT__[__WEBPACK_IMPORT_KEY__] = (function(key) {
53
+ return _config__WEBPACK_IMPORTED_MODULE_0__[key];
54
+ }).bind(0, __WEBPACK_IMPORT_KEY__);
55
+ __webpack_require__.d(__webpack_exports__, __WEBPACK_REEXPORT_OBJECT__);
56
+ })();
57
+ for(var __webpack_i__ in __webpack_exports__)exports[__webpack_i__] = __webpack_exports__[__webpack_i__];
58
+ Object.defineProperty(exports, '__esModule', {
59
+ value: true
295
60
  });
package/dist/index.mjs CHANGED
@@ -1,261 +1 @@
1
- var __defProp = Object.defineProperty;
2
- var __defProps = Object.defineProperties;
3
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
- var __spreadValues = (a, b) => {
9
- for (var prop in b || (b = {}))
10
- if (__hasOwnProp.call(b, prop))
11
- __defNormalProp(a, prop, b[prop]);
12
- if (__getOwnPropSymbols)
13
- for (var prop of __getOwnPropSymbols(b)) {
14
- if (__propIsEnum.call(b, prop))
15
- __defNormalProp(a, prop, b[prop]);
16
- }
17
- return a;
18
- };
19
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
- var __objRest = (source, exclude) => {
21
- var target = {};
22
- for (var prop in source)
23
- if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
24
- target[prop] = source[prop];
25
- if (source != null && __getOwnPropSymbols)
26
- for (var prop of __getOwnPropSymbols(source)) {
27
- if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
28
- target[prop] = source[prop];
29
- }
30
- return target;
31
- };
32
- var __async = (__this, __arguments, generator) => {
33
- return new Promise((resolve, reject) => {
34
- var fulfilled = (value) => {
35
- try {
36
- step(generator.next(value));
37
- } catch (e) {
38
- reject(e);
39
- }
40
- };
41
- var rejected = (value) => {
42
- try {
43
- step(generator.throw(value));
44
- } catch (e) {
45
- reject(e);
46
- }
47
- };
48
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
49
- step((generator = generator.apply(__this, __arguments)).next());
50
- });
51
- };
52
-
53
- // src/webpack-plugin.ts
54
- import { spawn } from "child_process";
55
- import path2 from "path";
56
-
57
- // src/utils.ts
58
- import path from "path";
59
- import fs from "fs";
60
- function resolveBinaryPath(envPath, cwd, binName) {
61
- const envLocations = envPath.split(path.delimiter);
62
- const localLocations = buildLocalBinaryPaths(cwd);
63
- const directories = [.../* @__PURE__ */ new Set([...envLocations, ...localLocations])];
64
- for (const directory of directories) {
65
- const binaryPath = path.join(directory, binName);
66
- if (fs.existsSync(binaryPath)) {
67
- return binaryPath;
68
- }
69
- }
70
- throw new Error(`Binary ${binName} not found`);
71
- }
72
- var buildLocalBinaryPaths = (cwd) => {
73
- const localPaths = getLocalPaths(path.resolve(cwd)).map(
74
- (localPath) => path.join(localPath, "node_modules/.bin")
75
- );
76
- return localPaths;
77
- };
78
- var getLocalPaths = (startPath) => {
79
- const paths = [];
80
- let currentPath = startPath;
81
- while (true) {
82
- paths.push(currentPath);
83
- const parentPath = path.resolve(currentPath, "..");
84
- if (parentPath === currentPath) {
85
- break;
86
- }
87
- currentPath = parentPath;
88
- }
89
- return paths;
90
- };
91
-
92
- // src/webpack-plugin.ts
93
- var SourcemapWebpackPlugin = class {
94
- constructor(posthogOptions, isServer, nextRuntime, distDir) {
95
- this.posthogOptions = posthogOptions;
96
- this.isServer = isServer;
97
- this.nextRuntime = nextRuntime;
98
- const resolvedDistDir = path2.resolve(distDir != null ? distDir : ".next");
99
- if (!this.posthogOptions.personalApiKey) {
100
- throw new Error(
101
- `Personal API key not provided. If you are using turbo, make sure to add env variables to your turbo config`
102
- );
103
- }
104
- if (!this.posthogOptions.envId) {
105
- throw new Error(
106
- `Environment ID not provided. If you are using turbo, make sure to add env variables to your turbo config`
107
- );
108
- }
109
- this.directory = this.isServer ? path2.join(resolvedDistDir, "server") : path2.join(resolvedDistDir, "static/chunks");
110
- }
111
- apply(compiler) {
112
- if (this.nextRuntime === "edge") {
113
- return;
114
- }
115
- const onDone = (_, callback) => __async(this, null, function* () {
116
- callback = callback || (() => {
117
- });
118
- try {
119
- yield this.runInject();
120
- yield this.runUpload();
121
- } catch (error) {
122
- const errorMessage = error instanceof Error ? error.message : error;
123
- return console.error("Error running PostHog sourcemap plugin:", errorMessage);
124
- }
125
- return callback();
126
- });
127
- if (compiler.hooks) {
128
- compiler.hooks.done.tapAsync("SourcemapWebpackPlugin", onDone);
129
- } else {
130
- compiler.plugin("done", onDone);
131
- }
132
- }
133
- runInject() {
134
- return __async(this, null, function* () {
135
- const cliOptions = [];
136
- cliOptions.push("sourcemap", "inject", "--directory", this.directory);
137
- yield callPosthogCli(cliOptions, process.env, this.posthogOptions.verbose);
138
- });
139
- }
140
- runUpload() {
141
- return __async(this, null, function* () {
142
- const cliOptions = [];
143
- if (this.posthogOptions.host) {
144
- cliOptions.push("--host", this.posthogOptions.host);
145
- }
146
- cliOptions.push("sourcemap", "upload");
147
- cliOptions.push("--directory", this.directory);
148
- if (this.posthogOptions.sourcemaps.project) {
149
- cliOptions.push("--project", this.posthogOptions.sourcemaps.project);
150
- }
151
- if (this.posthogOptions.sourcemaps.version) {
152
- cliOptions.push("--version", this.posthogOptions.sourcemaps.version);
153
- }
154
- if (this.posthogOptions.sourcemaps.deleteAfterUpload && !this.isServer) {
155
- cliOptions.push("--delete-after");
156
- }
157
- const envVars = __spreadProps(__spreadValues({}, process.env), {
158
- POSTHOG_CLI_TOKEN: this.posthogOptions.personalApiKey,
159
- POSTHOG_CLI_ENV_ID: this.posthogOptions.envId
160
- });
161
- yield callPosthogCli(cliOptions, envVars, this.posthogOptions.verbose);
162
- });
163
- }
164
- };
165
- function callPosthogCli(args, env, verbose) {
166
- return __async(this, null, function* () {
167
- var _a;
168
- let binaryLocation;
169
- try {
170
- binaryLocation = resolveBinaryPath((_a = process.env.PATH) != null ? _a : "", __dirname, "posthog-cli");
171
- } catch (e) {
172
- throw new Error(`Binary ${e} not found. Make sure postinstall script has been allowed for @posthog/cli`);
173
- }
174
- if (verbose) {
175
- console.log("running posthog-cli from ", binaryLocation);
176
- }
177
- const child = spawn(binaryLocation, [...args], {
178
- stdio: verbose ? "inherit" : "ignore",
179
- env,
180
- cwd: process.cwd()
181
- });
182
- yield new Promise((resolve, reject) => {
183
- child.on("close", (code) => {
184
- if (code === 0) {
185
- resolve();
186
- } else {
187
- reject(new Error(`Command failed with code ${code}`));
188
- }
189
- });
190
- child.on("error", (error) => {
191
- reject(error);
192
- });
193
- });
194
- });
195
- }
196
-
197
- // src/config.ts
198
- function withPostHogConfig(userNextConfig, posthogConfig) {
199
- const posthogNextConfigComplete = resolvePostHogConfig(posthogConfig);
200
- return (_0, _1) => __async(null, [_0, _1], function* (phase, { defaultConfig }) {
201
- const _a = yield resolveUserConfig(userNextConfig, phase, defaultConfig), {
202
- webpack: userWebPackConfig,
203
- distDir
204
- } = _a, userConfig = __objRest(_a, [
205
- "webpack",
206
- "distDir"
207
- ]);
208
- const defaultWebpackConfig = userWebPackConfig || ((config) => config);
209
- const sourceMapEnabled = posthogNextConfigComplete.sourcemaps.enabled;
210
- return __spreadProps(__spreadValues({}, userConfig), {
211
- distDir,
212
- productionBrowserSourceMaps: sourceMapEnabled,
213
- webpack: (config, options) => {
214
- const webpackConfig = defaultWebpackConfig(config, options);
215
- if (webpackConfig && options.isServer && sourceMapEnabled) {
216
- webpackConfig.devtool = "source-map";
217
- }
218
- if (sourceMapEnabled) {
219
- webpackConfig.plugins = webpackConfig.plugins || [];
220
- webpackConfig.plugins.push(
221
- new SourcemapWebpackPlugin(posthogNextConfigComplete, options.isServer, options.nextRuntime, distDir)
222
- );
223
- }
224
- return webpackConfig;
225
- }
226
- });
227
- });
228
- }
229
- function resolveUserConfig(userNextConfig, phase, defaultConfig) {
230
- if (typeof userNextConfig === "function") {
231
- const maybePromise = userNextConfig(phase, { defaultConfig });
232
- if (maybePromise instanceof Promise) {
233
- return maybePromise;
234
- } else {
235
- return Promise.resolve(maybePromise);
236
- }
237
- } else if (typeof userNextConfig === "object") {
238
- return Promise.resolve(userNextConfig);
239
- } else {
240
- throw new Error("Invalid user config");
241
- }
242
- }
243
- function resolvePostHogConfig(posthogProvidedConfig) {
244
- var _a, _b;
245
- const { personalApiKey, envId, host, verbose, sourcemaps = {} } = posthogProvidedConfig;
246
- return {
247
- personalApiKey,
248
- envId,
249
- host: host != null ? host : "https://us.posthog.com",
250
- verbose: verbose != null ? verbose : true,
251
- sourcemaps: {
252
- enabled: (_a = sourcemaps.enabled) != null ? _a : process.env.NODE_ENV == "production",
253
- project: sourcemaps.project,
254
- version: sourcemaps.version,
255
- deleteAfterUpload: (_b = sourcemaps.deleteAfterUpload) != null ? _b : true
256
- }
257
- };
258
- }
259
- export {
260
- withPostHogConfig
261
- };
1
+ export * from "./config.mjs";
@@ -0,0 +1,3 @@
1
+ export declare function resolveBinaryPath(envPath: string, cwd: string, binName: string): string;
2
+ export declare const buildLocalBinaryPaths: (cwd: string) => string[];
3
+ export declare function callPosthogCli(args: string[], env: NodeJS.ProcessEnv, verbose: boolean): Promise<void>;
package/dist/utils.js ADDED
@@ -0,0 +1,111 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.n = (module)=>{
5
+ var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
6
+ __webpack_require__.d(getter, {
7
+ a: getter
8
+ });
9
+ return getter;
10
+ };
11
+ })();
12
+ (()=>{
13
+ __webpack_require__.d = (exports1, definition)=>{
14
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
15
+ enumerable: true,
16
+ get: definition[key]
17
+ });
18
+ };
19
+ })();
20
+ (()=>{
21
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
22
+ })();
23
+ (()=>{
24
+ __webpack_require__.r = (exports1)=>{
25
+ if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
26
+ value: 'Module'
27
+ });
28
+ Object.defineProperty(exports1, '__esModule', {
29
+ value: true
30
+ });
31
+ };
32
+ })();
33
+ var __webpack_exports__ = {};
34
+ __webpack_require__.r(__webpack_exports__);
35
+ __webpack_require__.d(__webpack_exports__, {
36
+ buildLocalBinaryPaths: ()=>buildLocalBinaryPaths,
37
+ resolveBinaryPath: ()=>resolveBinaryPath,
38
+ callPosthogCli: ()=>callPosthogCli
39
+ });
40
+ const external_path_namespaceObject = require("path");
41
+ var external_path_default = /*#__PURE__*/ __webpack_require__.n(external_path_namespaceObject);
42
+ const external_fs_namespaceObject = require("fs");
43
+ var external_fs_default = /*#__PURE__*/ __webpack_require__.n(external_fs_namespaceObject);
44
+ const external_child_process_namespaceObject = require("child_process");
45
+ function resolveBinaryPath(envPath, cwd, binName) {
46
+ const envLocations = envPath.split(external_path_default().delimiter);
47
+ const localLocations = buildLocalBinaryPaths(cwd);
48
+ const directories = [
49
+ ...new Set([
50
+ ...envLocations,
51
+ ...localLocations
52
+ ])
53
+ ];
54
+ for (const directory of directories){
55
+ const binaryPath = external_path_default().join(directory, binName);
56
+ if (external_fs_default().existsSync(binaryPath)) return binaryPath;
57
+ }
58
+ throw new Error(`Binary ${binName} not found`);
59
+ }
60
+ const buildLocalBinaryPaths = (cwd)=>{
61
+ const localPaths = getLocalPaths(external_path_default().resolve(cwd)).map((localPath)=>external_path_default().join(localPath, 'node_modules/.bin'));
62
+ return localPaths;
63
+ };
64
+ const getLocalPaths = (startPath)=>{
65
+ const paths = [];
66
+ let currentPath = startPath;
67
+ while(true){
68
+ paths.push(currentPath);
69
+ const parentPath = external_path_default().resolve(currentPath, '..');
70
+ if (parentPath === currentPath) break;
71
+ currentPath = parentPath;
72
+ }
73
+ return paths;
74
+ };
75
+ async function callPosthogCli(args, env, verbose) {
76
+ let binaryLocation;
77
+ try {
78
+ var _process_env_PATH;
79
+ binaryLocation = resolveBinaryPath(null != (_process_env_PATH = process.env.PATH) ? _process_env_PATH : '', __dirname, 'posthog-cli');
80
+ } catch (e) {
81
+ throw new Error(`Binary ${e} not found. Make sure postinstall script has been allowed for @posthog/cli`);
82
+ }
83
+ if (verbose) console.log('running posthog-cli from ', binaryLocation);
84
+ const child = (0, external_child_process_namespaceObject.spawn)(binaryLocation, [
85
+ ...args
86
+ ], {
87
+ stdio: verbose ? 'inherit' : 'ignore',
88
+ env,
89
+ cwd: process.cwd()
90
+ });
91
+ await new Promise((resolve, reject)=>{
92
+ child.on('close', (code)=>{
93
+ if (0 === code) resolve();
94
+ else reject(new Error(`Command failed with code ${code}`));
95
+ });
96
+ child.on('error', (error)=>{
97
+ reject(error);
98
+ });
99
+ });
100
+ }
101
+ exports.buildLocalBinaryPaths = __webpack_exports__.buildLocalBinaryPaths;
102
+ exports.callPosthogCli = __webpack_exports__.callPosthogCli;
103
+ exports.resolveBinaryPath = __webpack_exports__.resolveBinaryPath;
104
+ for(var __webpack_i__ in __webpack_exports__)if (-1 === [
105
+ "buildLocalBinaryPaths",
106
+ "callPosthogCli",
107
+ "resolveBinaryPath"
108
+ ].indexOf(__webpack_i__)) exports[__webpack_i__] = __webpack_exports__[__webpack_i__];
109
+ Object.defineProperty(exports, '__esModule', {
110
+ value: true
111
+ });
package/dist/utils.mjs ADDED
@@ -0,0 +1,63 @@
1
+ import { fileURLToPath as __webpack_fileURLToPath__ } from "node:url";
2
+ import { dirname as __webpack_dirname__ } from "node:path";
3
+ import path from "path";
4
+ import fs from "fs";
5
+ import { spawn } from "child_process";
6
+ var utils_dirname = __webpack_dirname__(__webpack_fileURLToPath__(import.meta.url));
7
+ function resolveBinaryPath(envPath, cwd, binName) {
8
+ const envLocations = envPath.split(path.delimiter);
9
+ const localLocations = buildLocalBinaryPaths(cwd);
10
+ const directories = [
11
+ ...new Set([
12
+ ...envLocations,
13
+ ...localLocations
14
+ ])
15
+ ];
16
+ for (const directory of directories){
17
+ const binaryPath = path.join(directory, binName);
18
+ if (fs.existsSync(binaryPath)) return binaryPath;
19
+ }
20
+ throw new Error(`Binary ${binName} not found`);
21
+ }
22
+ const buildLocalBinaryPaths = (cwd)=>{
23
+ const localPaths = getLocalPaths(path.resolve(cwd)).map((localPath)=>path.join(localPath, 'node_modules/.bin'));
24
+ return localPaths;
25
+ };
26
+ const getLocalPaths = (startPath)=>{
27
+ const paths = [];
28
+ let currentPath = startPath;
29
+ while(true){
30
+ paths.push(currentPath);
31
+ const parentPath = path.resolve(currentPath, '..');
32
+ if (parentPath === currentPath) break;
33
+ currentPath = parentPath;
34
+ }
35
+ return paths;
36
+ };
37
+ async function callPosthogCli(args, env, verbose) {
38
+ let binaryLocation;
39
+ try {
40
+ var _process_env_PATH;
41
+ binaryLocation = resolveBinaryPath(null != (_process_env_PATH = process.env.PATH) ? _process_env_PATH : '', utils_dirname, 'posthog-cli');
42
+ } catch (e) {
43
+ throw new Error(`Binary ${e} not found. Make sure postinstall script has been allowed for @posthog/cli`);
44
+ }
45
+ if (verbose) console.log('running posthog-cli from ', binaryLocation);
46
+ const child = spawn(binaryLocation, [
47
+ ...args
48
+ ], {
49
+ stdio: verbose ? 'inherit' : 'ignore',
50
+ env,
51
+ cwd: process.cwd()
52
+ });
53
+ await new Promise((resolve, reject)=>{
54
+ child.on('close', (code)=>{
55
+ if (0 === code) resolve();
56
+ else reject(new Error(`Command failed with code ${code}`));
57
+ });
58
+ child.on('error', (error)=>{
59
+ reject(error);
60
+ });
61
+ });
62
+ }
63
+ export { buildLocalBinaryPaths, callPosthogCli, resolveBinaryPath };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ var __webpack_exports__ = {};
3
+ const external_utils_js_namespaceObject = require("./utils.js");
4
+ describe('buildLocalBinaryPaths', ()=>{
5
+ it('generates possible binary locations', ()=>{
6
+ const cwd = '/home/user';
7
+ const result = (0, external_utils_js_namespaceObject.buildLocalBinaryPaths)(cwd);
8
+ expect(result.includes('/home/user/node_modules/.bin')).toBe(true);
9
+ expect(result.includes('/home/node_modules/.bin')).toBe(true);
10
+ expect(result.includes('/node_modules/.bin')).toBe(true);
11
+ });
12
+ });
13
+ for(var __webpack_i__ in __webpack_exports__)exports[__webpack_i__] = __webpack_exports__[__webpack_i__];
14
+ Object.defineProperty(exports, '__esModule', {
15
+ value: true
16
+ });
@@ -0,0 +1,10 @@
1
+ import { buildLocalBinaryPaths } from "./utils.mjs";
2
+ describe('buildLocalBinaryPaths', ()=>{
3
+ it('generates possible binary locations', ()=>{
4
+ const cwd = '/home/user';
5
+ const result = buildLocalBinaryPaths(cwd);
6
+ expect(result.includes('/home/user/node_modules/.bin')).toBe(true);
7
+ expect(result.includes('/home/node_modules/.bin')).toBe(true);
8
+ expect(result.includes('/node_modules/.bin')).toBe(true);
9
+ });
10
+ });
@@ -0,0 +1,13 @@
1
+ import { PostHogNextConfigComplete } from './config';
2
+ type NextRuntime = 'edge' | 'nodejs' | undefined;
3
+ export declare class SourcemapWebpackPlugin {
4
+ private posthogOptions;
5
+ private isServer;
6
+ private nextRuntime;
7
+ directory: string;
8
+ constructor(posthogOptions: PostHogNextConfigComplete, isServer: boolean, nextRuntime: NextRuntime, distDir?: string);
9
+ apply(compiler: any): void;
10
+ runInject(): Promise<void>;
11
+ runUpload(): Promise<void>;
12
+ }
13
+ export {};
@@ -0,0 +1,94 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.n = (module)=>{
5
+ var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
6
+ __webpack_require__.d(getter, {
7
+ a: getter
8
+ });
9
+ return getter;
10
+ };
11
+ })();
12
+ (()=>{
13
+ __webpack_require__.d = (exports1, definition)=>{
14
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
15
+ enumerable: true,
16
+ get: definition[key]
17
+ });
18
+ };
19
+ })();
20
+ (()=>{
21
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
22
+ })();
23
+ (()=>{
24
+ __webpack_require__.r = (exports1)=>{
25
+ if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
26
+ value: 'Module'
27
+ });
28
+ Object.defineProperty(exports1, '__esModule', {
29
+ value: true
30
+ });
31
+ };
32
+ })();
33
+ var __webpack_exports__ = {};
34
+ __webpack_require__.r(__webpack_exports__);
35
+ __webpack_require__.d(__webpack_exports__, {
36
+ SourcemapWebpackPlugin: ()=>SourcemapWebpackPlugin
37
+ });
38
+ const external_path_namespaceObject = require("path");
39
+ var external_path_default = /*#__PURE__*/ __webpack_require__.n(external_path_namespaceObject);
40
+ const external_utils_js_namespaceObject = require("./utils.js");
41
+ class SourcemapWebpackPlugin {
42
+ apply(compiler) {
43
+ if ('edge' === this.nextRuntime) return;
44
+ const onDone = async (_, callback)=>{
45
+ callback = callback || (()=>{});
46
+ try {
47
+ await this.runInject();
48
+ await this.runUpload();
49
+ } catch (error) {
50
+ const errorMessage = error instanceof Error ? error.message : error;
51
+ return console.error('Error running PostHog sourcemap plugin:', errorMessage);
52
+ }
53
+ return callback();
54
+ };
55
+ if (compiler.hooks) compiler.hooks.done.tapAsync('SourcemapWebpackPlugin', onDone);
56
+ else compiler.plugin('done', onDone);
57
+ }
58
+ async runInject() {
59
+ const cliOptions = [];
60
+ cliOptions.push('sourcemap', 'inject', '--directory', this.directory);
61
+ await (0, external_utils_js_namespaceObject.callPosthogCli)(cliOptions, process.env, this.posthogOptions.verbose);
62
+ }
63
+ async runUpload() {
64
+ const cliOptions = [];
65
+ if (this.posthogOptions.host) cliOptions.push('--host', this.posthogOptions.host);
66
+ cliOptions.push('sourcemap', 'upload');
67
+ cliOptions.push('--directory', this.directory);
68
+ if (this.posthogOptions.sourcemaps.project) cliOptions.push('--project', this.posthogOptions.sourcemaps.project);
69
+ if (this.posthogOptions.sourcemaps.version) cliOptions.push('--version', this.posthogOptions.sourcemaps.version);
70
+ if (this.posthogOptions.sourcemaps.deleteAfterUpload && !this.isServer) cliOptions.push('--delete-after');
71
+ const envVars = {
72
+ ...process.env,
73
+ POSTHOG_CLI_TOKEN: this.posthogOptions.personalApiKey,
74
+ POSTHOG_CLI_ENV_ID: this.posthogOptions.envId
75
+ };
76
+ await (0, external_utils_js_namespaceObject.callPosthogCli)(cliOptions, envVars, this.posthogOptions.verbose);
77
+ }
78
+ constructor(posthogOptions, isServer, nextRuntime, distDir){
79
+ this.posthogOptions = posthogOptions;
80
+ this.isServer = isServer;
81
+ this.nextRuntime = nextRuntime;
82
+ const resolvedDistDir = external_path_default().resolve(null != distDir ? distDir : '.next');
83
+ if (!this.posthogOptions.personalApiKey) throw new Error("Personal API key not provided. If you are using turbo, make sure to add env variables to your turbo config");
84
+ if (!this.posthogOptions.envId) throw new Error("Environment ID not provided. If you are using turbo, make sure to add env variables to your turbo config");
85
+ this.directory = this.isServer ? external_path_default().join(resolvedDistDir, 'server') : external_path_default().join(resolvedDistDir, 'static/chunks');
86
+ }
87
+ }
88
+ exports.SourcemapWebpackPlugin = __webpack_exports__.SourcemapWebpackPlugin;
89
+ for(var __webpack_i__ in __webpack_exports__)if (-1 === [
90
+ "SourcemapWebpackPlugin"
91
+ ].indexOf(__webpack_i__)) exports[__webpack_i__] = __webpack_exports__[__webpack_i__];
92
+ Object.defineProperty(exports, '__esModule', {
93
+ value: true
94
+ });
@@ -0,0 +1,50 @@
1
+ import path from "path";
2
+ import { callPosthogCli } from "./utils.mjs";
3
+ class SourcemapWebpackPlugin {
4
+ apply(compiler) {
5
+ if ('edge' === this.nextRuntime) return;
6
+ const onDone = async (_, callback)=>{
7
+ callback = callback || (()=>{});
8
+ try {
9
+ await this.runInject();
10
+ await this.runUpload();
11
+ } catch (error) {
12
+ const errorMessage = error instanceof Error ? error.message : error;
13
+ return console.error('Error running PostHog sourcemap plugin:', errorMessage);
14
+ }
15
+ return callback();
16
+ };
17
+ if (compiler.hooks) compiler.hooks.done.tapAsync('SourcemapWebpackPlugin', onDone);
18
+ else compiler.plugin('done', onDone);
19
+ }
20
+ async runInject() {
21
+ const cliOptions = [];
22
+ cliOptions.push('sourcemap', 'inject', '--directory', this.directory);
23
+ await callPosthogCli(cliOptions, process.env, this.posthogOptions.verbose);
24
+ }
25
+ async runUpload() {
26
+ const cliOptions = [];
27
+ if (this.posthogOptions.host) cliOptions.push('--host', this.posthogOptions.host);
28
+ cliOptions.push('sourcemap', 'upload');
29
+ cliOptions.push('--directory', this.directory);
30
+ if (this.posthogOptions.sourcemaps.project) cliOptions.push('--project', this.posthogOptions.sourcemaps.project);
31
+ if (this.posthogOptions.sourcemaps.version) cliOptions.push('--version', this.posthogOptions.sourcemaps.version);
32
+ if (this.posthogOptions.sourcemaps.deleteAfterUpload && !this.isServer) cliOptions.push('--delete-after');
33
+ const envVars = {
34
+ ...process.env,
35
+ POSTHOG_CLI_TOKEN: this.posthogOptions.personalApiKey,
36
+ POSTHOG_CLI_ENV_ID: this.posthogOptions.envId
37
+ };
38
+ await callPosthogCli(cliOptions, envVars, this.posthogOptions.verbose);
39
+ }
40
+ constructor(posthogOptions, isServer, nextRuntime, distDir){
41
+ this.posthogOptions = posthogOptions;
42
+ this.isServer = isServer;
43
+ this.nextRuntime = nextRuntime;
44
+ const resolvedDistDir = path.resolve(null != distDir ? distDir : '.next');
45
+ if (!this.posthogOptions.personalApiKey) throw new Error("Personal API key not provided. If you are using turbo, make sure to add env variables to your turbo config");
46
+ if (!this.posthogOptions.envId) throw new Error("Environment ID not provided. If you are using turbo, make sure to add env variables to your turbo config");
47
+ this.directory = this.isServer ? path.join(resolvedDistDir, 'server') : path.join(resolvedDistDir, 'static/chunks');
48
+ }
49
+ }
50
+ export { SourcemapWebpackPlugin };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@posthog/nextjs-config",
3
- "version": "1.1.0",
3
+ "version": "1.1.1",
4
4
  "description": "NextJS configuration helper for Posthog 🦔",
5
5
  "repository": {
6
6
  "type": "git",
@@ -39,9 +39,11 @@
39
39
  "nextjs"
40
40
  ],
41
41
  "devDependencies": {
42
+ "@rslib/core": "^0.10.5",
42
43
  "@types/node": "^22.15.23",
43
44
  "next": "^12.1.0",
44
- "tsup": "^8.5.0",
45
+ "jest": "^29.7.0",
46
+ "ts-jest": "29.4.0",
45
47
  "@posthog-tooling/tsconfig-base": "1.0.0",
46
48
  "@posthog-tooling/rollup-utils": "1.0.0"
47
49
  },
@@ -55,8 +57,9 @@
55
57
  "clean": "rimraf dist",
56
58
  "lint": "eslint src",
57
59
  "lint:fix": "eslint src --fix",
58
- "build": "tsup src/index.ts --format cjs,esm --dts --out-dir dist",
59
- "dev": "tsup src/index.ts --format cjs,esm --dts --out-dir dist --watch",
60
+ "build": "rslib build",
61
+ "test:unit": "jest",
62
+ "dev": "rslib build --watch",
60
63
  "package": "pnpm pack --out $PACKAGE_DEST/%s.tgz"
61
64
  }
62
65
  }