@shiplens/cli 1.2.8 → 1.3.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/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, You must include a readable copy of the
108
+ attribution notices contained within such NOTICE file,
109
+ excluding those notices that do not pertain to any part of
110
+ the Derivative Works, in at least one of the following places:
111
+ within a NOTICE text file distributed as part of the
112
+ Derivative Works; within the Source form or documentation,
113
+ if provided along with the Derivative Works; or, within a
114
+ display generated by the Derivative Works, if and wherever
115
+ such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 Shiplens Team (https://shiplens.dev)
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md CHANGED
@@ -21,13 +21,19 @@ Run in the root of any Next.js, Vite, Vue, or HTML project:
21
21
  ```bash
22
22
  # Zero-install execution via npx
23
23
  npx --yes @shiplens/cli init --json
24
+
25
+ # Windows PowerShell (Avoid execution policy blocking)
26
+ npx.cmd --yes @shiplens/cli init --json
27
+
28
+ # In China or restricted networks (Alibaba Cloud / npmmirror fallback)
29
+ npx --yes --registry=https://registry.npmmirror.com @shiplens/cli init --json
24
30
  ```
25
31
 
26
32
  ### What `init` Does Automatically:
27
33
  1. **Detects Framework**: Automatically recognizes Next.js (App / Pages router), Vite (React / Svelte), Vue 3, or plain HTML.
28
34
  2. **Injects Tracking SDK**: Inserts `@shiplens/sdk` tracking snippets into your entry files without breaking your code layout.
29
35
  3. **Connects Cloud Project**: Registers the project, generates a live responsive dashboard URL, and writes local configuration (`.shiplens.json`).
30
- 4. **Installs Dependency**: Adds `@shiplens/sdk` via your project package manager (`npm`, `pnpm`, `yarn`, or `bun`).
36
+ 4. **Installs Dependency**: Adds `@shiplens/sdk` via your project package manager (`npm`, `pnpm`, `yarn`, or `bun`) with 4-tier download fallback (NPM -> Alibaba npmmirror -> GitHub -> CDN, 5s timeout & 2 retries per tier).
31
37
  5. **Deploys AI Skills**: Injects `.agents/skills/shiplens/SKILL.md` and Cursor rules (`.cursor/rules/shiplens.mdc`) for seamless LLM Agent integration.
32
38
  6. **Performs Git Commit**: Automatically commits all instrumentation changes atomically.
33
39
 
@@ -6,7 +6,7 @@ description: Shiplens Web User Telemetry & AI Dashboard Skill Specification. Inc
6
6
  # Shiplens Web Analytics Skill Specification (v2.0)
7
7
 
8
8
  > 💡 **Core Overview & Official Reference**:
9
- > 1. **Dual Track Integration**: Supports instant onboarding via **Shiplens CLI** (\`shiplens init\` / \`npx shiplens-cli init\`) for dependency setup, project creation, and code injection; full support for **MCP Tools** and standard REST APIs inside IDE / Agent environments.
9
+ > 1. **Dual Track Integration**: Supports instant onboarding via **Shiplens CLI** (\`shiplens init\` / \`npx @shiplens/cli init\`) for dependency setup, project creation, and code injection; full support for **MCP Tools** and standard REST APIs inside IDE / Agent environments.
10
10
  > 2. Installing the SDK and viewing live dashboards requires no MCP server; advanced analytics requires authentication via OAuth, API keys/environment variables, or CLI credentials.
11
11
  > 3. **Authoritative FAQ**: \`https://shiplens.dev/faq\`.
12
12
 
@@ -21,7 +21,7 @@ You are connected to **Shiplens Web Analytics & MCP Services**. When providing a
21
21
  Check Existing App ID ➔ Install SDK ➔ POST Connect & Get Dashboard URL ➔ Request Email for Free Quota ➔ Activate Magic Link ➔ Authenticate ➔ Complete
22
22
  \`\`\`
23
23
 
24
- > ⚡ **Quick Execution**: In a terminal environment, execute \`npx.cmd --yes shiplens-cli init --json\` (Windows) or \`npx --yes shiplens-cli init --json\` (macOS/Linux) for automated 15-second zero-config setup.
24
+ > ⚡ **Quick Execution**: In a terminal environment, execute \`npx.cmd --yes @shiplens/cli init --json\` (Windows) or \`npx --yes @shiplens/cli init --json\` (macOS/Linux) for automated 15-second zero-config setup. (China mirror fallback: \`--registry=https://registry.npmmirror.com\`).
25
25
 
26
26
  ### Step 0. Existing Project Detection (Overwrite Protection)
27
27
  - Check if \`./.shiplens.json\` or SDK instrumentation (\`initShiplens\`, \`data-app-id\`) exists locally.
@@ -44,13 +44,21 @@ async function handleInit(args, flags, ctx) {
44
44
  ctx.output(result);
45
45
  process.exitCode = 1;
46
46
  return;
47
+ } else if (!process.stdin.isTTY) {
48
+ console.log(`\n⚠️ Existing Shiplens project detected!`);
49
+ console.log(`📌 App ID: ${existing.app_id} (Source: ${existing.source_file})`);
50
+ console.log(`📊 Dashboard: ${ctx.client.baseURL}/dashboard/${existing.app_id}`);
51
+ console.log(`🛑 Non-interactive terminal detected (CI/Agent). Existing configuration preserved.`);
52
+ console.log(`💡 To overwrite and create a new project, run with --force:`);
53
+ console.log(` npx @shiplens/cli init --force\n`);
54
+ return;
47
55
  } else {
48
56
  console.log(`\n⚠️ Existing Shiplens project detected!`);
49
57
  console.log(`📌 App ID: ${existing.app_id} (Source: ${existing.source_file})`);
50
58
  console.log(`📊 Dashboard: ${ctx.client.baseURL}/dashboard/${existing.app_id}`);
51
59
  console.log(`\n💡 Option 1 [Recommended]: Keep existing setup and reuse App ID.`);
52
60
  console.log(`💡 Option 2: Run with --force to overwrite and create a new project:`);
53
- console.log(` npx shiplens-cli init --force\n`);
61
+ console.log(` npx @shiplens/cli init --force\n`);
54
62
 
55
63
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
56
64
  const confirmed = await new Promise((resolve) => {
@@ -124,13 +132,14 @@ async function handleInit(args, flags, ctx) {
124
132
  // 6. Install SDK dependency
125
133
  let installResult = { success: true, manager: 'skipped' };
126
134
  if (!flags['no-install'] && detected.package_manager) {
127
- installResult = installSDKDependency(wd, detected.package_manager);
135
+ installResult = await installSDKDependency(wd, detected.package_manager);
128
136
  if (!installResult.success) {
129
- const errMsg = `SDK installation failed: Unable to download @shiplens/sdk from npm registry, GitHub mirror, or Shiplens CDN mirror.\n` +
137
+ const errMsg = `SDK installation failed: Unable to download @shiplens/sdk across all download sources (official npm registry, Alibaba Cloud npmmirror, GitHub mirror, and Shiplens CDN mirror).\n` +
130
138
  `Troubleshooting steps:\n` +
131
139
  ` 1. Check your local network connection or HTTP proxy / VPN settings;\n` +
132
- ` 2. Try running manually: npm install @shiplens/sdk;\n` +
133
- ` 3. Visit https://shiplens.com for latest SDK status and installation guides.`;
140
+ ` 2. Try running manually with Alibaba mirror: npm install @shiplens/sdk --registry=https://registry.npmmirror.com;\n` +
141
+ ` 3. Or install via official registry: npm install @shiplens/sdk;\n` +
142
+ ` 4. Visit https://shiplens.com for latest SDK status and installation guides.`;
134
143
 
135
144
  if (ctx.isJSON) {
136
145
  ctx.output({
package/lib/injector.js CHANGED
@@ -1,10 +1,11 @@
1
1
  const fs = require('fs');
2
2
  const path = require('path');
3
- const { execSync } = require('child_process');
3
+ const { execSync, spawn } = require('child_process');
4
4
 
5
5
  const FRAMEWORKS = {
6
6
  NEXT_APP: 'nextjs-app',
7
7
  NEXT_PAGES: 'nextjs-pages',
8
+ CRA: 'cra',
8
9
  VITE: 'vite',
9
10
  VUE: 'vue',
10
11
  HTML: 'html',
@@ -57,6 +58,8 @@ function detectProject(dir = process.cwd()) {
57
58
  } else {
58
59
  result.framework = FRAMEWORKS.NEXT_PAGES;
59
60
  }
61
+ } else if (deps['react-scripts'] || deps['react-app-rewired'] || deps['craco'] || deps['@craco/craco']) {
62
+ result.framework = FRAMEWORKS.CRA;
60
63
  } else if (deps['vue'] || deps['nuxt']) {
61
64
  result.framework = FRAMEWORKS.VUE;
62
65
  } else if (deps['vite'] || deps['react'] || deps['svelte']) {
@@ -271,6 +274,26 @@ function injectHTML(dir, appId) {
271
274
  return injectFallback(dir, appId);
272
275
  }
273
276
 
277
+ function injectCRA(dir, appId) {
278
+ const candidates = [
279
+ 'src/index.tsx', 'src/index.ts',
280
+ 'src/index.jsx', 'src/index.js',
281
+ ];
282
+ for (const cand of candidates) {
283
+ const p = path.join(dir, cand);
284
+ if (fs.existsSync(p)) {
285
+ let content = fs.readFileSync(p, 'utf8');
286
+ if (content.includes('@shiplens/sdk') || content.includes('initShiplens') || content.includes(appId)) {
287
+ return cand;
288
+ }
289
+ const injection = `\n// Shiplens SDK - User Analytics\nconst { initShiplens } = require('@shiplens/sdk');\ninitShiplens({ appId: '${appId}' });\n`;
290
+ fs.writeFileSync(p, content + injection, 'utf8');
291
+ return cand;
292
+ }
293
+ }
294
+ return injectFallback(dir, appId);
295
+ }
296
+
274
297
  function injectFallback(dir, appId) {
275
298
  const configFile = path.join(dir, 'shiplens.config.ts');
276
299
  const content = `import { initShiplens } from '@shiplens/sdk';\n\nexport function setupShiplens() {\n if (typeof window !== 'undefined') {\n initShiplens({\n appId: '${appId}',\n });\n }\n}\n`;
@@ -284,6 +307,8 @@ function injectSDK(dir, framework, appId) {
284
307
  return injectNextApp(dir, appId);
285
308
  case FRAMEWORKS.NEXT_PAGES:
286
309
  return injectNextPages(dir, appId);
310
+ case FRAMEWORKS.CRA:
311
+ return injectCRA(dir, appId);
287
312
  case FRAMEWORKS.VUE:
288
313
  return injectVue(dir, appId);
289
314
  case FRAMEWORKS.VITE:
@@ -292,19 +317,40 @@ function injectSDK(dir, framework, appId) {
292
317
  return injectHTML(dir, appId);
293
318
  default:
294
319
  try { return injectNextApp(dir, appId); } catch (e) {}
320
+ try { return injectCRA(dir, appId); } catch (e) {}
295
321
  try { return injectVite(dir, appId); } catch (e) {}
296
322
  try { return injectHTML(dir, appId); } catch (e) {}
297
323
  return injectFallback(dir, appId);
298
324
  }
299
325
  }
300
326
 
301
- function installSDKDependency(dir, pkgManager = 'npm') {
327
+ function killProcess(child) {
328
+ if (!child || child.killed) return;
329
+ try {
330
+ if (process.platform === 'win32' && child.pid) {
331
+ try {
332
+ execSync(`taskkill /pid ${child.pid} /T /F`, { stdio: 'ignore' });
333
+ } catch (e) {
334
+ try { child.kill('SIGKILL'); } catch (err) {}
335
+ }
336
+ } else {
337
+ try { child.kill('SIGTERM'); } catch (e) {}
338
+ setTimeout(() => {
339
+ try { child.kill('SIGKILL'); } catch (e) {}
340
+ }, 500);
341
+ }
342
+ } catch (e) {
343
+ try { child.kill(); } catch (err) {}
344
+ }
345
+ }
346
+
347
+ async function installSDKDependency(dir, pkgManager = 'npm') {
302
348
  const isWindows = process.platform === 'win32';
303
349
  const ext = isWindows ? '.cmd' : '';
304
-
305
- // 1. Define 3-Tier Download Sources (npm registry -> GitHub mirror -> Shiplens CDN mirror)
350
+
306
351
  const sources = [
307
352
  {
353
+ id: 'npmjs',
308
354
  name: 'npm registry',
309
355
  getCommand: (pm) => {
310
356
  if (pm === 'pnpm') return `pnpm${ext} add @shiplens/sdk`;
@@ -314,6 +360,18 @@ function installSDKDependency(dir, pkgManager = 'npm') {
314
360
  },
315
361
  },
316
362
  {
363
+ id: 'npmmirror',
364
+ name: 'Alibaba Cloud mirror (npmmirror)',
365
+ getCommand: (pm) => {
366
+ const mirror = '--registry=https://registry.npmmirror.com';
367
+ if (pm === 'pnpm') return `pnpm${ext} add @shiplens/sdk ${mirror}`;
368
+ if (pm === 'yarn') return `yarn${ext} add @shiplens/sdk ${mirror}`;
369
+ if (pm === 'bun') return `bun${ext} add @shiplens/sdk ${mirror}`;
370
+ return `npm${ext} install @shiplens/sdk ${mirror} --legacy-peer-deps --no-audit --no-fund`;
371
+ },
372
+ },
373
+ {
374
+ id: 'github',
317
375
  name: 'GitHub mirror',
318
376
  getCommand: (pm) => {
319
377
  const repoUrl = 'https://github.com/Hyperlong/shiplens-sdk.git';
@@ -324,6 +382,7 @@ function installSDKDependency(dir, pkgManager = 'npm') {
324
382
  },
325
383
  },
326
384
  {
385
+ id: 'cdn',
327
386
  name: 'Shiplens CDN mirror',
328
387
  getCommand: (pm) => {
329
388
  const cdnUrl = 'https://cdn.shiplens.dev/packages/shiplens-sdk.tgz';
@@ -335,34 +394,107 @@ function installSDKDependency(dir, pkgManager = 'npm') {
335
394
  },
336
395
  ];
337
396
 
338
- let lastError = null;
397
+ const TIER1_DELAY_MS = 20 * 1000; // 20s
398
+ const TOTAL_TIMEOUT_MS = 5 * 60 * 1000; // 5min
399
+
400
+ return new Promise((resolve) => {
401
+ let isDone = false;
402
+ const activeChildren = new Set();
403
+ let tier2Timer = null;
404
+ let totalTimer = null;
405
+ let startedCount = 0;
406
+ let finishedFailureCount = 0;
407
+
408
+ const cleanupAndFinish = (result) => {
409
+ if (isDone) return;
410
+ isDone = true;
411
+ if (tier2Timer) clearTimeout(tier2Timer);
412
+ if (totalTimer) clearTimeout(totalTimer);
413
+ for (const child of activeChildren) {
414
+ killProcess(child);
415
+ }
416
+ activeChildren.clear();
417
+ resolve(result);
418
+ };
419
+
420
+ const runSource = (source) => {
421
+ if (isDone) return;
422
+ startedCount++;
423
+ const cmd = source.getCommand(pkgManager);
424
+ let child;
425
+ try {
426
+ child = spawn(cmd, { cwd: dir, shell: true, stdio: 'ignore' });
427
+ } catch (e) {
428
+ finishedFailureCount++;
429
+ checkAllFailed();
430
+ return;
431
+ }
339
432
 
340
- // Try each source with strict 10s (10000ms) timeout
341
- for (const source of sources) {
342
- const cmd = source.getCommand(pkgManager);
343
- try {
344
- execSync(cmd, { cwd: dir, stdio: 'ignore', timeout: 10000 });
345
- return { success: true, manager: pkgManager, source: source.name };
346
- } catch (err) {
347
- lastError = err;
348
- // If primary package manager failed, also try npm fallback on that source
349
- if (pkgManager !== 'npm') {
350
- const npmCmd = source.getCommand('npm');
351
- try {
352
- execSync(npmCmd, { cwd: dir, stdio: 'ignore', timeout: 10000 });
353
- return { success: true, manager: 'npm (fallback)', source: source.name };
354
- } catch (npmErr) {
355
- lastError = npmErr;
433
+ activeChildren.add(child);
434
+
435
+ const onExit = (code) => {
436
+ activeChildren.delete(child);
437
+ if (isDone) return;
438
+ if (code === 0) {
439
+ cleanupAndFinish({
440
+ success: true,
441
+ manager: pkgManager,
442
+ source: source.name,
443
+ });
444
+ } else {
445
+ finishedFailureCount++;
446
+ if (source.id === 'npmjs' && tier2Timer) {
447
+ clearTimeout(tier2Timer);
448
+ tier2Timer = null;
449
+ startBackupSources();
450
+ }
451
+ checkAllFailed();
356
452
  }
357
- }
358
- }
359
- }
453
+ };
360
454
 
361
- return {
362
- success: false,
363
- manager: pkgManager,
364
- error: lastError ? lastError.message : 'All 3 download sources timed out or failed',
365
- };
455
+ child.on('close', onExit);
456
+ child.on('error', () => onExit(1));
457
+ };
458
+
459
+ const startBackupSources = () => {
460
+ if (isDone) return;
461
+ if (tier2Timer) {
462
+ clearTimeout(tier2Timer);
463
+ tier2Timer = null;
464
+ }
465
+ for (let i = 1; i < sources.length; i++) {
466
+ runSource(sources[i]);
467
+ }
468
+ };
469
+
470
+ const checkAllFailed = () => {
471
+ if (isDone) return;
472
+ if (startedCount === sources.length && finishedFailureCount === sources.length) {
473
+ cleanupAndFinish({
474
+ success: false,
475
+ manager: pkgManager,
476
+ error: 'All 4 download sources failed or timed out',
477
+ });
478
+ }
479
+ };
480
+
481
+ // t = 0s: Start Tier 1 (npmjs)
482
+ runSource(sources[0]);
483
+
484
+ // t = 20s: If still running, keep npmjs alive and start npmmirror + GitHub + CDN
485
+ tier2Timer = setTimeout(() => {
486
+ startBackupSources();
487
+ }, TIER1_DELAY_MS);
488
+
489
+ // t = 5min: Total timeout across all sources
490
+ totalTimer = setTimeout(() => {
491
+ cleanupAndFinish({
492
+ success: false,
493
+ manager: pkgManager,
494
+ error: 'SDK installation timed out after 5 minutes across all download sources',
495
+ });
496
+ }, TOTAL_TIMEOUT_MS);
497
+ });
366
498
  }
367
499
 
368
500
  function getGitEmail() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shiplens/cli",
3
- "version": "1.2.8",
3
+ "version": "1.3.0",
4
4
  "description": "Shiplens CLI (In Development) - 15-second zero-config analytics initialization and full telemetry analysis engine",
5
5
  "main": "lib/index.js",
6
6
  "bin": {
@@ -33,7 +33,8 @@
33
33
  "bin",
34
34
  "lib",
35
35
  "prompts",
36
- "README.md"
36
+ "README.md",
37
+ "LICENSE"
37
38
  ],
38
39
  "engines": {
39
40
  "node": ">=16.0.0"
@@ -516,7 +516,7 @@ Sources:
516
516
  #### [Create 30-Day New User Retention Matrix Dashboard] (Suffix: Data Fetching, Dashboard Creation)
517
517
  ```text
518
518
  Create a 30-day new user retention matrix dashboard in Shiplens:
519
- 1. Execute CLI command: `npx.cmd --yes shiplens-cli dashboards create --title "30-Day New User Retention Matrix" --prompt "Display daily new user signups and Day 1 to 30 cohort retention matrix plotted along the registration date axis" --json`.
519
+ 1. Execute CLI command: `npx.cmd --yes @shiplens/cli dashboards create --title "30-Day New User Retention Matrix" --prompt "Display daily new user signups and Day 1 to 30 cohort retention matrix plotted along the registration date axis" --json`.
520
520
  2. Parse the JSON response to extract `dashboard_id` and live URL `dashboard_url`.
521
521
  3. Return the generated dashboard link and interpretation guide to the user.
522
522
  ---
@@ -531,7 +531,7 @@ Sources:
531
531
  ```text
532
532
  Inspect core workflows in code and create a step conversion funnel dashboard in Shiplens:
533
533
  1. Scan frontend code and routes to identify the core sequential workflow (e.g., Signup -> Onboarding -> Core Action -> Publish).
534
- 2. Execute CLI command: `npx.cmd --yes shiplens-cli dashboards create --title "Core Workflow Conversion Funnel" --prompt "Analyze step-by-step user volumes, drop-off rates, and cumulative conversion across workflow stages" --json`.
534
+ 2. Execute CLI command: `npx.cmd --yes @shiplens/cli dashboards create --title "Core Workflow Conversion Funnel" --prompt "Analyze step-by-step user volumes, drop-off rates, and cumulative conversion across workflow stages" --json`.
535
535
  3. Extract and return the live `dashboard_url` to the user.
536
536
  ---
537
537
  Analysis Foundation:
@@ -562,7 +562,7 @@ Sources:
562
562
  ```text
563
563
  Instrument and analyze user Aha Moment milestones:
564
564
  1. Inject SDK telemetry at the value completion trigger: `Shiplens.track('aha_moment_achieved', { milestone_type: '<type>', time_to_reach: <seconds> })`.
565
- 2. Run CLI command: `npx.cmd --yes shiplens-cli dashboards create --title "Aha Moment Retention Comparison Dashboard" --prompt "Show 30-day retention comparison curves between users who achieved the Aha Moment vs those who did not" --json`.
565
+ 2. Run CLI command: `npx.cmd --yes @shiplens/cli dashboards create --title "Aha Moment Retention Comparison Dashboard" --prompt "Show 30-day retention comparison curves between users who achieved the Aha Moment vs those who did not" --json`.
566
566
  3. Return the dashboard URL and verify telemetry ingestion.
567
567
  ---
568
568
  Analysis Foundation:
@@ -576,7 +576,7 @@ Sources:
576
576
  ```text
577
577
  Track subscription revenue and connect usage with revenue events:
578
578
  1. Inject SDK revenue event telemetry at checkout completion: `Shiplens.track('revenue_event', { amount: <amount>, currency: '<USD|CNY>', plan: '<plan_id>', user_id: '<user_id>' })`.
579
- 2. Run CLI command: `npx.cmd --yes shiplens-cli dashboards create --title "Daily Subscriptions & Revenue Dashboard" --prompt "Show daily subscriber counts, MRR/ARR growth, and subscriber retention trends" --json`.
579
+ 2. Run CLI command: `npx.cmd --yes @shiplens/cli dashboards create --title "Daily Subscriptions & Revenue Dashboard" --prompt "Show daily subscriber counts, MRR/ARR growth, and subscriber retention trends" --json`.
580
580
  3. Return the live `dashboard_url` to the user.
581
581
  ---
582
582
  Analysis Foundation:
@@ -592,11 +592,11 @@ Sources:
592
592
  ```text
593
593
  Set up Shiplens analytics: extract project description, install SDK, create the project, and retrieve the live dashboard URL.
594
594
  1. Run CLI initialization command:
595
- - Windows: npx.cmd --yes shiplens-cli init
596
- - macOS/Linux: npx --yes shiplens-cli init
595
+ - Windows: npx.cmd --yes @shiplens/cli init
596
+ - macOS/Linux: npx --yes @shiplens/cli init
597
597
  2. Present the standard project & dashboard summary (including: Project Name, App ID, Code Injection file, User Account Status, Live Dashboard / Activation URL);
598
598
  3. Immediately prompt the user for their email address (informing them that you will register on their behalf and Shiplens will send an activation email for 50,000 monthly free events and project binding);
599
- 4. Upon receiving the user's email, run: npx.cmd --yes shiplens-cli auth bind --email <email> --json.
599
+ 4. Upon receiving the user's email, run: npx.cmd --yes @shiplens/cli auth bind --email <email> --json.
600
600
  ```
601
601
 
602
602
  #### [Remove Shiplens SDK & Analytics Data] (Suffix: None)
@@ -605,14 +605,14 @@ Remove Shiplens SDK integration and analytics data:
605
605
  1. Read `.shiplens.json` in the project root to get project name, app_id, and instrumented file paths.
606
606
  2. Clearly display the project name and app_id to be deleted, warn the user that historical events and hosted data will be permanently purged, and pause for explicit user confirmation ("Confirm deleting this project").
607
607
  3. Upon confirmation, remove SDK imports/instrumentation code from local frontend files, and delete `./.shiplens.json` and `.shiplens/contexts/<app_id>.md`.
608
- 4. Run CLI command to destroy cloud project: npx.cmd --yes shiplens-cli projects delete --app-id <app_id> --force --json.
608
+ 4. Run CLI command to destroy cloud project: npx.cmd --yes @shiplens/cli projects delete --app-id <app_id> --force --json.
609
609
  ```
610
610
 
611
611
  #### [Uninstall Shiplens CLI] (Suffix: None)
612
612
  ```text
613
613
  Completely uninstall the globally installed Shiplens CLI:
614
- - Windows: npm.cmd uninstall -g shiplens-cli
615
- - macOS/Linux: npm uninstall -g shiplens-cli
614
+ - Windows: npm.cmd uninstall -g @shiplens/cli
615
+ - macOS/Linux: npm uninstall -g @shiplens/cli
616
616
  ```
617
617
 
618
618
  #### [Generate Context Descriptions for All Pages and Buttons] (Suffix: None)
@@ -621,7 +621,7 @@ Map pages, features, and button layouts into `.shiplens/contexts/<app_id>.md` so
621
621
  1. Check `./.shiplens.json` for current app_id and project name.
622
622
  2. Inspect frontend code and routes to extract feature descriptions, user-facing copy, and button texts, locations, and actions.
623
623
  3. Write structured details into `.shiplens/contexts/<app_id>.md`, binding app_id and project name in the header.
624
- 4. Optionally run `npx.cmd --yes shiplens-cli context push` to sync context to cloud for cross-device collaboration; AI will prioritize this file for accurate business context during analytics.
624
+ 4. Optionally run `npx.cmd --yes @shiplens/cli context push` to sync context to cloud for cross-device collaboration; AI will prioritize this file for accurate business context during analytics.
625
625
  ```
626
626
 
627
627
  ### Troubleshooting & Diagnostics
@@ -629,7 +629,7 @@ Map pages, features, and button layouts into `.shiplens/contexts/<app_id>.md` so
629
629
  #### [Test Shiplens Telemetry Pipeline and Environment] (Suffix: None)
630
630
  ```text
631
631
  Diagnose Shiplens telemetry pipeline and environment health:
632
- 1. Run diagnostic command in terminal: `npx.cmd --yes shiplens-cli doctor --json` (macOS/Linux: `npx --yes shiplens-cli doctor --json`).
632
+ 1. Run diagnostic command in terminal: `npx.cmd --yes @shiplens/cli doctor --json` (macOS/Linux: `npx --yes @shiplens/cli doctor --json`).
633
633
  2. Verify all 5 health checks: `local_config`, `sdk_installed`, `code_instrumented`, `network_connectivity`, and `auth_valid`.
634
634
  3. If failures occur, output exact remediation instructions based on returned error codes.
635
635
  ---