@posthog/wizard 0.3.0 → 0.4.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.
- package/README.md +13 -13
- package/dist/src/nextjs/docs.js.map +1 -1
- package/dist/src/react/docs.d.ts +2 -1
- package/dist/src/react/docs.js +5 -2
- package/dist/src/react/docs.js.map +1 -1
- package/dist/src/react/react-wizard.js +3 -1
- package/dist/src/react/react-wizard.js.map +1 -1
- package/dist/src/run.js +2 -0
- package/dist/src/run.js.map +1 -1
- package/dist/src/utils/environment.d.ts +2 -0
- package/dist/src/utils/environment.js +52 -0
- package/dist/src/utils/environment.js.map +1 -1
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -5,8 +5,8 @@
|
|
|
5
5
|
> **⚠️ Experimental:** This wizard is still in an experimental phase.
|
|
6
6
|
> If you have any feedback, please drop an email to **joshua** [at] **posthog** [dot] **com**.
|
|
7
7
|
|
|
8
|
-
<h1>PostHog Wizard
|
|
9
|
-
<h4>The PostHog Wizard helps you quickly add PostHog to your project.</h4>
|
|
8
|
+
<h1>PostHog Wizard ✨</h1>
|
|
9
|
+
<h4>The PostHog Wizard helps you quickly add PostHog to your project using AI.</h4>
|
|
10
10
|
|
|
11
11
|
# Usage
|
|
12
12
|
|
|
@@ -16,21 +16,21 @@ To use the wizard, you can run it directly using:
|
|
|
16
16
|
npx @posthog/wizard
|
|
17
17
|
```
|
|
18
18
|
|
|
19
|
-
Currently the wizard can be used for Next.js
|
|
19
|
+
Currently the wizard can be used for React & Next.js projects. If you have other integrations you would like the wizard to support, please open a [GitHub issue](https://github.com/posthog/wizard/issues)!
|
|
20
20
|
|
|
21
21
|
# Options
|
|
22
22
|
|
|
23
23
|
The following CLI arguments are available:
|
|
24
24
|
|
|
25
|
-
| Option | Description | Type | Default | Choices
|
|
26
|
-
| ----------------- | -------------------------------------------------------------------------- | ------- | ------------------------------- |
|
|
27
|
-
| `--help` | Show help | boolean | |
|
|
28
|
-
| `--version` | Show version number | boolean | |
|
|
29
|
-
| `--debug` | Enable verbose logging | boolean | `false` |
|
|
30
|
-
| `--integration` | Choose the integration to setup | choices | Select integration during setup | "nextjs"
|
|
31
|
-
| `--force-install` | Force install the SDK NPM package (use with caution!) | boolean | `false` |
|
|
32
|
-
| `--install-dir` | Relative path to install in | string | `.` |
|
|
33
|
-
| `--region` | PostHog region to use | choices | | "us", "eu"
|
|
34
|
-
| `--default` | Select the default option for all questions automatically (where possible) | boolean | `false` |
|
|
25
|
+
| Option | Description | Type | Default | Choices | Environment Variable |
|
|
26
|
+
| ----------------- | -------------------------------------------------------------------------- | ------- | ------------------------------- | ----------------- | ---------------------------- |
|
|
27
|
+
| `--help` | Show help | boolean | | | |
|
|
28
|
+
| `--version` | Show version number | boolean | | | |
|
|
29
|
+
| `--debug` | Enable verbose logging | boolean | `false` | | `POSTHOG_WIZARD_DEBUG` |
|
|
30
|
+
| `--integration` | Choose the integration to setup | choices | Select integration during setup | "nextjs", "react" | `POSTHOG_WIZARD_INTEGRATION` |
|
|
31
|
+
| `--force-install` | Force install the SDK NPM package (use with caution!) | boolean | `false` | | |
|
|
32
|
+
| `--install-dir` | Relative path to install in | string | `.` | | `POSTHOG_WIZARD_INSTALL_DIR` |
|
|
33
|
+
| `--region` | PostHog region to use | choices | | "us", "eu" | `POSTHOG_WIZARD_REGION` |
|
|
34
|
+
| `--default` | Select the default option for all questions automatically (where possible) | boolean | `false` | | `POSTHOG_WIZARD_DEFAULT` |
|
|
35
35
|
|
|
36
36
|
> Note: A large amount of the scaffolding for this came from the amazing Sentry wizard, which you can find [here](https://github.com/getsentry/sentry-wizard) 💖
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"docs.js","sourceRoot":"","sources":["../../../src/nextjs/docs.ts"],"names":[],"mappings":";;;AAAA,wCAAwE;AAEjE,MAAM,sBAAsB,GAAG,CAAC,EACrC,IAAI,EACJ,QAAQ,GAIT,EAAE,EAAE;IACH,OAAO;;
|
|
1
|
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B,EAAC,IAAI,CAAC;;;;wBAI1B,IAAI;;;;wBAIJ,IAAI;;;;;;;;mDAQuB,CAAC;AACpD,CAAC,CAAC;AA3GW,QAAA,wBAAwB,4BA2GnC","sourcesContent":["import { getAssetHostFromHost, getUiHostFromHost } from '../utils/urls';\n\nexport const getNextjsAppRouterDocs = ({\n host,\n language,\n}: {\n host: string;\n language: 'typescript' | 'javascript';\n}) => {\n return `\n==============================\nFILE: PostHogProvider.${\n language === 'typescript' ? 'tsx' : 'jsx'\n } (put it somewhere where client files are, like the components folder)\nLOCATION: Wherever other providers are, or the components folder\n==============================\nChanges:\n- Create a PostHogProvider component that will be imported into the layout file.\n\nExample:\n--------------------------------------------------\n\"use client\"\n\nimport posthog from \"posthog-js\"\nimport { PostHogProvider as PHProvider, usePostHog } from \"posthog-js/react\"\nimport { Suspense, useEffect } from \"react\"\nimport { usePathname, useSearchParams } from \"next/navigation\"\n\nexport function PostHogProvider({ children }: { children: React.ReactNode }) {\n useEffect(() => {\n posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {\n api_host: \"/ingest\",\n ui_host: \"${getUiHostFromHost(host)}\",\n capture_pageview: false, // We capture pageviews manually\n capture_pageleave: true, // Enable pageleave capture\n })\n }, [])\n\n return (\n <PHProvider client={posthog}>\n <SuspendedPostHogPageView />\n {children}\n </PHProvider>\n )\n}\n\n\nfunction PostHogPageView() {\n const pathname = usePathname()\n const searchParams = useSearchParams()\n const posthog = usePostHog()\n\n useEffect(() => {\n if (pathname && posthog) {\n let url = window.origin + pathname\n const search = searchParams.toString()\n if (search) {\n url += \"?\" + search\n }\n posthog.capture(\"$pageview\", { \"$current_url\": url })\n }\n }, [pathname, searchParams, posthog])\n\n return null\n}\n\nfunction SuspendedPostHogPageView() {\n return (\n <Suspense fallback={null}>\n <PostHogPageView />\n </Suspense>\n )\n}\n--------------------------------------------------\n\n==============================\nFILE: layout.${language === 'typescript' ? 'tsx' : 'jsx'}\nLOCATION: Wherever the root layout is\n==============================\nChanges:\n- Import the PostHogProvider from the providers file and wrap the app in it.\n\nExample:\n--------------------------------------------------\n// other imports\nimport { PostHogProvider } from \"LOCATION_OF_POSTHOG_PROVIDER\"\n\nexport default function RootLayout({ children }) {\n return (\n <html lang=\"en\">\n <body>\n <PostHogProvider>\n {/* other providers */}\n {children}\n {/* other providers */}\n </PostHogProvider>\n </body>\n </html>\n )\n}\n--------------------------------------------------\n\n==============================\nFILE: posthog.${language === 'typescript' ? 'ts' : 'js'}\nLOCATION: Wherever works best given the project structure\n==============================\nChanges:\n- Initialize the PostHog Node.js client\n\nExample:\n--------------------------------------------------\nimport { PostHog } from \"posthog-node\"\n\nexport default function PostHogClient() {\n const posthogClient = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {\n host: \"${host}\",\n flushAt: 1,\n flushInterval: 0,\n })\n return posthogClient\n}\n--------------------------------------------------\n\n==============================\nFILE: next.config.{js,ts,mjs,cjs}\nLOCATION: Wherever the root next config is\n==============================\nChanges:\n- Add rewrites to the Next.js config to support PostHog, if there are existing rewrites, add the PostHog rewrites to them.\n- Add skipTrailingSlashRedirect to the Next.js config to support PostHog trailing slash API requests.\n- This can be of type js, ts, mjs, cjs etc. You should adapt the file according to what extension it uses, and if it does not exist yet use '.js'.\n\nExample:\n--------------------------------------------------\nconst nextConfig = {\n // other config\n async rewrites() {\n return [\n {\n source: \"/ingest/static/:path*\",\n destination: \"${getAssetHostFromHost(host)}/static/:path*\",\n },\n {\n source: \"/ingest/:path*\",\n destination: \"${host}/:path*\",\n },\n {\n source: \"/ingest/decide\",\n destination: \"${host}/decide\",\n },\n ];\n },\n // This is required to support PostHog trailing slash API requests\n skipTrailingSlashRedirect: true,\n}\nmodule.exports = nextConfig\n--------------------------------------------------`;\n};\n\nexport const getNextjsPagesRouterDocs = ({\n host,\n language,\n}: {\n host: string;\n language: 'typescript' | 'javascript';\n}) => {\n return `\n==============================\nFILE: _app.${language === 'typescript' ? 'tsx' : 'jsx'}\nLOCATION: Wherever the root _app.${\n language === 'typescript' ? 'tsx' : 'jsx'\n } file is\n==============================\nChanges:\n- Initialize PostHog in _app.js.\n- Wrap the application in PostHogProvider.\n- Manually capture $pageview events.\n\nExample:\n--------------------------------------------------\nimport { useEffect } from \"react\"\nimport { Router } from \"next/router\"\nimport posthog from \"posthog-js\"\nimport { PostHogProvider } from \"posthog-js/react\"\n\nexport default function App({ Component, pageProps }) {\n useEffect(() => {\n posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY, {\n api_host: \"/ingest\",\n ui_host: \"${getUiHostFromHost(host)}\",\n loaded: (posthog) => {\n if (process.env.NODE_ENV === \"development\") posthog.debug()\n },\n })\n\n const handleRouteChange = () => posthog?.capture(\"$pageview\")\n Router.events.on(\"routeChangeComplete\", handleRouteChange)\n\n return () => {\n Router.events.off(\"routeChangeComplete\", handleRouteChange)\n }\n }, [])\n\n return (\n <PostHogProvider client={posthog}>\n <Component {...pageProps} />\n </PostHogProvider>\n )\n}\n--------------------------------------------------\n\n==============================\nFILE: posthog.${language === 'typescript' ? 'ts' : 'js'}\nLOCATION: Wherever works best given the project structure\n==============================\nChanges:\n- Initialize the PostHog Node.js client\n\nExample:\n--------------------------------------------------\nimport { PostHog } from \"posthog-node\"\n\nexport default function PostHogClient() {\n const posthogClient = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {\n host: \"${host}\",\n flushAt: 1,\n flushInterval: 0,\n })\n return posthogClient\n}\n--------------------------------------------------\n\n==============================\nFILE: next.config.{js,ts,mjs,cjs}\nLOCATION: Wherever the root next config is\n==============================\nChanges:\n- Add rewrites to the Next.js config to support PostHog, if there are existing rewrites, add the PostHog rewrites to them.\n- Add skipTrailingSlashRedirect to the Next.js config to support PostHog trailing slash API requests.\n- This can be of type js, ts, mjs, cjs etc. You should adapt the file according to what extension it uses, and if it does not exist yet use '.js'.\n\nExample:\n--------------------------------------------------\nconst nextConfig = {\n // other config\n async rewrites() {\n return [\n {\n source: \"/ingest/static/:path*\",\n destination: \"${getAssetHostFromHost(host)}/static/:path*\",\n },\n {\n source: \"/ingest/:path*\",\n destination: \"${host}/:path*\",\n },\n {\n source: \"/ingest/decide\",\n destination: \"${host}/decide\",\n },\n ];\n },\n // This is required to support PostHog trailing slash API requests\n skipTrailingSlashRedirect: true,\n}\nmodule.exports = nextConfig\n--------------------------------------------------`;\n};\n"]}
|
package/dist/src/react/docs.d.ts
CHANGED
package/dist/src/react/docs.js
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.getReactDocumentation = void 0;
|
|
4
|
-
const getReactDocumentation = ({ host, language, }) => {
|
|
4
|
+
const getReactDocumentation = ({ host, language, envVarPrefix, }) => {
|
|
5
|
+
const apiKeyText = envVarPrefix === 'VITE_PUBLIC_'
|
|
6
|
+
? 'import.meta.env.VITE_PUBLIC_POSTHOG_KEY'
|
|
7
|
+
: `process.env.${envVarPrefix}POSTHOG_KEY`;
|
|
5
8
|
return `
|
|
6
9
|
==============================
|
|
7
10
|
FILE: {index / App}.${language === 'typescript' ? 'tsx' : 'jsx'} (wherever the root of the app is)
|
|
@@ -23,7 +26,7 @@ const root = ReactDOM.createRoot(document.getElementById('root'));
|
|
|
23
26
|
root.render(
|
|
24
27
|
<React.StrictMode>
|
|
25
28
|
<PostHogProvider
|
|
26
|
-
apiKey={
|
|
29
|
+
apiKey={${apiKeyText}}
|
|
27
30
|
options={{
|
|
28
31
|
api_host: ${host},
|
|
29
32
|
}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"docs.js","sourceRoot":"","sources":["../../../src/react/docs.ts"],"names":[],"mappings":";;;AAAO,MAAM,qBAAqB,GAAG,CAAC,EACpC,IAAI,EACJ,QAAQ,
|
|
1
|
+
{"version":3,"file":"docs.js","sourceRoot":"","sources":["../../../src/react/docs.ts"],"names":[],"mappings":";;;AAAO,MAAM,qBAAqB,GAAG,CAAC,EACpC,IAAI,EACJ,QAAQ,EACR,YAAY,GAKb,EAAE,EAAE;IACH,MAAM,UAAU,GACd,YAAY,KAAK,cAAc;QAC7B,CAAC,CAAC,yCAAyC;QAC3C,CAAC,CAAC,eAAe,YAAY,aAAa,CAAC;IAC/C,OAAO;;sBAGL,QAAQ,KAAK,YAAY,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KACtC;;;;;;;;;;;;;;;;;;;gBAmBc,UAAU;;cAEZ,IAAI;;;;;;mDAMiC,CAAC;AACpD,CAAC,CAAC;AA7CW,QAAA,qBAAqB,yBA6ChC","sourcesContent":["export const getReactDocumentation = ({\n host,\n language,\n envVarPrefix,\n}: {\n host: string;\n language: 'typescript' | 'javascript';\n envVarPrefix: string;\n}) => {\n const apiKeyText =\n envVarPrefix === 'VITE_PUBLIC_'\n ? 'import.meta.env.VITE_PUBLIC_POSTHOG_KEY'\n : `process.env.${envVarPrefix}POSTHOG_KEY`;\n return `\n==============================\nFILE: {index / App}.${\n language === 'typescript' ? 'tsx' : 'jsx'\n } (wherever the root of the app is)\nLOCATION: Wherever the root of the app is\n==============================\nChanges:\n- Add the PostHogProvider to the root of the app in the provider tree.\n\nExample:\n--------------------------------------------------\nimport React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport App from './App';\n\nimport { PostHogProvider} from 'posthog-js/react'\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\n\nroot.render(\n <React.StrictMode>\n <PostHogProvider\n apiKey={${apiKeyText}}\n options={{\n api_host: ${host},\n}}\n >\n <App />\n </PostHogProvider>\n </React.StrictMode>\n--------------------------------------------------`;\n};\n"]}
|
|
@@ -51,9 +51,11 @@ async function runReactWizard(options) {
|
|
|
51
51
|
installDir: options.installDir,
|
|
52
52
|
integration: constants_1.Integration.react,
|
|
53
53
|
});
|
|
54
|
+
const envVarPrefix = await (0, environment_1.detectEnvVarPrefix)(options);
|
|
54
55
|
const installationDocumentation = (0, docs_1.getReactDocumentation)({
|
|
55
56
|
host,
|
|
56
57
|
language: typeScriptDetected ? 'typescript' : 'javascript',
|
|
58
|
+
envVarPrefix,
|
|
57
59
|
});
|
|
58
60
|
clack_1.default.log.info(`Reviewing PostHog documentation for React`);
|
|
59
61
|
const filesToChange = await (0, file_utils_1.getFilesToChange)({
|
|
@@ -73,7 +75,7 @@ async function runReactWizard(options) {
|
|
|
73
75
|
});
|
|
74
76
|
await (0, environment_1.addOrUpdateEnvironmentVariables)({
|
|
75
77
|
variables: {
|
|
76
|
-
|
|
78
|
+
[envVarPrefix + 'POSTHOG_KEY']: projectApiKey,
|
|
77
79
|
},
|
|
78
80
|
installDir: options.installDir,
|
|
79
81
|
integration: constants_1.Integration.react,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"react-wizard.js","sourceRoot":"","sources":["../../../src/react/react-wizard.ts"],"names":[],"mappings":";AAAA,8BAA8B;;;;;
|
|
1
|
+
{"version":3,"file":"react-wizard.js","sourceRoot":"","sources":["../../../src/react/react-wizard.ts"],"names":[],"mappings":";AAAA,8BAA8B;;;;;AAiC9B,wCA8GC;AA7ID,kDAA0B;AAC1B,sDAY8B;AAC9B,wDAA+E;AAC/E,2DAAmC;AACnC,gDAA2D;AAC3D,iCAA+C;AAC/C,kDAA+C;AAC/C,sDAG8B;AAC9B,oDAI6B;AAE7B,sDAAyD;AAElD,KAAK,UAAU,cAAc,CAAC,OAAsB;IACzD,IAAA,0BAAY,EAAC;QACX,UAAU,EAAE,sBAAsB;KACnC,CAAC,CAAC;IAEH,MAAM,SAAS,GAAG,MAAM,IAAA,6BAAe,EAAC,OAAO,CAAC,CAAC;IAEjD,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,MAAM,IAAA,mBAAK,EACT,qJAAqJ,EACrJ,CAAC,CACF,CAAC;IACJ,CAAC;IAED,MAAM,WAAW,GAAG,OAAO,CAAC,WAAW,IAAI,CAAC,MAAM,IAAA,+BAAiB,GAAE,CAAC,CAAC;IAEvE,MAAM,kBAAkB,GAAG,IAAA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BAAgB,MAAM,CACjD,GAAG;;EAEJ,eAAK,CAAC,GAAG,CAAC,kDAAkD,sBAAU,EAAE,CAAC,EAAE,CAAC,CAAC;IAE7E,MAAM,qBAAS,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;AACtC,CAAC","sourcesContent":["/* eslint-disable max-lines */\n\nimport chalk from 'chalk';\nimport {\n abort,\n askForAIConsent,\n confirmContinueIfNoOrDirtyGitRepo,\n ensurePackageIsInstalled,\n getOrAskForProjectData,\n getPackageDotJson,\n getPackageManager,\n installPackage,\n isUsingTypeScript,\n printWelcome,\n runPrettierIfInstalled,\n} from '../utils/clack-utils';\nimport { getPackageVersion, hasPackageInstalled } from '../utils/package-json';\nimport clack from '../utils/clack';\nimport { Integration, ISSUES_URL } from '../lib/constants';\nimport { getReactDocumentation } from './docs';\nimport { analytics } from '../utils/analytics';\nimport {\n addOrUpdateEnvironmentVariables,\n detectEnvVarPrefix,\n} from '../utils/environment';\nimport {\n generateFileChangesForIntegration,\n getFilesToChange,\n getRelevantFilesForIntegration,\n} from '../utils/file-utils';\nimport type { WizardOptions } from '../utils/types';\nimport { askForCloudRegion } from '../utils/clack-utils';\n\nexport async function runReactWizard(options: WizardOptions): Promise<void> {\n printWelcome({\n wizardName: 'PostHog React Wizard',\n });\n\n const aiConsent = await askForAIConsent(options);\n\n if (!aiConsent) {\n await abort(\n 'The React wizard requires AI to get setup right now. Please view the docs to setup React manually instead: https://posthog.com/docs/libraries/react',\n 0,\n );\n }\n\n const cloudRegion = options.cloudRegion ?? (await askForCloudRegion());\n\n const typeScriptDetected = isUsingTypeScript(options);\n\n await confirmContinueIfNoOrDirtyGitRepo(options);\n\n const packageJson = await getPackageDotJson(options);\n\n await ensurePackageIsInstalled(packageJson, 'react', 'React');\n\n const reactVersion = getPackageVersion('react', packageJson);\n\n if (reactVersion) {\n analytics.setTag('react-version', reactVersion);\n }\n\n const { projectApiKey, wizardHash, host } = await getOrAskForProjectData({\n ...options,\n cloudRegion,\n });\n\n const sdkAlreadyInstalled = hasPackageInstalled('posthog-js', packageJson);\n\n analytics.setTag('sdk-already-installed', sdkAlreadyInstalled);\n\n const { packageManager: packageManagerFromInstallStep } =\n await installPackage({\n packageName: 'posthog-js',\n packageNameDisplayLabel: 'posthog-js',\n alreadyInstalled: !!packageJson?.dependencies?.['posthog-js'],\n forceInstall: options.forceInstall,\n askBeforeUpdating: false,\n installDir: options.installDir,\n integration: Integration.react,\n });\n\n const relevantFiles = await getRelevantFilesForIntegration({\n installDir: options.installDir,\n integration: Integration.react,\n });\n\n const envVarPrefix = await detectEnvVarPrefix(options);\n\n const installationDocumentation = getReactDocumentation({\n host,\n language: typeScriptDetected ? 'typescript' : 'javascript',\n envVarPrefix,\n });\n\n clack.log.info(`Reviewing PostHog documentation for React`);\n\n const filesToChange = await getFilesToChange({\n integration: Integration.react,\n relevantFiles,\n documentation: installationDocumentation,\n wizardHash,\n cloudRegion,\n });\n\n await generateFileChangesForIntegration({\n integration: Integration.react,\n filesToChange,\n wizardHash,\n installDir: options.installDir,\n documentation: installationDocumentation,\n cloudRegion,\n });\n\n await addOrUpdateEnvironmentVariables({\n variables: {\n [envVarPrefix + 'POSTHOG_KEY']: projectApiKey,\n },\n installDir: options.installDir,\n integration: Integration.react,\n });\n\n const packageManagerForOutro =\n packageManagerFromInstallStep ?? (await getPackageManager(options));\n\n await runPrettierIfInstalled({\n installDir: options.installDir,\n integration: Integration.react,\n });\n\n clack.outro(`\n${chalk.green('Successfully installed PostHog!')} ${`\\n\\n${\n aiConsent\n ? `Note: This uses experimental AI to setup your project. It might have got it wrong, pleaes check!\\n`\n : ``\n }You should validate your setup by (re)starting your dev environment (e.g. ${chalk.cyan(\n `${packageManagerForOutro.runScriptCommand} dev`,\n )})`}\n\n${chalk.dim(`If you encounter any issues, let us know here: ${ISSUES_URL}`)}`);\n\n await analytics.shutdown('success');\n}\n"]}
|
package/dist/src/run.js
CHANGED
|
@@ -12,6 +12,7 @@ const clack_1 = __importDefault(require("./utils/clack"));
|
|
|
12
12
|
const path_1 = __importDefault(require("path"));
|
|
13
13
|
const config_1 = require("./lib/config");
|
|
14
14
|
const react_wizard_1 = require("./react/react-wizard");
|
|
15
|
+
const analytics_1 = require("./utils/analytics");
|
|
15
16
|
async function run(argv) {
|
|
16
17
|
await runWizard(argv);
|
|
17
18
|
}
|
|
@@ -31,6 +32,7 @@ async function runWizard(argv) {
|
|
|
31
32
|
};
|
|
32
33
|
clack_1.default.intro(`Welcome to the PostHog setup wizard ✨`);
|
|
33
34
|
const integration = finalArgs.integration ?? (await getIntegrationForSetup(wizardOptions));
|
|
35
|
+
analytics_1.analytics.setTag('integration', integration);
|
|
34
36
|
switch (integration) {
|
|
35
37
|
case constants_1.Integration.nextjs:
|
|
36
38
|
await (0, nextjs_wizard_1.runNextjsWizard)(wizardOptions);
|
package/dist/src/run.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run.js","sourceRoot":"","sources":["../../src/run.ts"],"names":[],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"run.js","sourceRoot":"","sources":["../../src/run.ts"],"names":[],"mappings":";;;;;AAsBA,kBAEC;AAxBD,qDAAuD;AAEvD,0DAAyD;AAGzD,+CAAyE;AACzE,qDAAsD;AACtD,0DAAkC;AAClC,gDAAwB;AACxB,yCAAqE;AACrE,uDAAsD;AACtD,iDAA8C;AAWvC,KAAK,UAAU,GAAG,CAAC,IAAU;IAClC,MAAM,SAAS,CAAC,IAAI,CAAC,CAAC;AACxB,CAAC;AAED,KAAK,UAAU,SAAS,CAAC,IAAU;IACjC,MAAM,SAAS,GAAG;QAChB,GAAG,IAAI;QACP,GAAG,IAAA,6BAAe,GAAE;KACrB,CAAC;IAEF,MAAM,aAAa,GAAkB;QACnC,KAAK,EAAE,SAAS,CAAC,KAAK,IAAI,KAAK;QAC/B,YAAY,EAAE,SAAS,CAAC,YAAY,IAAI,KAAK;QAC7C,UAAU,EAAE,SAAS,CAAC,UAAU;YAC9B,CA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AO,WAA0B,CAAC;QACpC,CAAC;IACH,CAAC;AACH,CAAC;AAED,KAAK,UAAU,sBAAsB,CACnC,OAA0C;IAE1C,MAAM,mBAAmB,GAAG,MAAM,iBAAiB,CAAC,OAAO,CAAC,CAAC;IAE7D,IAAI,mBAAmB,EAAE,CAAC;QACxB,eAAK,CAAC,GAAG,CAAC,OAAO,CACf,yBAAyB,IAAA,qCAAyB,EAAC,mBAAmB,CAAC,EAAE,CAC1E,CAAC;QACF,OAAO,mBAAmB,CAAC;IAC7B,CAAC;IAED,MAAM,WAAW,GAAgB,MAAM,IAAA,8BAAgB,EACrD,eAAK,CAAC,MAAM,CAAC;QACX,OAAO,EAAE,6BAA6B;QACtC,OAAO,EAAE;YACP,EAAE,KAAK,EAAE,uBAAW,CAAC,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE;YAC/C,EAAE,KAAK,EAAE,uBAAW,CAAC,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE;SAC7C;KACF,CAAC,CACH,CAAC;IAEF,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["import { abortIfCancelled } from './utils/clack-utils';\n\nimport { runNextjsWizard } from './nextjs/nextjs-wizard';\nimport type { CloudRegion, WizardOptions } from './utils/types';\n\nimport { getIntegrationDescription, Integration } from './lib/constants';\nimport { readEnvironment } from './utils/environment';\nimport clack from './utils/clack';\nimport path from 'path';\nimport { INTEGRATION_CONFIG, INTEGRATION_ORDER } from './lib/config';\nimport { runReactWizard } from './react/react-wizard';\nimport { analytics } from './utils/analytics';\n\ntype Args = {\n integration?: Integration;\n debug?: boolean;\n forceInstall?: boolean;\n installDir?: string;\n region?: CloudRegion;\n default?: boolean;\n};\n\nexport async function run(argv: Args) {\n await runWizard(argv);\n}\n\nasync function runWizard(argv: Args) {\n const finalArgs = {\n ...argv,\n ...readEnvironment(),\n };\n\n const wizardOptions: WizardOptions = {\n debug: finalArgs.debug ?? false,\n forceInstall: finalArgs.forceInstall ?? false,\n installDir: finalArgs.installDir\n ? path.join(process.cwd(), finalArgs.installDir)\n : process.cwd(),\n cloudRegion: finalArgs.region ?? undefined,\n default: finalArgs.default ?? false,\n };\n\n clack.intro(`Welcome to the PostHog setup wizard ✨`);\n\n const integration =\n finalArgs.integration ?? (await getIntegrationForSetup(wizardOptions));\n\n analytics.setTag('integration', integration);\n\n switch (integration) {\n case Integration.nextjs:\n await runNextjsWizard(wizardOptions);\n break;\n case Integration.react:\n await runReactWizard(wizardOptions);\n break;\n\n default:\n clack.log.error('No setup wizard selected!');\n }\n}\n\nasync function detectIntegration(\n options: Pick<WizardOptions, 'installDir'>,\n): Promise<Integration | undefined> {\n const integrationConfigs = Object.entries(INTEGRATION_CONFIG).sort(\n ([a], [b]) =>\n INTEGRATION_ORDER.indexOf(a as Integration) -\n INTEGRATION_ORDER.indexOf(b as Integration),\n );\n\n for (const [integration, config] of integrationConfigs) {\n const detected = await config.detect(options);\n if (detected) {\n return integration as Integration;\n }\n }\n}\n\nasync function getIntegrationForSetup(\n options: Pick<WizardOptions, 'installDir'>,\n) {\n const detectedIntegration = await detectIntegration(options);\n\n if (detectedIntegration) {\n clack.log.success(\n `Detected integration: ${getIntegrationDescription(detectedIntegration)}`,\n );\n return detectedIntegration;\n }\n\n const integration: Integration = await abortIfCancelled(\n clack.select({\n message: 'What do you want to set up?',\n options: [\n { value: Integration.nextjs, label: 'Next.js' },\n { value: Integration.react, label: 'React' },\n ],\n }),\n );\n\n return integration;\n}\n"]}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { Integration } from '../lib/constants';
|
|
2
|
+
import type { WizardOptions } from './types';
|
|
2
3
|
export declare function readEnvironment(): Record<string, unknown>;
|
|
3
4
|
export declare function addOrUpdateEnvironmentVariables({ installDir, variables, integration, }: {
|
|
4
5
|
installDir: string;
|
|
5
6
|
variables: Record<string, string>;
|
|
6
7
|
integration: Integration;
|
|
7
8
|
}): Promise<void>;
|
|
9
|
+
export declare function detectEnvVarPrefix(options: WizardOptions): Promise<string>;
|
|
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.readEnvironment = readEnvironment;
|
|
7
7
|
exports.addOrUpdateEnvironmentVariables = addOrUpdateEnvironmentVariables;
|
|
8
|
+
exports.detectEnvVarPrefix = detectEnvVarPrefix;
|
|
8
9
|
const path_1 = __importDefault(require("path"));
|
|
9
10
|
const read_env_1 = __importDefault(require("read-env"));
|
|
10
11
|
const fs_1 = __importDefault(require("fs"));
|
|
@@ -12,6 +13,8 @@ const clack_1 = __importDefault(require("./clack"));
|
|
|
12
13
|
const chalk_1 = __importDefault(require("chalk"));
|
|
13
14
|
const file_utils_1 = require("./file-utils");
|
|
14
15
|
const analytics_1 = require("./analytics");
|
|
16
|
+
const clack_utils_1 = require("./clack-utils");
|
|
17
|
+
const fast_glob_1 = __importDefault(require("fast-glob"));
|
|
15
18
|
function readEnvironment() {
|
|
16
19
|
const result = (0, read_env_1.default)('POSTHOG_WIZARD');
|
|
17
20
|
return result;
|
|
@@ -109,4 +112,53 @@ async function addOrUpdateEnvironmentVariables({ installDir, variables, integrat
|
|
|
109
112
|
integration,
|
|
110
113
|
});
|
|
111
114
|
}
|
|
115
|
+
async function detectEnvVarPrefix(options) {
|
|
116
|
+
const packageJson = await (0, clack_utils_1.getPackageDotJson)(options);
|
|
117
|
+
const deps = { ...packageJson.dependencies, ...packageJson.devDependencies };
|
|
118
|
+
const has = (name) => name in deps;
|
|
119
|
+
const hasAnyFile = async (patterns) => {
|
|
120
|
+
const matches = await (0, fast_glob_1.default)(patterns, {
|
|
121
|
+
cwd: options.installDir,
|
|
122
|
+
absolute: false,
|
|
123
|
+
onlyFiles: true,
|
|
124
|
+
ignore: ['**/node_modules/**'],
|
|
125
|
+
});
|
|
126
|
+
return matches.length > 0;
|
|
127
|
+
};
|
|
128
|
+
// --- Next.js
|
|
129
|
+
if (has('next') || (await hasAnyFile(['**/next.config.{js,ts,mjs,cjs}']))) {
|
|
130
|
+
return 'NEXT_PUBLIC_';
|
|
131
|
+
}
|
|
132
|
+
// --- Create React App
|
|
133
|
+
if (has('react-scripts') ||
|
|
134
|
+
has('create-react-app') ||
|
|
135
|
+
(await hasAnyFile(['**/config-overrides.js']))) {
|
|
136
|
+
return 'REACT_APP_';
|
|
137
|
+
}
|
|
138
|
+
// --- Vite (vanilla, TanStack, Solid, etc.)
|
|
139
|
+
// Note: Vite does not need PUBLIC_ but we use it to follow the docs, to improve the chances of an LLM getting it right.
|
|
140
|
+
if (has('vite') || (await hasAnyFile(['**/vite.config.{js,ts,mjs,cjs}']))) {
|
|
141
|
+
return 'VITE_PUBLIC_';
|
|
142
|
+
}
|
|
143
|
+
// --- SvelteKit
|
|
144
|
+
if (has('@sveltejs/kit') ||
|
|
145
|
+
(await hasAnyFile(['**/svelte.config.{js,ts}']))) {
|
|
146
|
+
return 'PUBLIC_';
|
|
147
|
+
}
|
|
148
|
+
// --- TanStack Start (uses Vite)
|
|
149
|
+
if (has('@tanstack/start') ||
|
|
150
|
+
(await hasAnyFile(['**/tanstack.config.{js,ts}']))) {
|
|
151
|
+
return 'VITE_PUBLIC_';
|
|
152
|
+
}
|
|
153
|
+
// --- SolidStart (uses Vite)
|
|
154
|
+
if (has('solid-start') || (await hasAnyFile(['**/solid.config.{js,ts}']))) {
|
|
155
|
+
return 'VITE_PUBLIC_';
|
|
156
|
+
}
|
|
157
|
+
// --- Astro
|
|
158
|
+
if (has('astro') || (await hasAnyFile(['**/astro.config.{js,ts,mjs}']))) {
|
|
159
|
+
return 'PUBLIC_';
|
|
160
|
+
}
|
|
161
|
+
// We default to Vite if we can't detect a specific framework, since it's the most commonly used.
|
|
162
|
+
return 'VITE_PUBLIC_';
|
|
163
|
+
}
|
|
112
164
|
//# sourceMappingURL=environment.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"environment.js","sourceRoot":"","sources":["../../../src/utils/environment.ts"],"names":[],"mapp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CAAC,IAAI,CAAC,IAAI,CACxB,YAAY,CACb,gCAAgC,CAClC,CAAC;YACJ,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,eAAK,CAAC,GAAG,CAAC,OAAO,CACf,oBAAoB,eAAK,CAAC,IAAI,CAAC,IAAI,CACjC,YAAY,CACb,yCAAyC,KAAK,CAAC,OAAO,EAAE,CAC1D,CAAC;YACJ,CAAC;QACH,CAAC;IACH,CAAC;SAAM,CAAC;QACN,IAAI,CAAC;YACH,MAAM,mBAAmB,GAAG,GAAG,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;YACvD,MAAM,YAAE,CAAC,QAAQ,CAAC,SAAS,CACzB,cAAI,CAAC,IAAI,CAAC,UAAU,EAAE,YAAY,CAAC,EACnC,mBAAmB,EACnB;gBACE,QAAQ,EAAE,MAAM;gBAChB,IAAI,EAAE,GAAG;aACV,CACF,CAAC;YACF,eAAK,CAAC,GAAG,CAAC,OAAO,CACf,WAAW,eAAK,CAAC,IAAI,CAAC,IAAI,CAAC,YAAY,CAAC,0BAA0B,CACnE,CAAC;QACJ,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,eAAK,CAAC,GAAG,CAAC,OAAO,CACf,oBAAoB,eAAK,CAAC,IAAI,CAAC,IAAI,CACjC,YAAY,CACb,mCAAmC,KAAK,CAAC,OAAO,EAAE,CACpD,CAAC;QACJ,CAAC;IACH,CAAC;IAED,qBAAS,CAAC,OAAO,CAAC,oBAAoB,EAAE;QACtC,MAAM,EAAE,6BAA6B;QACrC,WAAW;KACZ,CAAC,CAAC;AACL,CAAC","sourcesContent":["import path from 'path';\nimport readEnv from 'read-env';\nimport fs from 'fs';\nimport clack from './clack';\nimport chalk from 'chalk';\nimport { getDotGitignore } from './file-utils';\nimport { Integration } from '../lib/constants';\nimport { analytics } from './analytics';\nexport function readEnvironment(): Record<string, unknown> {\n const result = readEnv('POSTHOG_WIZARD');\n\n return result;\n}\n\nexport async function addOrUpdateEnvironmentVariables({\n installDir,\n variables,\n integration,\n}: {\n installDir: string;\n variables: Record<string, string>;\n integration: Integration;\n}): Promise<void> {\n const envVarContent = Object.entries(variables)\n .map(([key, value]) => `${key}=${value}`)\n .join('\\n');\n\n const dotEnvLocalFilePath = path.join(installDir, '.env.local');\n const dotEnvFilePath = path.join(installDir, '.env');\n const targetEnvFilePath = fs.existsSync(dotEnvLocalFilePath)\n ? dotEnvLocalFilePath\n : dotEnvFilePath;\n\n const dotEnvFileExists = fs.existsSync(targetEnvFilePath);\n\n const relativeEnvFilePath = path.relative(installDir, targetEnvFilePath);\n\n if (dotEnvFileExists) {\n try {\n let dotEnvFileContent = fs.readFileSync(targetEnvFilePath, 'utf8');\n let updated = false;\n\n for (const [key, value] of Object.entries(variables)) {\n const regex = new RegExp(`^${key}=.*$`, 'm');\n\n if (dotEnvFileContent.match(regex)) {\n dotEnvFileContent = dotEnvFileContent.replace(\n regex,\n `${key}=${value}`,\n );\n updated = true;\n } else {\n if (!dotEnvFileContent.endsWith('\\n')) {\n dotEnvFileContent += '\\n';\n }\n dotEnvFileContent += `${key}=${value}\\n`;\n updated = true;\n }\n }\n\n if (updated) {\n await fs.promises.writeFile(targetEnvFilePath, dotEnvFileContent, {\n encoding: 'utf8',\n flag: 'w',\n });\n clack.log.success(\n `Updated environment variables in ${chalk.bold.cyan(\n relativeEnvFilePath,\n )}`,\n );\n } else {\n clack.log.success(\n `${chalk.bold.cyan(\n relativeEnvFilePath,\n )} already has the necessary environment variables.`,\n );\n }\n } catch (error) {\n clack.log.warning(\n `Failed to update environment variables in ${chalk.bold.cyan(\n relativeEnvFilePath,\n )}. Please update them manually. Error: ${error.message}`,\n );\n }\n } else {\n try {\n await fs.promises.writeFile(targetEnvFilePath, envVarContent, {\n encoding: 'utf8',\n flag: 'w',\n });\n clack.log.success(\n `Created ${chalk.bold.cyan(\n relativeEnvFilePath,\n )} with environment variables.`,\n );\n } catch (error) {\n clack.log.warning(\n `Failed to create ${chalk.bold.cyan(\n relativeEnvFilePath,\n )} with environment variables. Please add them manually. Error: ${\n error.message\n }`,\n );\n }\n }\n\n const gitignorePath = getDotGitignore({ installDir });\n const envFiles = ['.env', '.env.local'];\n\n if (gitignorePath) {\n const gitignoreContent = fs.readFileSync(gitignorePath, 'utf8');\n const missingEnvFiles = envFiles.filter(\n (file) => !gitignoreContent.includes(file),\n );\n\n if (missingEnvFiles.length > 0) {\n try {\n const newGitignoreContent = `${gitignoreContent}\\n${missingEnvFiles.join(\n '\\n',\n )}`;\n await fs.promises.writeFile(gitignorePath, newGitignoreContent, {\n encoding: 'utf8',\n flag: 'w',\n });\n clack.log.success(\n `Updated ${chalk.bold.cyan(\n '.gitignore',\n )} to include environment files.`,\n );\n } catch (error) {\n clack.log.warning(\n `Failed to update ${chalk.bold.cyan(\n '.gitignore',\n )} to include environment files. Error: ${error.message}`,\n );\n }\n }\n } else {\n try {\n const newGitignoreContent = `${envFiles.join('\\n')}\\n`;\n await fs.promises.writeFile(\n path.join(installDir, '.gitignore'),\n newGitignoreContent,\n {\n encoding: 'utf8',\n flag: 'w',\n },\n );\n clack.log.success(\n `Created ${chalk.bold.cyan('.gitignore')} with environment files.`,\n );\n } catch (error) {\n clack.log.warning(\n `Failed to create ${chalk.bold.cyan(\n '.gitignore',\n )} with environment files. Error: ${error.message}`,\n );\n }\n }\n\n analytics.capture('wizard interaction', {\n action: 'added environment variables',\n integration,\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"environment.js","sourceRoot":"","sources":["../../../src/utils/environment.ts"],"names":[],"mappings":";;;;;AAYA,0CAIC;AAED,0EAsJC;AAED,gDAiEC;AA3OD,gDAAwB;AACxB,wDAA+B;AAC/B,4CAAoB;AACpB,oDAA4B;AAC5B,kDAA0B;AAC1B,6CAA+C;AAE/C,2CAAwC;AACxC,+CAAkD;AAElD,0DAA2B;AAE3B,SAAgB,eAAe;IAC7B,MAAM,MAAM,GAAG,IAAA,kBAAO,EAAC,gBAAgB,CAAC,CAAC;IAE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,CAAC,CAAC,6BAA6B,CAAC,CAAC,CAAC,EAAE,CAAC;QACxE,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,iGAAiG;IACjG,OAAO,cAAc,CAAC;AACxB,CAAC","sourcesContent":["import path from 'path';\nimport readEnv from 'read-env';\nimport fs from 'fs';\nimport clack from './clack';\nimport chalk from 'chalk';\nimport { getDotGitignore } from './file-utils';\nimport { Integration } from '../lib/constants';\nimport { analytics } from './analytics';\nimport { getPackageDotJson } from './clack-utils';\nimport type { WizardOptions } from './types';\nimport fg from 'fast-glob';\n\nexport function readEnvironment(): Record<string, unknown> {\n const result = readEnv('POSTHOG_WIZARD');\n\n return result;\n}\n\nexport async function addOrUpdateEnvironmentVariables({\n installDir,\n variables,\n integration,\n}: {\n installDir: string;\n variables: Record<string, string>;\n integration: Integration;\n}): Promise<void> {\n const envVarContent = Object.entries(variables)\n .map(([key, value]) => `${key}=${value}`)\n .join('\\n');\n\n const dotEnvLocalFilePath = path.join(installDir, '.env.local');\n const dotEnvFilePath = path.join(installDir, '.env');\n const targetEnvFilePath = fs.existsSync(dotEnvLocalFilePath)\n ? dotEnvLocalFilePath\n : dotEnvFilePath;\n\n const dotEnvFileExists = fs.existsSync(targetEnvFilePath);\n\n const relativeEnvFilePath = path.relative(installDir, targetEnvFilePath);\n\n if (dotEnvFileExists) {\n try {\n let dotEnvFileContent = fs.readFileSync(targetEnvFilePath, 'utf8');\n let updated = false;\n\n for (const [key, value] of Object.entries(variables)) {\n const regex = new RegExp(`^${key}=.*$`, 'm');\n\n if (dotEnvFileContent.match(regex)) {\n dotEnvFileContent = dotEnvFileContent.replace(\n regex,\n `${key}=${value}`,\n );\n updated = true;\n } else {\n if (!dotEnvFileContent.endsWith('\\n')) {\n dotEnvFileContent += '\\n';\n }\n dotEnvFileContent += `${key}=${value}\\n`;\n updated = true;\n }\n }\n\n if (updated) {\n await fs.promises.writeFile(targetEnvFilePath, dotEnvFileContent, {\n encoding: 'utf8',\n flag: 'w',\n });\n clack.log.success(\n `Updated environment variables in ${chalk.bold.cyan(\n relativeEnvFilePath,\n )}`,\n );\n } else {\n clack.log.success(\n `${chalk.bold.cyan(\n relativeEnvFilePath,\n )} already has the necessary environment variables.`,\n );\n }\n } catch (error) {\n clack.log.warning(\n `Failed to update environment variables in ${chalk.bold.cyan(\n relativeEnvFilePath,\n )}. Please update them manually. Error: ${error.message}`,\n );\n }\n } else {\n try {\n await fs.promises.writeFile(targetEnvFilePath, envVarContent, {\n encoding: 'utf8',\n flag: 'w',\n });\n clack.log.success(\n `Created ${chalk.bold.cyan(\n relativeEnvFilePath,\n )} with environment variables.`,\n );\n } catch (error) {\n clack.log.warning(\n `Failed to create ${chalk.bold.cyan(\n relativeEnvFilePath,\n )} with environment variables. Please add them manually. Error: ${\n error.message\n }`,\n );\n }\n }\n\n const gitignorePath = getDotGitignore({ installDir });\n const envFiles = ['.env', '.env.local'];\n\n if (gitignorePath) {\n const gitignoreContent = fs.readFileSync(gitignorePath, 'utf8');\n const missingEnvFiles = envFiles.filter(\n (file) => !gitignoreContent.includes(file),\n );\n\n if (missingEnvFiles.length > 0) {\n try {\n const newGitignoreContent = `${gitignoreContent}\\n${missingEnvFiles.join(\n '\\n',\n )}`;\n await fs.promises.writeFile(gitignorePath, newGitignoreContent, {\n encoding: 'utf8',\n flag: 'w',\n });\n clack.log.success(\n `Updated ${chalk.bold.cyan(\n '.gitignore',\n )} to include environment files.`,\n );\n } catch (error) {\n clack.log.warning(\n `Failed to update ${chalk.bold.cyan(\n '.gitignore',\n )} to include environment files. Error: ${error.message}`,\n );\n }\n }\n } else {\n try {\n const newGitignoreContent = `${envFiles.join('\\n')}\\n`;\n await fs.promises.writeFile(\n path.join(installDir, '.gitignore'),\n newGitignoreContent,\n {\n encoding: 'utf8',\n flag: 'w',\n },\n );\n clack.log.success(\n `Created ${chalk.bold.cyan('.gitignore')} with environment files.`,\n );\n } catch (error) {\n clack.log.warning(\n `Failed to create ${chalk.bold.cyan(\n '.gitignore',\n )} with environment files. Error: ${error.message}`,\n );\n }\n }\n\n analytics.capture('wizard interaction', {\n action: 'added environment variables',\n integration,\n });\n}\n\nexport async function detectEnvVarPrefix(\n options: WizardOptions,\n): Promise<string> {\n const packageJson = await getPackageDotJson(options);\n\n const deps = { ...packageJson.dependencies, ...packageJson.devDependencies };\n const has = (name: string) => name in deps;\n const hasAnyFile = async (patterns: string[]) => {\n const matches = await fg(patterns, {\n cwd: options.installDir,\n absolute: false,\n onlyFiles: true,\n ignore: ['**/node_modules/**'],\n });\n return matches.length > 0;\n };\n\n // --- Next.js\n if (has('next') || (await hasAnyFile(['**/next.config.{js,ts,mjs,cjs}']))) {\n return 'NEXT_PUBLIC_';\n }\n\n // --- Create React App\n if (\n has('react-scripts') ||\n has('create-react-app') ||\n (await hasAnyFile(['**/config-overrides.js']))\n ) {\n return 'REACT_APP_';\n }\n\n // --- Vite (vanilla, TanStack, Solid, etc.)\n // Note: Vite does not need PUBLIC_ but we use it to follow the docs, to improve the chances of an LLM getting it right.\n if (has('vite') || (await hasAnyFile(['**/vite.config.{js,ts,mjs,cjs}']))) {\n return 'VITE_PUBLIC_';\n }\n\n // --- SvelteKit\n if (\n has('@sveltejs/kit') ||\n (await hasAnyFile(['**/svelte.config.{js,ts}']))\n ) {\n return 'PUBLIC_';\n }\n\n // --- TanStack Start (uses Vite)\n if (\n has('@tanstack/start') ||\n (await hasAnyFile(['**/tanstack.config.{js,ts}']))\n ) {\n return 'VITE_PUBLIC_';\n }\n\n // --- SolidStart (uses Vite)\n if (has('solid-start') || (await hasAnyFile(['**/solid.config.{js,ts}']))) {\n return 'VITE_PUBLIC_';\n }\n\n // --- Astro\n if (has('astro') || (await hasAnyFile(['**/astro.config.{js,ts,mjs}']))) {\n return 'PUBLIC_';\n }\n\n // We default to Vite if we can't detect a specific framework, since it's the most commonly used.\n return 'VITE_PUBLIC_';\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@posthog/wizard",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.1",
|
|
4
4
|
"homepage": "https://github.com/posthog/wizard",
|
|
5
5
|
"repository": "https://github.com/posthog/wizard",
|
|
6
6
|
"description": "The PostHog wizard helps you to configure your project",
|
|
@@ -71,6 +71,7 @@
|
|
|
71
71
|
"eslint": "^8.18.0",
|
|
72
72
|
"eslint-config-prettier": "^8.3.0",
|
|
73
73
|
"eslint-plugin-jest": "^25.3.0",
|
|
74
|
+
"husky": "^9.1.7",
|
|
74
75
|
"jest": "^29.5.0",
|
|
75
76
|
"prettier": "^2.8.7",
|
|
76
77
|
"rimraf": "^3.0.2",
|