@datalyr/wizard 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,1275 @@
1
+ // src/index.ts
2
+ import path5 from "path";
3
+
4
+ // src/detection/detector.ts
5
+ import path2 from "path";
6
+
7
+ // src/utils/fs.ts
8
+ import fs from "fs-extra";
9
+ import path from "path";
10
+ import { glob } from "glob";
11
+ async function fileExists(filePath) {
12
+ try {
13
+ await fs.access(filePath);
14
+ return true;
15
+ } catch {
16
+ return false;
17
+ }
18
+ }
19
+ async function readFile(filePath) {
20
+ try {
21
+ return await fs.readFile(filePath, "utf-8");
22
+ } catch {
23
+ return null;
24
+ }
25
+ }
26
+ async function writeFile(filePath, content) {
27
+ await fs.ensureDir(path.dirname(filePath));
28
+ await fs.writeFile(filePath, content, "utf-8");
29
+ }
30
+ async function readJson(filePath) {
31
+ try {
32
+ return await fs.readJson(filePath);
33
+ } catch {
34
+ return null;
35
+ }
36
+ }
37
+ async function readPackageJson(cwd) {
38
+ return readJson(path.join(cwd, "package.json"));
39
+ }
40
+ async function findFile(cwd, patterns) {
41
+ for (const pattern of patterns) {
42
+ const matches = await glob(pattern, { cwd, nodir: true });
43
+ if (matches.length > 0) {
44
+ return path.join(cwd, matches[0]);
45
+ }
46
+ }
47
+ return null;
48
+ }
49
+ async function findFiles(cwd, pattern) {
50
+ const matches = await glob(pattern, {
51
+ cwd,
52
+ ignore: ["node_modules/**", ".git/**"]
53
+ });
54
+ return matches.map((f) => path.join(cwd, f));
55
+ }
56
+
57
+ // src/detection/detector.ts
58
+ async function detectFramework(cwd) {
59
+ const signals = [];
60
+ const pkg = await readPackageJson(cwd);
61
+ const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
62
+ if (await fileExists(path2.join(cwd, "Package.swift"))) {
63
+ signals.push({ framework: "ios", score: 100, signal: "Package.swift found" });
64
+ }
65
+ const xcodeprojs = await findFile(cwd, ["*.xcodeproj", "*.xcworkspace"]);
66
+ if (xcodeprojs) {
67
+ signals.push({ framework: "ios", score: 90, signal: "Xcode project found" });
68
+ }
69
+ if (!pkg) {
70
+ const iosScore = signals.filter((s) => s.framework === "ios").reduce((a, b) => a + b.score, 0);
71
+ if (iosScore > 0) {
72
+ return buildResult("ios", signals, null);
73
+ }
74
+ return buildResult("unknown", [], null);
75
+ }
76
+ if (deps.next) {
77
+ signals.push({ framework: "nextjs", score: 100, signal: "next in dependencies" });
78
+ if (await fileExists(path2.join(cwd, "app", "layout.tsx")) || await fileExists(path2.join(cwd, "app", "layout.js"))) {
79
+ signals.push({ framework: "nextjs", score: 20, signal: "App Router detected" });
80
+ }
81
+ if (await fileExists(path2.join(cwd, "pages", "_app.tsx")) || await fileExists(path2.join(cwd, "pages", "_app.js"))) {
82
+ signals.push({ framework: "nextjs", score: 15, signal: "Pages Router detected" });
83
+ }
84
+ }
85
+ if (deps.expo) {
86
+ signals.push({ framework: "expo", score: 100, signal: "expo in dependencies" });
87
+ }
88
+ if (deps["react-native"] && !deps.expo) {
89
+ signals.push({ framework: "react-native", score: 100, signal: "react-native in dependencies" });
90
+ }
91
+ if (deps["@remix-run/react"] || deps["@remix-run/node"]) {
92
+ signals.push({ framework: "remix", score: 100, signal: "@remix-run packages found" });
93
+ }
94
+ if (deps.astro) {
95
+ signals.push({ framework: "astro", score: 100, signal: "astro in dependencies" });
96
+ }
97
+ if (deps["@sveltejs/kit"]) {
98
+ signals.push({ framework: "sveltekit", score: 100, signal: "@sveltejs/kit in dependencies" });
99
+ } else if (deps.svelte) {
100
+ signals.push({ framework: "svelte", score: 80, signal: "svelte in dependencies" });
101
+ }
102
+ if (deps.nuxt) {
103
+ signals.push({ framework: "nuxt", score: 100, signal: "nuxt in dependencies" });
104
+ } else if (deps.vue) {
105
+ signals.push({ framework: "vue", score: 80, signal: "vue in dependencies" });
106
+ }
107
+ if (deps.react && deps["react-dom"]) {
108
+ if (!deps.next && !deps["@remix-run/react"] && !deps["react-native"] && !deps.expo) {
109
+ if (deps.vite || deps["@vitejs/plugin-react"]) {
110
+ signals.push({ framework: "react-vite", score: 90, signal: "React + Vite" });
111
+ } else if (deps["react-scripts"]) {
112
+ signals.push({ framework: "react", score: 85, signal: "Create React App" });
113
+ } else {
114
+ signals.push({ framework: "react", score: 70, signal: "React project" });
115
+ }
116
+ }
117
+ }
118
+ if (deps.express || deps.fastify || deps.koa || deps.hapi) {
119
+ if (!deps.react && !deps.vue && !deps.svelte) {
120
+ signals.push({ framework: "node", score: 80, signal: "Node.js server framework" });
121
+ }
122
+ }
123
+ const frameworkScores = /* @__PURE__ */ new Map();
124
+ signals.forEach((s) => {
125
+ const current = frameworkScores.get(s.framework) || 0;
126
+ frameworkScores.set(s.framework, current + s.score);
127
+ });
128
+ let bestFramework = "unknown";
129
+ let bestScore = 0;
130
+ frameworkScores.forEach((score, framework) => {
131
+ if (score > bestScore) {
132
+ bestScore = score;
133
+ bestFramework = framework;
134
+ }
135
+ });
136
+ return buildResult(bestFramework, signals, pkg);
137
+ }
138
+ function buildResult(framework, signals, pkg) {
139
+ const relevantSignals = signals.filter((s) => s.framework === framework).map((s) => s.signal);
140
+ const confidence = Math.min(100, signals.filter((s) => s.framework === framework).reduce((a, b) => a + b.score, 0));
141
+ const language = detectLanguage(pkg);
142
+ const sdks = getSDKsForFramework(framework);
143
+ const hasAppRouter = framework === "nextjs" && relevantSignals.some((s) => s.includes("App Router"));
144
+ return {
145
+ framework,
146
+ confidence,
147
+ signals: relevantSignals,
148
+ sdks,
149
+ language,
150
+ hasAppRouter,
151
+ isExpo: framework === "expo"
152
+ };
153
+ }
154
+ function detectLanguage(pkg) {
155
+ if (!pkg) return "javascript";
156
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
157
+ return deps.typescript ? "typescript" : "javascript";
158
+ }
159
+ function getSDKsForFramework(framework) {
160
+ switch (framework) {
161
+ case "nextjs":
162
+ case "remix":
163
+ case "sveltekit":
164
+ case "nuxt":
165
+ case "astro":
166
+ return ["@datalyr/web", "@datalyr/api"];
167
+ case "react":
168
+ case "react-vite":
169
+ case "svelte":
170
+ case "vue":
171
+ return ["@datalyr/web"];
172
+ case "react-native":
173
+ case "expo":
174
+ return ["@datalyr/react-native"];
175
+ case "ios":
176
+ return ["DatalyrSDK"];
177
+ case "node":
178
+ return ["@datalyr/api"];
179
+ default:
180
+ return ["@datalyr/web"];
181
+ }
182
+ }
183
+ function getFrameworkDisplayName(framework) {
184
+ const names = {
185
+ nextjs: "Next.js",
186
+ react: "React (Create React App)",
187
+ "react-vite": "React (Vite)",
188
+ svelte: "Svelte",
189
+ sveltekit: "SvelteKit",
190
+ vue: "Vue",
191
+ nuxt: "Nuxt",
192
+ remix: "Remix",
193
+ astro: "Astro",
194
+ "react-native": "React Native",
195
+ expo: "Expo",
196
+ ios: "iOS (Swift)",
197
+ node: "Node.js",
198
+ unknown: "Unknown"
199
+ };
200
+ return names[framework];
201
+ }
202
+
203
+ // src/utils/package-manager.ts
204
+ import path3 from "path";
205
+ async function detectPackageManager(cwd) {
206
+ if (await fileExists(path3.join(cwd, "bun.lockb"))) {
207
+ return "bun";
208
+ }
209
+ if (await fileExists(path3.join(cwd, "pnpm-lock.yaml"))) {
210
+ return "pnpm";
211
+ }
212
+ if (await fileExists(path3.join(cwd, "yarn.lock"))) {
213
+ return "yarn";
214
+ }
215
+ if (await fileExists(path3.join(cwd, "package-lock.json"))) {
216
+ return "npm";
217
+ }
218
+ return "npm";
219
+ }
220
+ function getInstallCommand(pm, packages, dev = false) {
221
+ const pkgList = packages.join(" ");
222
+ switch (pm) {
223
+ case "npm":
224
+ return dev ? `npm install -D ${pkgList}` : `npm install ${pkgList}`;
225
+ case "yarn":
226
+ return dev ? `yarn add -D ${pkgList}` : `yarn add ${pkgList}`;
227
+ case "pnpm":
228
+ return dev ? `pnpm add -D ${pkgList}` : `pnpm add ${pkgList}`;
229
+ case "bun":
230
+ return dev ? `bun add -d ${pkgList}` : `bun add ${pkgList}`;
231
+ }
232
+ }
233
+
234
+ // src/generators/templates/nextjs.ts
235
+ function generateNextJSFiles(options) {
236
+ const { language, hasAppRouter } = options;
237
+ const ext = language === "typescript" ? "tsx" : "jsx";
238
+ const tsExt = language === "typescript" ? "ts" : "js";
239
+ const files = [];
240
+ if (hasAppRouter) {
241
+ files.push({
242
+ path: `app/providers.${ext}`,
243
+ action: "create",
244
+ description: "Datalyr provider component",
245
+ content: generateAppRouterProvider(language)
246
+ });
247
+ files.push({
248
+ path: `lib/datalyr.${tsExt}`,
249
+ action: "create",
250
+ description: "Server-side Datalyr instance",
251
+ content: generateServerInstance(language)
252
+ });
253
+ } else {
254
+ files.push({
255
+ path: `lib/datalyr.${tsExt}`,
256
+ action: "create",
257
+ description: "Datalyr initialization",
258
+ content: generatePagesRouterInit(language)
259
+ });
260
+ files.push({
261
+ path: `lib/datalyr-server.${tsExt}`,
262
+ action: "create",
263
+ description: "Server-side Datalyr instance",
264
+ content: generateServerInstance(language)
265
+ });
266
+ }
267
+ return files;
268
+ }
269
+ function generateAppRouterProvider(language) {
270
+ if (language === "typescript") {
271
+ return `'use client';
272
+
273
+ import datalyr from '@datalyr/web';
274
+ import { useEffect } from 'react';
275
+
276
+ interface DatalyrProviderProps {
277
+ children: React.ReactNode;
278
+ }
279
+
280
+ export function DatalyrProvider({ children }: DatalyrProviderProps) {
281
+ useEffect(() => {
282
+ datalyr.init({
283
+ workspaceId: process.env.NEXT_PUBLIC_DATALYR_WORKSPACE_ID!,
284
+ debug: process.env.NODE_ENV === 'development',
285
+ trackSPA: true,
286
+ });
287
+ }, []);
288
+
289
+ return <>{children}</>;
290
+ }
291
+ `;
292
+ }
293
+ return `'use client';
294
+
295
+ import datalyr from '@datalyr/web';
296
+ import { useEffect } from 'react';
297
+
298
+ export function DatalyrProvider({ children }) {
299
+ useEffect(() => {
300
+ datalyr.init({
301
+ workspaceId: process.env.NEXT_PUBLIC_DATALYR_WORKSPACE_ID,
302
+ debug: process.env.NODE_ENV === 'development',
303
+ trackSPA: true,
304
+ });
305
+ }, []);
306
+
307
+ return <>{children}</>;
308
+ }
309
+ `;
310
+ }
311
+ function generateServerInstance(language) {
312
+ if (language === "typescript") {
313
+ return `import Datalyr from '@datalyr/api';
314
+
315
+ // Server-side Datalyr instance
316
+ export const datalyr = new Datalyr(process.env.DATALYR_API_KEY!);
317
+
318
+ // Helper to track server-side events
319
+ export async function trackServerEvent(
320
+ event: string,
321
+ properties?: Record<string, unknown>,
322
+ userId?: string,
323
+ ) {
324
+ await datalyr.track({
325
+ event,
326
+ properties,
327
+ userId,
328
+ timestamp: new Date().toISOString(),
329
+ });
330
+ }
331
+ `;
332
+ }
333
+ return `import Datalyr from '@datalyr/api';
334
+
335
+ // Server-side Datalyr instance
336
+ export const datalyr = new Datalyr(process.env.DATALYR_API_KEY);
337
+
338
+ // Helper to track server-side events
339
+ export async function trackServerEvent(event, properties, userId) {
340
+ await datalyr.track({
341
+ event,
342
+ properties,
343
+ userId,
344
+ timestamp: new Date().toISOString(),
345
+ });
346
+ }
347
+ `;
348
+ }
349
+ function generatePagesRouterInit(language) {
350
+ if (language === "typescript") {
351
+ return `import datalyr from '@datalyr/web';
352
+
353
+ let initialized = false;
354
+
355
+ export function initDatalyr(): void {
356
+ if (initialized || typeof window === 'undefined') return;
357
+
358
+ datalyr.init({
359
+ workspaceId: process.env.NEXT_PUBLIC_DATALYR_WORKSPACE_ID!,
360
+ debug: process.env.NODE_ENV === 'development',
361
+ trackSPA: true,
362
+ });
363
+
364
+ initialized = true;
365
+ }
366
+
367
+ export { datalyr };
368
+ `;
369
+ }
370
+ return `import datalyr from '@datalyr/web';
371
+
372
+ let initialized = false;
373
+
374
+ export function initDatalyr() {
375
+ if (initialized || typeof window === 'undefined') return;
376
+
377
+ datalyr.init({
378
+ workspaceId: process.env.NEXT_PUBLIC_DATALYR_WORKSPACE_ID,
379
+ debug: process.env.NODE_ENV === 'development',
380
+ trackSPA: true,
381
+ });
382
+
383
+ initialized = true;
384
+ }
385
+
386
+ export { datalyr };
387
+ `;
388
+ }
389
+
390
+ // src/generators/templates/react.ts
391
+ function generateReactFiles(options) {
392
+ const { language, isVite } = options;
393
+ const ext = language === "typescript" ? "ts" : "js";
394
+ return [
395
+ {
396
+ path: `src/lib/datalyr.${ext}`,
397
+ action: "create",
398
+ description: "Datalyr initialization",
399
+ content: generateReactInit(language)
400
+ }
401
+ ];
402
+ }
403
+ function generateReactInit(language) {
404
+ if (language === "typescript") {
405
+ return `import datalyr from '@datalyr/web';
406
+
407
+ let initialized = false;
408
+
409
+ export function initDatalyr(): void {
410
+ if (initialized || typeof window === 'undefined') return;
411
+
412
+ datalyr.init({
413
+ workspaceId: import.meta.env.VITE_DATALYR_WORKSPACE_ID,
414
+ debug: import.meta.env.DEV,
415
+ trackSPA: true,
416
+ });
417
+
418
+ initialized = true;
419
+ }
420
+
421
+ // Re-export for convenience
422
+ export { datalyr };
423
+
424
+ // Usage in your main.tsx/App.tsx:
425
+ // import { initDatalyr } from './lib/datalyr';
426
+ // initDatalyr();
427
+ `;
428
+ }
429
+ return `import datalyr from '@datalyr/web';
430
+
431
+ let initialized = false;
432
+
433
+ export function initDatalyr() {
434
+ if (initialized || typeof window === 'undefined') return;
435
+
436
+ datalyr.init({
437
+ workspaceId: import.meta.env.VITE_DATALYR_WORKSPACE_ID,
438
+ debug: import.meta.env.DEV,
439
+ trackSPA: true,
440
+ });
441
+
442
+ initialized = true;
443
+ }
444
+
445
+ // Re-export for convenience
446
+ export { datalyr };
447
+
448
+ // Usage in your main.jsx/App.jsx:
449
+ // import { initDatalyr } from './lib/datalyr';
450
+ // initDatalyr();
451
+ `;
452
+ }
453
+
454
+ // src/generators/templates/react-native.ts
455
+ function generateReactNativeFiles(options) {
456
+ const { language, isExpo, apiKey } = options;
457
+ const ext = language === "typescript" ? "ts" : "js";
458
+ return [
459
+ {
460
+ path: `src/utils/datalyr.${ext}`,
461
+ action: "create",
462
+ description: "Datalyr initialization",
463
+ content: generateReactNativeInit(language, isExpo, apiKey)
464
+ }
465
+ ];
466
+ }
467
+ function generateReactNativeInit(language, isExpo, apiKey) {
468
+ const importPath = isExpo ? "@datalyr/react-native/expo" : "@datalyr/react-native";
469
+ if (language === "typescript") {
470
+ return `import { Datalyr } from '${importPath}';
471
+
472
+ let initialized = false;
473
+
474
+ export async function initDatalyr(): Promise<void> {
475
+ if (initialized) return;
476
+
477
+ await Datalyr.initialize({
478
+ apiKey: '${apiKey}',
479
+ enableAutoEvents: true,
480
+ enableAttribution: true,
481
+ debug: __DEV__,
482
+ });
483
+
484
+ initialized = true;
485
+ }
486
+
487
+ // Re-export for convenience
488
+ export { Datalyr };
489
+
490
+ // Track custom events
491
+ export function trackEvent(event: string, properties?: Record<string, unknown>): void {
492
+ Datalyr.track(event, properties);
493
+ }
494
+
495
+ // Identify users
496
+ export function identifyUser(userId: string, traits?: Record<string, unknown>): void {
497
+ Datalyr.identify(userId, traits);
498
+ }
499
+ `;
500
+ }
501
+ return `import { Datalyr } from '${importPath}';
502
+
503
+ let initialized = false;
504
+
505
+ export async function initDatalyr() {
506
+ if (initialized) return;
507
+
508
+ await Datalyr.initialize({
509
+ apiKey: '${apiKey}',
510
+ enableAutoEvents: true,
511
+ enableAttribution: true,
512
+ debug: __DEV__,
513
+ });
514
+
515
+ initialized = true;
516
+ }
517
+
518
+ // Re-export for convenience
519
+ export { Datalyr };
520
+
521
+ // Track custom events
522
+ export function trackEvent(event, properties) {
523
+ Datalyr.track(event, properties);
524
+ }
525
+
526
+ // Identify users
527
+ export function identifyUser(userId, traits) {
528
+ Datalyr.identify(userId, traits);
529
+ }
530
+ `;
531
+ }
532
+
533
+ // src/installers/env.ts
534
+ import path4 from "path";
535
+
536
+ // src/cli/ui.ts
537
+ import ora from "ora";
538
+ import chalk from "chalk";
539
+ var currentSpinner = null;
540
+ function startSpinner(text) {
541
+ if (currentSpinner) {
542
+ currentSpinner.stop();
543
+ }
544
+ currentSpinner = ora({ text, color: "cyan" }).start();
545
+ return currentSpinner;
546
+ }
547
+ function succeedSpinner(text) {
548
+ if (currentSpinner) {
549
+ currentSpinner.succeed(text);
550
+ currentSpinner = null;
551
+ }
552
+ }
553
+ function failSpinner(text) {
554
+ if (currentSpinner) {
555
+ currentSpinner.fail(text);
556
+ currentSpinner = null;
557
+ }
558
+ }
559
+ function stopSpinner() {
560
+ if (currentSpinner) {
561
+ currentSpinner.stop();
562
+ currentSpinner = null;
563
+ }
564
+ }
565
+ function printWelcome() {
566
+ console.log();
567
+ console.log(chalk.cyan("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557"));
568
+ console.log(chalk.cyan("\u2551") + chalk.bold(" Welcome to Datalyr Wizard! ") + chalk.cyan("\u2551"));
569
+ console.log(chalk.cyan("\u2551") + " AI-powered SDK installation for Datalyr " + chalk.cyan("\u2551"));
570
+ console.log(chalk.cyan("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"));
571
+ console.log();
572
+ }
573
+ function printSuccess() {
574
+ console.log();
575
+ console.log(chalk.green.bold("Installation complete!"));
576
+ console.log();
577
+ console.log(chalk.bold("Next steps:"));
578
+ console.log();
579
+ console.log(" 1. Add your workspace ID to .env.local:");
580
+ console.log(chalk.cyan(" NEXT_PUBLIC_DATALYR_WORKSPACE_ID=your_workspace_id"));
581
+ console.log();
582
+ console.log(" 2. Start tracking events:");
583
+ console.log(chalk.cyan(" datalyr.track('button_clicked', { button: 'signup' })"));
584
+ console.log();
585
+ console.log(" 3. View your data:");
586
+ console.log(chalk.cyan(" https://app.datalyr.com/dashboard"));
587
+ console.log();
588
+ console.log(chalk.gray("Documentation: https://docs.datalyr.com"));
589
+ console.log(chalk.gray("Support: hello@datalyr.com"));
590
+ console.log();
591
+ }
592
+ function printPlan(plan) {
593
+ console.log();
594
+ console.log(chalk.bold("Installation Plan:"));
595
+ console.log();
596
+ if (plan.packages.length > 0) {
597
+ console.log(chalk.cyan(" \u{1F4E6} Packages:"));
598
+ plan.packages.forEach((pkg) => {
599
+ console.log(` \u2022 ${pkg}`);
600
+ });
601
+ console.log();
602
+ }
603
+ if (plan.files.length > 0) {
604
+ console.log(chalk.cyan(" \u{1F4DD} Files to create/update:"));
605
+ plan.files.forEach((file) => {
606
+ const actionIcon = file.action === "create" ? chalk.green("(create)") : chalk.yellow("(update)");
607
+ console.log(` \u2022 ${file.path} ${actionIcon}`);
608
+ });
609
+ console.log();
610
+ }
611
+ }
612
+ function printDetection(result) {
613
+ console.log();
614
+ console.log(chalk.bold("Detected Configuration:"));
615
+ console.log(` Framework: ${chalk.cyan(result.framework)}`);
616
+ console.log(` Language: ${chalk.cyan(result.language)}`);
617
+ console.log(` SDK Needs: ${chalk.cyan(result.sdks.join(" + "))}`);
618
+ console.log();
619
+ }
620
+ function printError(message, details) {
621
+ console.log();
622
+ console.log(chalk.red.bold("Error:"), message);
623
+ if (details) {
624
+ console.log(chalk.gray(details));
625
+ }
626
+ console.log();
627
+ }
628
+ function printDryRun(plan) {
629
+ console.log();
630
+ console.log(chalk.yellow.bold("[DRY RUN] No changes will be made"));
631
+ console.log();
632
+ if (plan.commands.length > 0) {
633
+ console.log(chalk.bold("Would run:"));
634
+ plan.commands.forEach((cmd) => console.log(chalk.cyan(` $ ${cmd}`)));
635
+ console.log();
636
+ }
637
+ if (plan.files.length > 0) {
638
+ console.log(chalk.bold("Would create/update files:"));
639
+ plan.files.forEach((file) => {
640
+ console.log(chalk.cyan(` ${file.path} (${file.action})`));
641
+ });
642
+ console.log();
643
+ }
644
+ }
645
+
646
+ // src/installers/env.ts
647
+ async function updateEnvFile(cwd, envVars, options = {}) {
648
+ if (envVars.length === 0) return true;
649
+ const envFileName = options.envFile || ".env.local";
650
+ const envPath = path4.join(cwd, envFileName);
651
+ const examplePath = path4.join(cwd, ".env.example");
652
+ if (options.dryRun) {
653
+ return true;
654
+ }
655
+ const spinner = startSpinner(`Updating ${envFileName}...`);
656
+ try {
657
+ let existingContent = "";
658
+ if (await fileExists(envPath)) {
659
+ existingContent = await readFile(envPath) || "";
660
+ }
661
+ const existingVars = parseEnvFile(existingContent);
662
+ const lines = [];
663
+ if (existingContent) {
664
+ lines.push(existingContent.trim());
665
+ lines.push("");
666
+ }
667
+ const newVars = envVars.filter((v) => !existingVars.has(v.key));
668
+ if (newVars.length > 0) {
669
+ lines.push("# Datalyr Analytics");
670
+ for (const envVar of newVars) {
671
+ if (envVar.description) {
672
+ lines.push(`# ${envVar.description}`);
673
+ }
674
+ lines.push(`${envVar.key}=${envVar.value}`);
675
+ }
676
+ }
677
+ await writeFile(envPath, lines.join("\n") + "\n");
678
+ if (await fileExists(examplePath)) {
679
+ await updateEnvExample(examplePath, envVars);
680
+ }
681
+ succeedSpinner(`Updated ${envFileName}`);
682
+ return true;
683
+ } catch (error) {
684
+ console.error(error);
685
+ return false;
686
+ }
687
+ }
688
+ async function updateEnvExample(examplePath, envVars) {
689
+ let content = await readFile(examplePath) || "";
690
+ const existingVars = parseEnvFile(content);
691
+ const newVars = envVars.filter((v) => !existingVars.has(v.key));
692
+ if (newVars.length === 0) return;
693
+ const lines = content.trim().split("\n");
694
+ lines.push("");
695
+ lines.push("# Datalyr Analytics");
696
+ for (const envVar of newVars) {
697
+ const exampleValue = envVar.isPublic ? "your_workspace_id" : "dk_your_api_key";
698
+ lines.push(`${envVar.key}=${exampleValue}`);
699
+ }
700
+ await writeFile(examplePath, lines.join("\n") + "\n");
701
+ }
702
+ function parseEnvFile(content) {
703
+ const vars = /* @__PURE__ */ new Set();
704
+ const lines = content.split("\n");
705
+ for (const line of lines) {
706
+ const trimmed = line.trim();
707
+ if (trimmed && !trimmed.startsWith("#")) {
708
+ const match = trimmed.match(/^([A-Z_][A-Z0-9_]*)=/);
709
+ if (match) {
710
+ vars.add(match[1]);
711
+ }
712
+ }
713
+ }
714
+ return vars;
715
+ }
716
+ function getEnvVarsForFramework(framework, apiKey) {
717
+ const vars = [];
718
+ if (["nextjs", "react", "react-vite", "svelte", "sveltekit", "vue", "nuxt", "remix", "astro"].includes(framework)) {
719
+ vars.push({
720
+ key: "NEXT_PUBLIC_DATALYR_WORKSPACE_ID",
721
+ value: "",
722
+ description: "Your Datalyr workspace ID (get from dashboard)",
723
+ isPublic: true
724
+ });
725
+ }
726
+ if (["nextjs", "sveltekit", "nuxt", "remix", "astro", "node"].includes(framework)) {
727
+ vars.push({
728
+ key: "DATALYR_API_KEY",
729
+ value: apiKey,
730
+ description: "Datalyr API key for server-side tracking",
731
+ isPublic: false
732
+ });
733
+ }
734
+ return vars;
735
+ }
736
+
737
+ // src/generators/index.ts
738
+ function generateInstallationPlan(context, apiKey) {
739
+ const packages = context.sdks.filter((sdk) => sdk !== "DatalyrSDK");
740
+ const files = generateFilesForFramework(context, apiKey);
741
+ const envVars = getEnvVarsForFramework(context.framework, apiKey);
742
+ const postInstallSteps = getPostInstallSteps(context);
743
+ return {
744
+ packages,
745
+ files,
746
+ envVars,
747
+ postInstallSteps
748
+ };
749
+ }
750
+ function generateFilesForFramework(context, apiKey) {
751
+ const { framework, language } = context;
752
+ switch (framework) {
753
+ case "nextjs":
754
+ return generateNextJSFiles({
755
+ language,
756
+ hasAppRouter: context.entryPoints.some((p) => p.includes("app/layout")),
757
+ apiKey
758
+ });
759
+ case "react":
760
+ case "react-vite":
761
+ return generateReactFiles({
762
+ language,
763
+ isVite: framework === "react-vite"
764
+ });
765
+ case "react-native":
766
+ case "expo":
767
+ return generateReactNativeFiles({
768
+ language,
769
+ isExpo: framework === "expo",
770
+ apiKey
771
+ });
772
+ case "sveltekit":
773
+ return generateSvelteKitFiles(language, apiKey);
774
+ case "svelte":
775
+ return generateSvelteFiles(language);
776
+ case "node":
777
+ return generateNodeFiles(language, apiKey);
778
+ case "ios":
779
+ return generateIOSFiles(apiKey);
780
+ default:
781
+ return generateGenericWebFiles(language);
782
+ }
783
+ }
784
+ function generateSvelteKitFiles(language, apiKey) {
785
+ const ext = language === "typescript" ? "ts" : "js";
786
+ return [
787
+ {
788
+ path: `src/lib/datalyr.${ext}`,
789
+ action: "create",
790
+ description: "Client-side Datalyr initialization",
791
+ content: `import datalyr from '@datalyr/web';
792
+ import { browser } from '$app/environment';
793
+
794
+ let initialized = false;
795
+
796
+ export function initDatalyr()${language === "typescript" ? ": void" : ""} {
797
+ if (initialized || !browser) return;
798
+
799
+ datalyr.init({
800
+ workspaceId: import.meta.env.VITE_DATALYR_WORKSPACE_ID,
801
+ debug: import.meta.env.DEV,
802
+ trackSPA: true,
803
+ });
804
+
805
+ initialized = true;
806
+ }
807
+
808
+ export { datalyr };
809
+ `
810
+ },
811
+ {
812
+ path: `src/lib/datalyr.server.${ext}`,
813
+ action: "create",
814
+ description: "Server-side Datalyr instance",
815
+ content: `import Datalyr from '@datalyr/api';
816
+ import { DATALYR_API_KEY } from '$env/static/private';
817
+
818
+ export const datalyr = new Datalyr(DATALYR_API_KEY);
819
+ `
820
+ }
821
+ ];
822
+ }
823
+ function generateSvelteFiles(language) {
824
+ const ext = language === "typescript" ? "ts" : "js";
825
+ return [
826
+ {
827
+ path: `src/lib/datalyr.${ext}`,
828
+ action: "create",
829
+ description: "Datalyr initialization",
830
+ content: `import datalyr from '@datalyr/web';
831
+
832
+ let initialized = false;
833
+
834
+ export function initDatalyr()${language === "typescript" ? ": void" : ""} {
835
+ if (initialized || typeof window === 'undefined') return;
836
+
837
+ datalyr.init({
838
+ workspaceId: import.meta.env.VITE_DATALYR_WORKSPACE_ID,
839
+ debug: import.meta.env.DEV,
840
+ trackSPA: true,
841
+ });
842
+
843
+ initialized = true;
844
+ }
845
+
846
+ export { datalyr };
847
+ `
848
+ }
849
+ ];
850
+ }
851
+ function generateNodeFiles(language, apiKey) {
852
+ const ext = language === "typescript" ? "ts" : "js";
853
+ return [
854
+ {
855
+ path: `src/lib/datalyr.${ext}`,
856
+ action: "create",
857
+ description: "Datalyr server instance",
858
+ content: language === "typescript" ? `import Datalyr from '@datalyr/api';
859
+
860
+ const apiKey = process.env.DATALYR_API_KEY;
861
+ if (!apiKey) {
862
+ throw new Error('DATALYR_API_KEY environment variable is required');
863
+ }
864
+
865
+ export const datalyr = new Datalyr(apiKey);
866
+
867
+ export async function trackEvent(
868
+ event: string,
869
+ properties?: Record<string, unknown>,
870
+ userId?: string,
871
+ ): Promise<void> {
872
+ await datalyr.track({
873
+ event,
874
+ properties,
875
+ userId,
876
+ timestamp: new Date().toISOString(),
877
+ });
878
+ }
879
+ ` : `import Datalyr from '@datalyr/api';
880
+
881
+ const apiKey = process.env.DATALYR_API_KEY;
882
+ if (!apiKey) {
883
+ throw new Error('DATALYR_API_KEY environment variable is required');
884
+ }
885
+
886
+ export const datalyr = new Datalyr(apiKey);
887
+
888
+ export async function trackEvent(event, properties, userId) {
889
+ await datalyr.track({
890
+ event,
891
+ properties,
892
+ userId,
893
+ timestamp: new Date().toISOString(),
894
+ });
895
+ }
896
+ `
897
+ }
898
+ ];
899
+ }
900
+ function generateIOSFiles(_apiKey) {
901
+ return [
902
+ {
903
+ path: "DatalyrConfig.swift",
904
+ action: "create",
905
+ description: "Datalyr iOS configuration",
906
+ content: `import DatalyrSDK
907
+ import Foundation
908
+
909
+ struct DatalyrConfig {
910
+ /// Initialize Datalyr SDK
911
+ /// Reads configuration from Info.plist for security
912
+ static func initialize() {
913
+ guard let apiKey = Bundle.main.object(forInfoDictionaryKey: "DATALYR_API_KEY") as? String,
914
+ let workspaceId = Bundle.main.object(forInfoDictionaryKey: "DATALYR_WORKSPACE_ID") as? String else {
915
+ #if DEBUG
916
+ fatalError("Datalyr API key or workspace ID not found in Info.plist. Add DATALYR_API_KEY and DATALYR_WORKSPACE_ID to your Info.plist.")
917
+ #else
918
+ print("[Datalyr] Warning: API key or workspace ID not configured")
919
+ return
920
+ #endif
921
+ }
922
+
923
+ Datalyr.shared.configure(
924
+ apiKey: apiKey,
925
+ workspaceId: workspaceId,
926
+ options: DatalyrOptions(
927
+ debug: false, // Set to true during development
928
+ enableAutoEvents: true,
929
+ enableAttribution: true
930
+ )
931
+ )
932
+ }
933
+ }
934
+
935
+ // SETUP INSTRUCTIONS:
936
+ // 1. Add to Info.plist:
937
+ // <key>DATALYR_API_KEY</key>
938
+ // <string>$(DATALYR_API_KEY)</string>
939
+ // <key>DATALYR_WORKSPACE_ID</key>
940
+ // <string>$(DATALYR_WORKSPACE_ID)</string>
941
+ //
942
+ // 2. Add to your .xcconfig file (recommended) or scheme environment:
943
+ // DATALYR_API_KEY = dk_your_api_key_here
944
+ // DATALYR_WORKSPACE_ID = your_workspace_id_here
945
+ //
946
+ // 3. Call DatalyrConfig.initialize() in your App's init or AppDelegate
947
+ `
948
+ },
949
+ {
950
+ path: "Datalyr.xcconfig",
951
+ action: "create",
952
+ description: "Datalyr configuration file (add your API key here)",
953
+ content: `// Datalyr Configuration
954
+ // Do NOT commit this file with real credentials to version control
955
+ // Add to .gitignore: *.xcconfig
956
+
957
+ DATALYR_API_KEY = YOUR_API_KEY_HERE
958
+ DATALYR_WORKSPACE_ID = YOUR_WORKSPACE_ID_HERE
959
+ `
960
+ }
961
+ ];
962
+ }
963
+ function generateGenericWebFiles(language) {
964
+ const ext = language === "typescript" ? "ts" : "js";
965
+ return [
966
+ {
967
+ path: `src/lib/datalyr.${ext}`,
968
+ action: "create",
969
+ description: "Datalyr initialization",
970
+ content: `import datalyr from '@datalyr/web';
971
+
972
+ export function initDatalyr()${language === "typescript" ? ": void" : ""} {
973
+ datalyr.init({
974
+ workspaceId: 'YOUR_WORKSPACE_ID',
975
+ debug: true,
976
+ });
977
+ }
978
+
979
+ export { datalyr };
980
+ `
981
+ }
982
+ ];
983
+ }
984
+ function getPostInstallSteps(context) {
985
+ const steps = [];
986
+ switch (context.framework) {
987
+ case "nextjs":
988
+ steps.push("Add your workspace ID to .env.local");
989
+ steps.push("Import DatalyrProvider in your app/layout.tsx");
990
+ break;
991
+ case "react":
992
+ case "react-vite":
993
+ steps.push("Add VITE_DATALYR_WORKSPACE_ID to your .env file");
994
+ steps.push("Call initDatalyr() in your main.tsx");
995
+ break;
996
+ case "react-native":
997
+ case "expo":
998
+ steps.push("Run: cd ios && pod install");
999
+ steps.push("Call initDatalyr() in your App.tsx useEffect");
1000
+ break;
1001
+ case "ios":
1002
+ steps.push("Add DatalyrSDK via Swift Package Manager");
1003
+ steps.push("Add DATALYR_API_KEY and DATALYR_WORKSPACE_ID to Datalyr.xcconfig");
1004
+ steps.push("Configure Info.plist to use the xcconfig variables");
1005
+ steps.push("Call DatalyrConfig.initialize() in your App");
1006
+ break;
1007
+ default:
1008
+ steps.push("Add your workspace ID to your environment");
1009
+ }
1010
+ return steps;
1011
+ }
1012
+
1013
+ // src/installers/npm.ts
1014
+ import { execa } from "execa";
1015
+ async function installPackages(cwd, packages, options = {}) {
1016
+ if (packages.length === 0) return true;
1017
+ if (options.dryRun) return true;
1018
+ const pm = await detectPackageManager(cwd);
1019
+ const command = getInstallCommand(pm, packages, options.dev);
1020
+ const spinner = startSpinner(`Installing ${packages.join(", ")}...`);
1021
+ try {
1022
+ const [cmd, ...args] = command.split(" ");
1023
+ await execa(cmd, args, { cwd, stdio: "pipe" });
1024
+ succeedSpinner(`Installed ${packages.join(", ")}`);
1025
+ return true;
1026
+ } catch (error) {
1027
+ failSpinner(`Failed to install packages`);
1028
+ console.error(error instanceof Error ? error.message : error);
1029
+ return false;
1030
+ }
1031
+ }
1032
+
1033
+ // src/cli/prompts.ts
1034
+ import { input, confirm, select } from "@inquirer/prompts";
1035
+ import chalk2 from "chalk";
1036
+ async function promptApiKey(existingKey) {
1037
+ if (existingKey) {
1038
+ return existingKey;
1039
+ }
1040
+ const apiKey = await input({
1041
+ message: "Enter your Datalyr API key (starts with dk_):",
1042
+ validate: (value) => {
1043
+ if (!value.startsWith("dk_")) {
1044
+ return 'API key must start with "dk_"';
1045
+ }
1046
+ if (value.length < 10) {
1047
+ return "API key seems too short";
1048
+ }
1049
+ return true;
1050
+ }
1051
+ });
1052
+ return apiKey;
1053
+ }
1054
+ async function promptFramework() {
1055
+ return select({
1056
+ message: "Select your framework:",
1057
+ choices: [
1058
+ { name: "Next.js", value: "nextjs" },
1059
+ { name: "React (Vite)", value: "react-vite" },
1060
+ { name: "React (Create React App)", value: "react" },
1061
+ { name: "Svelte/SvelteKit", value: "sveltekit" },
1062
+ { name: "Vue/Nuxt", value: "nuxt" },
1063
+ { name: "Remix", value: "remix" },
1064
+ { name: "Astro", value: "astro" },
1065
+ { name: "React Native", value: "react-native" },
1066
+ { name: "Expo", value: "expo" },
1067
+ { name: "iOS (Swift)", value: "ios" },
1068
+ { name: "Node.js (Server only)", value: "node" }
1069
+ ]
1070
+ });
1071
+ }
1072
+ async function promptProceed() {
1073
+ return confirm({
1074
+ message: "Proceed with installation?",
1075
+ default: true
1076
+ });
1077
+ }
1078
+
1079
+ // src/utils/logger.ts
1080
+ import chalk3 from "chalk";
1081
+ var logger = {
1082
+ info: (message) => console.log(chalk3.blue("\u2139"), message),
1083
+ success: (message) => console.log(chalk3.green("\u2713"), message),
1084
+ warn: (message) => console.log(chalk3.yellow("\u26A0"), message),
1085
+ error: (message) => console.log(chalk3.red("\u2717"), message),
1086
+ debug: (message, enabled = false) => {
1087
+ if (enabled) console.log(chalk3.gray("[debug]"), message);
1088
+ },
1089
+ header: (title) => {
1090
+ console.log();
1091
+ console.log(chalk3.bold.cyan(title));
1092
+ console.log(chalk3.gray("\u2500".repeat(40)));
1093
+ },
1094
+ step: (step, total, message) => {
1095
+ console.log();
1096
+ console.log(chalk3.bold(`Step ${step}/${total}: ${message}`));
1097
+ console.log(chalk3.gray("\u2500".repeat(40)));
1098
+ },
1099
+ box: (lines) => {
1100
+ const maxLen = Math.max(...lines.map((l) => l.length));
1101
+ const border = "\u2550".repeat(maxLen + 4);
1102
+ console.log(chalk3.cyan(`\u2554${border}\u2557`));
1103
+ lines.forEach((line) => {
1104
+ const padding = " ".repeat(maxLen - line.length);
1105
+ console.log(chalk3.cyan("\u2551") + ` ${line}${padding} ` + chalk3.cyan("\u2551"));
1106
+ });
1107
+ console.log(chalk3.cyan(`\u255A${border}\u255D`));
1108
+ },
1109
+ list: (items, indent = 2) => {
1110
+ const spaces = " ".repeat(indent);
1111
+ items.forEach((item) => console.log(`${spaces}\u2022 ${item}`));
1112
+ },
1113
+ blank: () => console.log()
1114
+ };
1115
+
1116
+ // src/index.ts
1117
+ async function runWizard(options = {}) {
1118
+ const cwd = options.cwd || process.cwd();
1119
+ const isInteractive = !options.yes && !options.json && !options.dryRun;
1120
+ try {
1121
+ if (isInteractive) {
1122
+ printWelcome();
1123
+ }
1124
+ let apiKey = options.apiKey || "dk_placeholder";
1125
+ if (isInteractive) {
1126
+ logger.step(1, 5, "Enter your Datalyr API Key");
1127
+ apiKey = await promptApiKey(options.apiKey);
1128
+ logger.success("API key validated");
1129
+ }
1130
+ if (!options.json) {
1131
+ logger.step(2, 5, "Analyzing your project...");
1132
+ }
1133
+ const spinner = options.json ? null : startSpinner("Scanning project structure...");
1134
+ let detection = await detectFramework(cwd);
1135
+ if (spinner) {
1136
+ succeedSpinner(`Detected ${getFrameworkDisplayName(detection.framework)}`);
1137
+ }
1138
+ if (detection.framework === "unknown" || options.framework) {
1139
+ stopSpinner();
1140
+ if (options.framework) {
1141
+ detection = { ...detection, framework: options.framework };
1142
+ } else if (isInteractive) {
1143
+ logger.warn("Could not auto-detect framework");
1144
+ detection.framework = await promptFramework();
1145
+ } else {
1146
+ printError("Could not detect framework", "Use --framework to specify");
1147
+ return false;
1148
+ }
1149
+ }
1150
+ const packageManager = await detectPackageManager(cwd);
1151
+ const entryPoints = await findEntryPoints(cwd, detection.framework);
1152
+ const context = {
1153
+ cwd,
1154
+ framework: detection.framework,
1155
+ sdks: detection.sdks,
1156
+ language: detection.language,
1157
+ packageManager,
1158
+ entryPoints,
1159
+ existingFiles: []
1160
+ };
1161
+ if (isInteractive) {
1162
+ printDetection({
1163
+ framework: getFrameworkDisplayName(detection.framework),
1164
+ language: detection.language === "typescript" ? "TypeScript" : "JavaScript",
1165
+ sdks: detection.sdks
1166
+ });
1167
+ }
1168
+ if (!options.json && !options.dryRun) {
1169
+ logger.step(3, 5, "Installation Plan");
1170
+ }
1171
+ const plan = generateInstallationPlan(context, apiKey);
1172
+ if (options.dryRun) {
1173
+ const commands = [
1174
+ `${packageManager} add ${plan.packages.join(" ")}`
1175
+ ];
1176
+ printDryRun({
1177
+ packages: plan.packages,
1178
+ files: plan.files,
1179
+ commands
1180
+ });
1181
+ return true;
1182
+ }
1183
+ if (options.json) {
1184
+ console.log(JSON.stringify({
1185
+ framework: detection.framework,
1186
+ language: detection.language,
1187
+ sdks: detection.sdks,
1188
+ packages: plan.packages,
1189
+ files: plan.files.map((f) => ({ path: f.path, action: f.action })),
1190
+ envVars: plan.envVars.map((v) => v.key)
1191
+ }, null, 2));
1192
+ return true;
1193
+ }
1194
+ printPlan({
1195
+ packages: plan.packages,
1196
+ files: plan.files
1197
+ });
1198
+ if (isInteractive) {
1199
+ const proceed = await promptProceed();
1200
+ if (!proceed) {
1201
+ logger.info("Installation cancelled");
1202
+ return false;
1203
+ }
1204
+ }
1205
+ logger.step(4, 5, "Installing...");
1206
+ if (plan.packages.length > 0) {
1207
+ const success = await installPackages(cwd, plan.packages);
1208
+ if (!success) {
1209
+ printError("Failed to install packages");
1210
+ return false;
1211
+ }
1212
+ }
1213
+ for (const file of plan.files) {
1214
+ const filePath = path5.join(cwd, file.path);
1215
+ const exists = await fileExists(filePath);
1216
+ if (exists && file.action === "create") {
1217
+ logger.warn(`Skipping ${file.path} (already exists)`);
1218
+ continue;
1219
+ }
1220
+ const fileSpinner = startSpinner(`Creating ${file.path}...`);
1221
+ await writeFile(filePath, file.content);
1222
+ succeedSpinner(`Created ${file.path}`);
1223
+ }
1224
+ if (plan.envVars.length > 0) {
1225
+ await updateEnvFile(cwd, plan.envVars);
1226
+ }
1227
+ logger.step(5, 5, "Success!");
1228
+ printSuccess();
1229
+ if (plan.postInstallSteps.length > 0) {
1230
+ logger.header("Next steps:");
1231
+ plan.postInstallSteps.forEach((step, i) => {
1232
+ console.log(` ${i + 1}. ${step}`);
1233
+ });
1234
+ console.log();
1235
+ }
1236
+ return true;
1237
+ } catch (error) {
1238
+ stopSpinner();
1239
+ printError(
1240
+ error instanceof Error ? error.message : "Unknown error occurred",
1241
+ options.debug ? error.stack : void 0
1242
+ );
1243
+ return false;
1244
+ }
1245
+ }
1246
+ async function findEntryPoints(cwd, framework) {
1247
+ const entryPoints = [];
1248
+ switch (framework) {
1249
+ case "nextjs":
1250
+ const appLayouts = await findFiles(cwd, "app/layout.{tsx,jsx,ts,js}");
1251
+ entryPoints.push(...appLayouts);
1252
+ const pagesApps = await findFiles(cwd, "pages/_app.{tsx,jsx,ts,js}");
1253
+ entryPoints.push(...pagesApps);
1254
+ break;
1255
+ case "react":
1256
+ case "react-vite":
1257
+ const mains = await findFiles(cwd, "src/main.{tsx,jsx,ts,js}");
1258
+ entryPoints.push(...mains);
1259
+ const apps = await findFiles(cwd, "src/App.{tsx,jsx,ts,js}");
1260
+ entryPoints.push(...apps);
1261
+ break;
1262
+ case "react-native":
1263
+ case "expo":
1264
+ const appFiles = await findFiles(cwd, "App.{tsx,jsx,ts,js}");
1265
+ entryPoints.push(...appFiles);
1266
+ break;
1267
+ }
1268
+ return entryPoints;
1269
+ }
1270
+ export {
1271
+ detectFramework,
1272
+ generateInstallationPlan,
1273
+ runWizard
1274
+ };
1275
+ //# sourceMappingURL=index.mjs.map