@posthog/wizard 0.7.0 β†’ 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/dist/bin.d.ts +2 -0
  2. package/dist/bin.js +28 -0
  3. package/dist/bin.js.map +1 -0
  4. package/dist/src/lib/config.d.ts +49 -0
  5. package/dist/src/lib/config.js +85 -0
  6. package/dist/src/lib/config.js.map +1 -0
  7. package/dist/src/lib/constants.d.ts +25 -0
  8. package/dist/src/lib/constants.js +45 -0
  9. package/dist/src/lib/constants.js.map +1 -0
  10. package/dist/src/lib/messages.d.ts +17 -0
  11. package/dist/src/lib/messages.js +68 -0
  12. package/dist/src/lib/messages.js.map +1 -0
  13. package/dist/src/lib/prompts.d.ts +16 -0
  14. package/dist/src/lib/prompts.js +83 -0
  15. package/dist/src/lib/prompts.js.map +1 -0
  16. package/dist/src/nextjs/docs.d.ts +8 -0
  17. package/dist/src/nextjs/docs.js +257 -0
  18. package/dist/src/nextjs/docs.js.map +1 -0
  19. package/dist/src/nextjs/nextjs-wizard.d.ts +2 -0
  20. package/dist/src/nextjs/nextjs-wizard.js +136 -0
  21. package/dist/src/nextjs/nextjs-wizard.js.map +1 -0
  22. package/dist/src/nextjs/utils.d.ts +9 -0
  23. package/dist/src/nextjs/utils.js +83 -0
  24. package/dist/src/nextjs/utils.js.map +1 -0
  25. package/dist/src/react/docs.d.ts +4 -0
  26. package/dist/src/react/docs.js +46 -0
  27. package/dist/src/react/docs.js.map +1 -0
  28. package/dist/src/react/react-wizard.d.ts +2 -0
  29. package/dist/src/react/react-wizard.js +115 -0
  30. package/dist/src/react/react-wizard.js.map +1 -0
  31. package/dist/src/react-native/docs.d.ts +5 -0
  32. package/dist/src/react-native/docs.js +31 -0
  33. package/dist/src/react-native/docs.js.map +1 -0
  34. package/dist/src/react-native/react-native-wizard.d.ts +2 -0
  35. package/dist/src/react-native/react-native-wizard.js +124 -0
  36. package/dist/src/react-native/react-native-wizard.js.map +1 -0
  37. package/dist/src/run.d.ts +13 -0
  38. package/dist/src/run.js +85 -0
  39. package/dist/src/run.js.map +1 -0
  40. package/dist/src/steps/__tests__/add-editor-rules.test.d.ts +1 -0
  41. package/dist/src/steps/__tests__/add-editor-rules.test.js +218 -0
  42. package/dist/src/steps/__tests__/add-editor-rules.test.js.map +1 -0
  43. package/dist/src/steps/__tests__/create-pr.test.d.ts +1 -0
  44. package/dist/src/steps/__tests__/create-pr.test.js +193 -0
  45. package/dist/src/steps/__tests__/create-pr.test.js.map +1 -0
  46. package/dist/src/steps/add-editor-rules.d.ts +9 -0
  47. package/dist/src/steps/add-editor-rules.js +92 -0
  48. package/dist/src/steps/add-editor-rules.js.map +1 -0
  49. package/dist/src/steps/add-or-update-environment-variables.d.ts +10 -0
  50. package/dist/src/steps/add-or-update-environment-variables.js +194 -0
  51. package/dist/src/steps/add-or-update-environment-variables.js.map +1 -0
  52. package/dist/src/steps/create-pr.d.ts +27 -0
  53. package/dist/src/steps/create-pr.js +305 -0
  54. package/dist/src/steps/create-pr.js.map +1 -0
  55. package/dist/src/steps/index.d.ts +4 -0
  56. package/dist/src/steps/index.js +21 -0
  57. package/dist/src/steps/index.js.map +1 -0
  58. package/dist/src/steps/run-prettier.d.ts +5 -0
  59. package/dist/src/steps/run-prettier.js +93 -0
  60. package/dist/src/steps/run-prettier.js.map +1 -0
  61. package/dist/src/steps/upload-environment-variables/EnvironmentProvider.d.ts +8 -0
  62. package/dist/src/steps/upload-environment-variables/EnvironmentProvider.js +12 -0
  63. package/dist/src/steps/upload-environment-variables/EnvironmentProvider.js.map +1 -0
  64. package/dist/src/steps/upload-environment-variables/index.d.ts +6 -0
  65. package/dist/src/steps/upload-environment-variables/index.js +66 -0
  66. package/dist/src/steps/upload-environment-variables/index.js.map +1 -0
  67. package/dist/src/steps/upload-environment-variables/providers/__tests__/vercel.test.d.ts +1 -0
  68. package/dist/src/steps/upload-environment-variables/providers/__tests__/vercel.test.js +117 -0
  69. package/dist/src/steps/upload-environment-variables/providers/__tests__/vercel.test.js.map +1 -0
  70. package/dist/src/steps/upload-environment-variables/providers/vercel.d.ts +14 -0
  71. package/dist/src/steps/upload-environment-variables/providers/vercel.js +146 -0
  72. package/dist/src/steps/upload-environment-variables/providers/vercel.js.map +1 -0
  73. package/dist/src/svelte/docs.d.ts +3 -0
  74. package/dist/src/svelte/docs.js +110 -0
  75. package/dist/src/svelte/docs.js.map +1 -0
  76. package/dist/src/svelte/svelte-wizard.d.ts +2 -0
  77. package/dist/src/svelte/svelte-wizard.js +115 -0
  78. package/dist/src/svelte/svelte-wizard.js.map +1 -0
  79. package/dist/src/telemetry.d.ts +2 -0
  80. package/dist/src/telemetry.js +13 -0
  81. package/dist/src/telemetry.js.map +1 -0
  82. package/dist/src/utils/__tests__/clack-utils.test.d.ts +1 -0
  83. package/dist/src/utils/__tests__/clack-utils.test.js +128 -0
  84. package/dist/src/utils/__tests__/clack-utils.test.js.map +1 -0
  85. package/dist/src/utils/analytics.d.ts +12 -0
  86. package/dist/src/utils/analytics.js +59 -0
  87. package/dist/src/utils/analytics.js.map +1 -0
  88. package/dist/src/utils/bash.d.ts +2 -0
  89. package/dist/src/utils/bash.js +54 -0
  90. package/dist/src/utils/bash.js.map +1 -0
  91. package/dist/src/utils/clack-utils.d.ts +180 -0
  92. package/dist/src/utils/clack-utils.js +634 -0
  93. package/dist/src/utils/clack-utils.js.map +1 -0
  94. package/dist/src/utils/clack.d.ts +2 -0
  95. package/dist/src/utils/clack.js +9 -0
  96. package/dist/src/utils/clack.js.map +1 -0
  97. package/dist/src/utils/debug.d.ts +2 -0
  98. package/dist/src/utils/debug.js +22 -0
  99. package/dist/src/utils/debug.js.map +1 -0
  100. package/dist/src/utils/environment.d.ts +3 -0
  101. package/dist/src/utils/environment.js +64 -0
  102. package/dist/src/utils/environment.js.map +1 -0
  103. package/dist/src/utils/file-utils.d.ts +29 -0
  104. package/dist/src/utils/file-utils.js +177 -0
  105. package/dist/src/utils/file-utils.js.map +1 -0
  106. package/dist/src/utils/logging.d.ts +9 -0
  107. package/dist/src/utils/logging.js +50 -0
  108. package/dist/src/utils/logging.js.map +1 -0
  109. package/dist/src/utils/package-json.d.ts +25 -0
  110. package/dist/src/utils/package-json.js +27 -0
  111. package/dist/src/utils/package-json.js.map +1 -0
  112. package/dist/src/utils/package-manager.d.ts +21 -0
  113. package/dist/src/utils/package-manager.js +208 -0
  114. package/dist/src/utils/package-manager.js.map +1 -0
  115. package/dist/src/utils/query.d.ts +8 -0
  116. package/dist/src/utils/query.js +27 -0
  117. package/dist/src/utils/query.js.map +1 -0
  118. package/dist/src/utils/rules/next-rules.md +9 -0
  119. package/dist/src/utils/rules/react-native-rules.md +7 -0
  120. package/dist/src/utils/rules/react-rules.md +7 -0
  121. package/dist/src/utils/rules/svelte-rules.md +7 -0
  122. package/dist/src/utils/rules/universal.md +20 -0
  123. package/dist/src/utils/semver.d.ts +5 -0
  124. package/dist/src/utils/semver.js +25 -0
  125. package/dist/src/utils/semver.js.map +1 -0
  126. package/dist/src/utils/string.d.ts +1 -0
  127. package/dist/src/utils/string.js +9 -0
  128. package/dist/src/utils/string.js.map +1 -0
  129. package/dist/src/utils/types.d.ts +48 -0
  130. package/dist/src/utils/types.js +3 -0
  131. package/dist/src/utils/types.js.map +1 -0
  132. package/dist/src/utils/urls.d.ts +4 -0
  133. package/dist/src/utils/urls.js +35 -0
  134. package/dist/src/utils/urls.js.map +1 -0
  135. package/dist/src/utils/vendor/is-unicorn-supported.d.ts +1 -0
  136. package/dist/src/utils/vendor/is-unicorn-supported.js +24 -0
  137. package/dist/src/utils/vendor/is-unicorn-supported.js.map +1 -0
  138. package/package.json +5 -1
@@ -0,0 +1,634 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.abort = abort;
40
+ exports.abortIfCancelled = abortIfCancelled;
41
+ exports.printWelcome = printWelcome;
42
+ exports.confirmContinueIfNoOrDirtyGitRepo = confirmContinueIfNoOrDirtyGitRepo;
43
+ exports.isInGitRepo = isInGitRepo;
44
+ exports.getUncommittedOrUntrackedFiles = getUncommittedOrUntrackedFiles;
45
+ exports.askForItemSelection = askForItemSelection;
46
+ exports.confirmContinueIfPackageVersionNotSupported = confirmContinueIfPackageVersionNotSupported;
47
+ exports.installPackage = installPackage;
48
+ exports.ensurePackageIsInstalled = ensurePackageIsInstalled;
49
+ exports.getPackageDotJson = getPackageDotJson;
50
+ exports.updatePackageDotJson = updatePackageDotJson;
51
+ exports.getPackageManager = getPackageManager;
52
+ exports.isUsingTypeScript = isUsingTypeScript;
53
+ exports.getOrAskForProjectData = getOrAskForProjectData;
54
+ exports.askForToolConfigPath = askForToolConfigPath;
55
+ exports.showCopyPasteInstructions = showCopyPasteInstructions;
56
+ exports.makeCodeSnippet = makeCodeSnippet;
57
+ exports.createNewConfigFile = createNewConfigFile;
58
+ exports.featureSelectionPrompt = featureSelectionPrompt;
59
+ exports.askShouldInstallPackage = askShouldInstallPackage;
60
+ exports.askShouldAddPackageOverride = askShouldAddPackageOverride;
61
+ exports.askForAIConsent = askForAIConsent;
62
+ exports.askForCloudRegion = askForCloudRegion;
63
+ const childProcess = __importStar(require("node:child_process"));
64
+ const fs = __importStar(require("node:fs"));
65
+ const os = __importStar(require("node:os"));
66
+ const node_path_1 = require("node:path");
67
+ const node_timers_1 = require("node:timers");
68
+ const node_url_1 = require("node:url");
69
+ const axios_1 = __importDefault(require("axios"));
70
+ const chalk_1 = __importDefault(require("chalk"));
71
+ const opn_1 = __importDefault(require("opn"));
72
+ const telemetry_1 = require("../telemetry");
73
+ const debug_1 = require("./debug");
74
+ const package_json_1 = require("./package-json");
75
+ const package_manager_1 = require("./package-manager");
76
+ const semver_1 = require("./semver");
77
+ const constants_1 = require("../lib/constants");
78
+ const analytics_1 = require("./analytics");
79
+ const clack_1 = __importDefault(require("./clack"));
80
+ const urls_1 = require("./urls");
81
+ async function abort(message, status) {
82
+ await analytics_1.analytics.shutdown('cancelled');
83
+ clack_1.default.outro(message ?? 'Wizard setup cancelled.');
84
+ return process.exit(status ?? 1);
85
+ }
86
+ async function abortIfCancelled(input) {
87
+ await analytics_1.analytics.shutdown('cancelled');
88
+ if (clack_1.default.isCancel(await input)) {
89
+ clack_1.default.cancel('Wizard setup cancelled.');
90
+ process.exit(0);
91
+ }
92
+ else {
93
+ return input;
94
+ }
95
+ }
96
+ function printWelcome(options) {
97
+ // eslint-disable-next-line no-console
98
+ console.log('');
99
+ clack_1.default.intro(chalk_1.default.inverse(` ${options.wizardName} `));
100
+ const welcomeText = options.message ||
101
+ `The ${options.wizardName} will help you set up PostHog for your application.\nThank you for using PostHog :)`;
102
+ clack_1.default.note(welcomeText);
103
+ }
104
+ async function confirmContinueIfNoOrDirtyGitRepo(options) {
105
+ return (0, telemetry_1.traceStep)('check-git-status', async () => {
106
+ if (!isInGitRepo()) {
107
+ const continueWithoutGit = options.default
108
+ ? true
109
+ : await abortIfCancelled(clack_1.default.confirm({
110
+ message: 'You are not inside a git repository. The wizard will create and update files. Do you want to continue anyway?',
111
+ }));
112
+ analytics_1.analytics.setTag('continue-without-git', continueWithoutGit);
113
+ if (!continueWithoutGit) {
114
+ await abort(undefined, 0);
115
+ }
116
+ // return early to avoid checking for uncommitted files
117
+ return;
118
+ }
119
+ const uncommittedOrUntrackedFiles = getUncommittedOrUntrackedFiles();
120
+ if (uncommittedOrUntrackedFiles.length) {
121
+ clack_1.default.log.warn(`You have uncommitted or untracked files in your repo:
122
+
123
+ ${uncommittedOrUntrackedFiles.join('\n')}
124
+
125
+ The wizard will create and update files.`);
126
+ const continueWithDirtyRepo = options.default
127
+ ? true
128
+ : await abortIfCancelled(clack_1.default.confirm({
129
+ message: 'Do you want to continue anyway?',
130
+ }));
131
+ analytics_1.analytics.setTag('continue-with-dirty-repo', continueWithDirtyRepo);
132
+ if (!continueWithDirtyRepo) {
133
+ await abort(undefined, 0);
134
+ }
135
+ }
136
+ });
137
+ }
138
+ function isInGitRepo() {
139
+ try {
140
+ childProcess.execSync('git rev-parse --is-inside-work-tree', {
141
+ stdio: 'ignore',
142
+ });
143
+ return true;
144
+ }
145
+ catch {
146
+ return false;
147
+ }
148
+ }
149
+ function getUncommittedOrUntrackedFiles() {
150
+ try {
151
+ const gitStatus = childProcess
152
+ .execSync('git status --porcelain=v1', {
153
+ // we only care about stdout
154
+ stdio: ['ignore', 'pipe', 'ignore'],
155
+ })
156
+ .toString();
157
+ const files = gitStatus
158
+ .split(os.EOL)
159
+ .map((line) => line.trim())
160
+ .filter(Boolean)
161
+ .map((f) => `- ${f.split(/\s+/)[1]}`);
162
+ return files;
163
+ }
164
+ catch {
165
+ return [];
166
+ }
167
+ }
168
+ async function askForItemSelection(items, message) {
169
+ const selection = await abortIfCancelled(clack_1.default.select({
170
+ maxItems: 12,
171
+ message: message,
172
+ options: items.map((item, index) => {
173
+ return {
174
+ value: { value: item, index: index },
175
+ label: item,
176
+ };
177
+ }),
178
+ }));
179
+ return selection;
180
+ }
181
+ async function confirmContinueIfPackageVersionNotSupported({ packageId, packageName, packageVersion, acceptableVersions, note, }) {
182
+ return (0, telemetry_1.traceStep)(`check-package-version`, async () => {
183
+ analytics_1.analytics.setTag(`${packageName.toLowerCase()}-version`, packageVersion);
184
+ const isSupportedVersion = (0, semver_1.fulfillsVersionRange)({
185
+ acceptableVersions,
186
+ version: packageVersion,
187
+ canBeLatest: true,
188
+ });
189
+ if (isSupportedVersion) {
190
+ analytics_1.analytics.setTag(`${packageName.toLowerCase()}-supported`, true);
191
+ return;
192
+ }
193
+ clack_1.default.log.warn(`You have an unsupported version of ${packageName} installed:
194
+
195
+ ${packageId}@${packageVersion}`);
196
+ clack_1.default.note(note ??
197
+ `Please upgrade to ${acceptableVersions} if you wish to use the PostHog Wizard.`);
198
+ const continueWithUnsupportedVersion = await abortIfCancelled(clack_1.default.confirm({
199
+ message: 'Do you want to continue anyway?',
200
+ }));
201
+ analytics_1.analytics.setTag(`${packageName.toLowerCase()}-continue-with-unsupported-version`, continueWithUnsupportedVersion);
202
+ if (!continueWithUnsupportedVersion) {
203
+ await abort(undefined, 0);
204
+ }
205
+ });
206
+ }
207
+ /**
208
+ * Installs or updates a package with the user's package manager.
209
+ *
210
+ * IMPORTANT: This function modifies the `package.json`! Be sure to re-read
211
+ * it if you make additional modifications to it after calling this function!
212
+ */
213
+ async function installPackage({ packageName, alreadyInstalled, askBeforeUpdating = true, packageNameDisplayLabel, packageManager, forceInstall = false, integration, installDir, }) {
214
+ return (0, telemetry_1.traceStep)('install-package', async () => {
215
+ if (alreadyInstalled && askBeforeUpdating) {
216
+ const shouldUpdatePackage = await abortIfCancelled(clack_1.default.confirm({
217
+ message: `The ${chalk_1.default.bold.cyan(packageNameDisplayLabel ?? packageName)} package is already installed. Do you want to update it to the latest version?`,
218
+ }));
219
+ if (!shouldUpdatePackage) {
220
+ return {};
221
+ }
222
+ }
223
+ const sdkInstallSpinner = clack_1.default.spinner();
224
+ const pkgManager = packageManager || (await getPackageManager({ installDir }));
225
+ sdkInstallSpinner.start(`${alreadyInstalled ? 'Updating' : 'Installing'} ${chalk_1.default.bold.cyan(packageNameDisplayLabel ?? packageName)} with ${chalk_1.default.bold(pkgManager.label)}.`);
226
+ try {
227
+ await new Promise((resolve, reject) => {
228
+ childProcess.exec(`${pkgManager.installCommand} ${packageName} ${pkgManager.flags} ${forceInstall ? pkgManager.forceInstallFlag : ''}`, { cwd: installDir }, (err, stdout, stderr) => {
229
+ if (err) {
230
+ // Write a log file so we can better troubleshoot issues
231
+ fs.writeFileSync((0, node_path_1.join)(process.cwd(), `posthog-wizard-installation-error-${Date.now()}.log`), JSON.stringify({
232
+ stdout,
233
+ stderr,
234
+ }), { encoding: 'utf8' });
235
+ reject(err);
236
+ }
237
+ else {
238
+ resolve();
239
+ }
240
+ });
241
+ });
242
+ }
243
+ catch (e) {
244
+ sdkInstallSpinner.stop('Installation failed.');
245
+ clack_1.default.log.error(`${chalk_1.default.red('Encountered the following error during installation:')}\n\n${e}\n\n${chalk_1.default.dim(`The wizard has created a \`posthog-wizard-installation-error-*.log\` file. If you think this issue is caused by the PostHog Wizard, create an issue on GitHub and include the log file's content:\n${constants_1.ISSUES_URL}`)}`);
246
+ await abort();
247
+ }
248
+ sdkInstallSpinner.stop(`${alreadyInstalled ? 'Updated' : 'Installed'} ${chalk_1.default.bold.cyan(packageNameDisplayLabel ?? packageName)} with ${chalk_1.default.bold(pkgManager.label)}.`);
249
+ analytics_1.analytics.capture('wizard interaction', {
250
+ action: 'package installed',
251
+ package_name: packageName,
252
+ package_manager: pkgManager.name,
253
+ integration,
254
+ });
255
+ return { packageManager: pkgManager };
256
+ });
257
+ }
258
+ /**
259
+ * Checks if @param packageId is listed as a dependency in @param packageJson.
260
+ * If not, it will ask users if they want to continue without the package.
261
+ *
262
+ * Use this function to check if e.g. a the framework of the SDK is installed
263
+ *
264
+ * @param packageJson the package.json object
265
+ * @param packageId the npm name of the package
266
+ * @param packageName a human readable name of the package
267
+ */
268
+ async function ensurePackageIsInstalled(packageJson, packageId, packageName) {
269
+ return (0, telemetry_1.traceStep)('ensure-package-installed', async () => {
270
+ const installed = (0, package_json_1.hasPackageInstalled)(packageId, packageJson);
271
+ analytics_1.analytics.setTag(`${packageName.toLowerCase()}-installed`, installed);
272
+ if (!installed) {
273
+ analytics_1.analytics.setTag(`${packageName.toLowerCase()}-installed`, false);
274
+ const continueWithoutPackage = await abortIfCancelled(clack_1.default.confirm({
275
+ message: `${packageName} does not seem to be installed. Do you still want to continue?`,
276
+ initialValue: false,
277
+ }));
278
+ if (!continueWithoutPackage) {
279
+ await abort(undefined, 0);
280
+ }
281
+ }
282
+ });
283
+ }
284
+ async function getPackageDotJson({ installDir, }) {
285
+ const packageJsonFileContents = await fs.promises
286
+ .readFile((0, node_path_1.join)(installDir, 'package.json'), 'utf8')
287
+ .catch(() => {
288
+ clack_1.default.log.error('Could not find package.json. Make sure to run the wizard in the root of your app!');
289
+ return abort();
290
+ });
291
+ let packageJson = undefined;
292
+ try {
293
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
294
+ packageJson = JSON.parse(packageJsonFileContents);
295
+ }
296
+ catch {
297
+ clack_1.default.log.error(`Unable to parse your ${chalk_1.default.cyan('package.json')}. Make sure it has a valid format!`);
298
+ await abort();
299
+ }
300
+ return packageJson || {};
301
+ }
302
+ async function updatePackageDotJson(packageDotJson, { installDir }) {
303
+ try {
304
+ await fs.promises.writeFile((0, node_path_1.join)(installDir, 'package.json'),
305
+ // TODO: maybe figure out the original indentation
306
+ JSON.stringify(packageDotJson, null, 2), {
307
+ encoding: 'utf8',
308
+ flag: 'w',
309
+ });
310
+ }
311
+ catch {
312
+ clack_1.default.log.error(`Unable to update your ${chalk_1.default.cyan('package.json')}.`);
313
+ await abort();
314
+ }
315
+ }
316
+ async function getPackageManager({ installDir, }) {
317
+ const detectedPackageManager = (0, package_manager_1.detectPackageManger)({ installDir });
318
+ if (detectedPackageManager) {
319
+ return detectedPackageManager;
320
+ }
321
+ const selectedPackageManager = await abortIfCancelled(clack_1.default.select({
322
+ message: 'Please select your package manager.',
323
+ options: package_manager_1.packageManagers.map((packageManager) => ({
324
+ value: packageManager,
325
+ label: packageManager.label,
326
+ })),
327
+ }));
328
+ analytics_1.analytics.setTag('package-manager', selectedPackageManager.name);
329
+ return selectedPackageManager;
330
+ }
331
+ function isUsingTypeScript({ installDir, }) {
332
+ try {
333
+ return fs.existsSync((0, node_path_1.join)(installDir, 'tsconfig.json'));
334
+ }
335
+ catch {
336
+ return false;
337
+ }
338
+ }
339
+ /**
340
+ *
341
+ * Use this function to get project data for the wizard.
342
+ *
343
+ * @param options wizard options
344
+ * @returns project data (token, url)
345
+ */
346
+ async function getOrAskForProjectData(_options) {
347
+ const cloudUrl = (0, urls_1.getCloudUrlFromRegion)(_options.cloudRegion);
348
+ const { host, projectApiKey, wizardHash } = await (0, telemetry_1.traceStep)('login', () => askForWizardLogin({
349
+ url: cloudUrl,
350
+ signup: _options.signup,
351
+ }));
352
+ if (!projectApiKey) {
353
+ clack_1.default.log.error(`Didn't receive a project API key. This shouldn't happen :(
354
+
355
+ Please let us know if you think this is a bug in the wizard:
356
+ ${chalk_1.default.cyan(constants_1.ISSUES_URL)}`);
357
+ clack_1.default.log
358
+ .info(`In the meantime, we'll add a dummy project API key (${chalk_1.default.cyan(`"${constants_1.DUMMY_PROJECT_API_KEY}"`)}) for you to replace later.
359
+ You can find your Project API key here:
360
+ ${chalk_1.default.cyan(`${cloudUrl}/settings/project#variables`)}`);
361
+ }
362
+ return {
363
+ wizardHash,
364
+ host: host || constants_1.DEFAULT_HOST_URL,
365
+ projectApiKey: projectApiKey || constants_1.DUMMY_PROJECT_API_KEY,
366
+ };
367
+ }
368
+ async function askForWizardLogin(options) {
369
+ let wizardHash;
370
+ try {
371
+ wizardHash = (await axios_1.default.post(`${options.url}/api/wizard/initialize`)).data.hash;
372
+ }
373
+ catch (e) {
374
+ clack_1.default.log.error('Loading wizard failed.');
375
+ clack_1.default.log.info(JSON.stringify(e, null, 2));
376
+ await abort(chalk_1.default.red(`Please try again in a few minutes and let us know if this issue persists: ${constants_1.ISSUES_URL}`));
377
+ throw e;
378
+ }
379
+ const loginUrl = new node_url_1.URL(`${options.url}/wizard?hash=${wizardHash}`);
380
+ const signupUrl = new node_url_1.URL(`${options.url}/signup?next=${encodeURIComponent(`/wizard?hash=${wizardHash}`)}`);
381
+ const urlToOpen = options.signup ? signupUrl.toString() : loginUrl.toString();
382
+ clack_1.default.log.info(`${chalk_1.default.bold(`If the browser window didn't open automatically, please open the following link to login into PostHog:`)}\n\n${chalk_1.default.cyan(urlToOpen)}${options.signup
383
+ ? `\n\nIf you already have an account, you can use this link:\n\n${chalk_1.default.cyan(loginUrl.toString())}`
384
+ : ``}`);
385
+ (0, opn_1.default)(urlToOpen, { wait: false }).catch(() => {
386
+ // opn throws in environments that don't have a browser (e.g. remote shells) so we just noop here
387
+ });
388
+ const loginSpinner = clack_1.default.spinner();
389
+ loginSpinner.start('Waiting for you to log in using the link above');
390
+ const data = await new Promise((resolve) => {
391
+ const pollingInterval = (0, node_timers_1.setInterval)(() => {
392
+ axios_1.default
393
+ .get(`${options.url}/api/wizard/data`, {
394
+ headers: {
395
+ 'Accept-Encoding': 'deflate',
396
+ 'X-PostHog-Wizard-Hash': wizardHash,
397
+ },
398
+ })
399
+ .then((result) => {
400
+ const data = {
401
+ wizardHash,
402
+ projectApiKey: result.data.project_api_key,
403
+ host: result.data.host,
404
+ distinctId: result.data.user_distinct_id,
405
+ };
406
+ resolve(data);
407
+ clearTimeout(timeout);
408
+ clearInterval(pollingInterval);
409
+ })
410
+ .catch(() => {
411
+ // noop - just try again
412
+ });
413
+ }, 500);
414
+ const timeout = setTimeout(() => {
415
+ clearInterval(pollingInterval);
416
+ loginSpinner.stop('Login timed out. No worries - it happens to the best of us.');
417
+ analytics_1.analytics.setTag('opened-wizard-link', false);
418
+ void abort('Please restart the Wizard and log in to complete the setup.');
419
+ }, 180_000);
420
+ });
421
+ loginSpinner.stop(`Login complete. ${options.signup ? 'Welcome to PostHog! πŸŽ‰' : ''}`);
422
+ analytics_1.analytics.setTag('opened-wizard-link', true);
423
+ analytics_1.analytics.setDistinctId(data.distinctId);
424
+ return data;
425
+ }
426
+ /**
427
+ * Asks users if they have a config file for @param tool (e.g. Vite).
428
+ * If yes, asks users to specify the path to their config file.
429
+ *
430
+ * Use this helper function as a fallback mechanism if the lookup for
431
+ * a config file with its most usual location/name fails.
432
+ *
433
+ * @param toolName Name of the tool for which we're looking for the config file
434
+ * @param configFileName Name of the most common config file name (e.g. vite.config.js)
435
+ *
436
+ * @returns a user path to the config file or undefined if the user doesn't have a config file
437
+ */
438
+ async function askForToolConfigPath(toolName, configFileName) {
439
+ const hasConfig = await abortIfCancelled(clack_1.default.confirm({
440
+ message: `Do you have a ${toolName} config file (e.g. ${chalk_1.default.cyan(configFileName)})?`,
441
+ initialValue: true,
442
+ }));
443
+ if (!hasConfig) {
444
+ return undefined;
445
+ }
446
+ return await abortIfCancelled(clack_1.default.text({
447
+ message: `Please enter the path to your ${toolName} config file:`,
448
+ placeholder: (0, node_path_1.join)('.', configFileName),
449
+ validate: (value) => {
450
+ if (!value) {
451
+ return 'Please enter a path.';
452
+ }
453
+ try {
454
+ fs.accessSync(value);
455
+ }
456
+ catch {
457
+ return 'Could not access the file at this path.';
458
+ }
459
+ },
460
+ }));
461
+ }
462
+ /**
463
+ * Prints copy/paste-able instructions to the console.
464
+ * Afterwards asks the user if they added the code snippet to their file.
465
+ *
466
+ * While there's no point in providing a "no" answer here, it gives users time to fulfill the
467
+ * task before the wizard continues with additional steps.
468
+ *
469
+ * Use this function if you want to show users instructions on how to add/modify
470
+ * code in their file. This is helpful if automatic insertion failed or is not possible/feasible.
471
+ *
472
+ * @param filename the name of the file to which the code snippet should be applied.
473
+ * If a path is provided, only the filename will be used.
474
+ *
475
+ * @param codeSnippet the snippet to be printed. Use {@link makeCodeSnippet} to create the
476
+ * diff-like format for visually highlighting unchanged or modified lines of code.
477
+ *
478
+ * @param hint (optional) a hint to be printed after the main instruction to add
479
+ * the code from @param codeSnippet to their @param filename.
480
+ *
481
+ * TODO: refactor copy paste instructions across different wizards to use this function.
482
+ * this might require adding a custom message parameter to the function
483
+ */
484
+ async function showCopyPasteInstructions(filename, codeSnippet, hint) {
485
+ clack_1.default.log.step(`Add the following code to your ${chalk_1.default.cyan((0, node_path_1.basename)(filename))} file:${hint ? chalk_1.default.dim(` (${chalk_1.default.dim(hint)})`) : ''}`);
486
+ // Padding the code snippet to be printed with a \n at the beginning and end
487
+ // This makes it easier to distinguish the snippet from the rest of the output
488
+ // Intentionally logging directly to console here so that the code can be copied/pasted directly
489
+ // eslint-disable-next-line no-console
490
+ console.log(`\n${codeSnippet}\n`);
491
+ await abortIfCancelled(clack_1.default.select({
492
+ message: 'Did you apply the snippet above?',
493
+ options: [{ label: 'Yes, continue!', value: true }],
494
+ initialValue: true,
495
+ }));
496
+ }
497
+ /**
498
+ * Crafts a code snippet that can be used to e.g.
499
+ * - print copy/paste instructions to the console
500
+ * - create a new config file.
501
+ *
502
+ * @param colors set this to true if you want the final snippet to be colored.
503
+ * This is useful for printing the snippet to the console as part of copy/paste instructions.
504
+ *
505
+ * @param callback the callback that returns the formatted code snippet.
506
+ * It exposes takes the helper functions for marking code as unchanged, new or removed.
507
+ * These functions no-op if no special formatting should be applied
508
+ * and otherwise apply the appropriate formatting/coloring.
509
+ * (@see {@link CodeSnippetFormatter})
510
+ *
511
+ * @see {@link showCopyPasteInstructions} for the helper with which to display the snippet in the console.
512
+ *
513
+ * @returns a string containing the final, formatted code snippet.
514
+ */
515
+ function makeCodeSnippet(colors, callback) {
516
+ const unchanged = (txt) => (colors ? chalk_1.default.grey(txt) : txt);
517
+ const plus = (txt) => (colors ? chalk_1.default.greenBright(txt) : txt);
518
+ const minus = (txt) => (colors ? chalk_1.default.redBright(txt) : txt);
519
+ return callback(unchanged, plus, minus);
520
+ }
521
+ /**
522
+ * Creates a new config file with the given @param filepath and @param codeSnippet.
523
+ *
524
+ * Use this function to create a new config file for users. This is useful
525
+ * when users answered that they don't yet have a config file for a tool.
526
+ *
527
+ * (This doesn't mean that they don't yet have some other way of configuring
528
+ * their tool but we can leave it up to them to figure out how to merge configs
529
+ * here.)
530
+ *
531
+ * @param filepath absolute path to the new config file
532
+ * @param codeSnippet the snippet to be inserted into the file
533
+ * @param moreInformation (optional) the message to be printed after the file was created
534
+ * For example, this can be a link to more information about configuring the tool.
535
+ *
536
+ * @returns true on success, false otherwise
537
+ */
538
+ async function createNewConfigFile(filepath, codeSnippet, { installDir }, moreInformation) {
539
+ if (!(0, node_path_1.isAbsolute)(filepath)) {
540
+ (0, debug_1.debug)(`createNewConfigFile: filepath is not absolute: ${filepath}`);
541
+ return false;
542
+ }
543
+ const prettyFilename = chalk_1.default.cyan((0, node_path_1.relative)(installDir, filepath));
544
+ try {
545
+ await fs.promises.writeFile(filepath, codeSnippet);
546
+ clack_1.default.log.success(`Added new ${prettyFilename} file.`);
547
+ if (moreInformation) {
548
+ clack_1.default.log.info(chalk_1.default.gray(moreInformation));
549
+ }
550
+ return true;
551
+ }
552
+ catch (e) {
553
+ (0, debug_1.debug)(e);
554
+ clack_1.default.log.warn(`Could not create a new ${prettyFilename} file. Please create one manually and follow the instructions below.`);
555
+ }
556
+ return false;
557
+ }
558
+ async function featureSelectionPrompt(features) {
559
+ return (0, telemetry_1.traceStep)('feature-selection', async () => {
560
+ const selectedFeatures = {};
561
+ for (const feature of features) {
562
+ const selected = await abortIfCancelled(clack_1.default.select({
563
+ message: feature.prompt,
564
+ initialValue: true,
565
+ options: [
566
+ {
567
+ value: true,
568
+ label: 'Yes',
569
+ hint: feature.enabledHint,
570
+ },
571
+ {
572
+ value: false,
573
+ label: 'No',
574
+ hint: feature.disabledHint,
575
+ },
576
+ ],
577
+ }));
578
+ selectedFeatures[feature.id] = selected;
579
+ }
580
+ return selectedFeatures;
581
+ });
582
+ }
583
+ async function askShouldInstallPackage(pkgName) {
584
+ return (0, telemetry_1.traceStep)(`ask-install-package`, () => abortIfCancelled(clack_1.default.confirm({
585
+ message: `Do you want to install ${chalk_1.default.cyan(pkgName)}?`,
586
+ })));
587
+ }
588
+ async function askShouldAddPackageOverride(pkgName, pkgVersion) {
589
+ return (0, telemetry_1.traceStep)(`ask-add-package-override`, () => abortIfCancelled(clack_1.default.confirm({
590
+ message: `Do you want to add an override for ${chalk_1.default.cyan(pkgName)} version ${chalk_1.default.cyan(pkgVersion)}?`,
591
+ })));
592
+ }
593
+ async function askForAIConsent(options) {
594
+ return await (0, telemetry_1.traceStep)('ask-for-ai-consent', async () => {
595
+ const aiConsent = options.default
596
+ ? true
597
+ : await abortIfCancelled(clack_1.default.select({
598
+ message: 'This setup wizard uses AI, are you happy to continue? ✨',
599
+ options: [
600
+ {
601
+ label: 'Yes',
602
+ value: true,
603
+ hint: 'We will use AI to help you setup PostHog quickly',
604
+ },
605
+ {
606
+ label: 'No',
607
+ value: false,
608
+ hint: "I don't like AI",
609
+ },
610
+ ],
611
+ initialValue: true,
612
+ }));
613
+ return aiConsent;
614
+ });
615
+ }
616
+ async function askForCloudRegion() {
617
+ return await (0, telemetry_1.traceStep)('ask-for-cloud-region', async () => {
618
+ const cloudRegion = await abortIfCancelled(clack_1.default.select({
619
+ message: 'Select your cloud region',
620
+ options: [
621
+ {
622
+ label: 'US πŸ‡ΊπŸ‡Έ',
623
+ value: 'us',
624
+ },
625
+ {
626
+ label: 'EU πŸ‡ͺπŸ‡Ί',
627
+ value: 'eu',
628
+ },
629
+ ],
630
+ }));
631
+ return cloudRegion;
632
+ });
633
+ }
634
+ //# sourceMappingURL=clack-utils.js.map