create-three-blocks-starter 0.0.5 → 0.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/bin/index.js +937 -470
  2. package/package.json +1 -1
package/bin/index.js CHANGED
@@ -12,531 +12,998 @@ import { spawnSync } from 'node:child_process';
12
12
  import readline from 'node:readline';
13
13
  import { bold, cyan, dim, green, red, yellow } from 'kolorist';
14
14
 
15
- const ESC = (n) => `\u001b[${n}m`;
16
- const reset = ESC(0);
15
+ const ESC = ( n ) => `\u001b[${n}m`;
16
+ const reset = ESC( 0 );
17
17
 
18
- const STARTER_PKG = '@three-blocks/starter'; // private starter (lives in CodeArtifact)
19
- const LOGIN_CLI = 'three-blocks-login'; // public login CLI
18
+ const STARTER_PKG = '@three-blocks/starter'; // private starter (lives in CodeArtifact)
19
+ const LOGIN_CLI = 'three-blocks-login'; // public login CLI
20
+ const LOGIN_SPEC = `${LOGIN_CLI}@latest`; // force-fresh npx install
20
21
  const SCOPE = '@three-blocks';
21
22
 
22
- const BLOCKED_NPM_ENV_KEYS = new Set([
23
- 'npm_config__three_blocks_registry',
24
- 'npm_config__three-blocks-registry',
25
- 'npm_config_verify_deps_before_run',
26
- 'npm_config_verify-deps-before-run',
27
- 'npm_config_global_bin_dir',
28
- 'npm_config_global-bin-dir',
29
- 'npm_config__jsr_registry',
30
- 'npm_config__jsr-registry',
31
- 'npm_config_node_linker',
32
- 'npm_config_node-linker',
33
- ].map((key) => key.replace(/-/g, '_').toLowerCase()));
34
-
35
- const cleanNpmEnv = (extra = {}) => {
36
- const env = { ...process.env, ...extra };
37
- for (const key of Object.keys(env)) {
38
- const normalized = key.replace(/-/g, '_').toLowerCase();
39
- if (BLOCKED_NPM_ENV_KEYS.has(normalized)) {
40
- delete env[key];
41
- }
42
- }
43
- return env;
23
+ const BLOCKED_NPM_ENV_KEYS = new Set( [
24
+ 'npm_config__three_blocks_registry',
25
+ 'npm_config_verify_deps_before_run',
26
+ 'npm_config_global_bin_dir',
27
+ 'npm_config__jsr_registry',
28
+ 'npm_config_node_linker',
29
+ ].map( ( key ) => key.replace( /-/g, '_' ).toLowerCase() ) );
30
+
31
+ let DEBUG = /^1|true|yes$/i.test( String( process.env.THREE_BLOCKS_DEBUG || '' ).trim() );
32
+
33
+ const logDebug = ( msg ) => {
34
+
35
+ if ( DEBUG ) console.log( dim( `▸ ${msg}` ) );
36
+
37
+ };
38
+
39
+ class CliError extends Error {
40
+
41
+ constructor( message, {
42
+ exitCode = 1,
43
+ command = '',
44
+ args = [],
45
+ stdout = '',
46
+ stderr = '',
47
+ suggestion = '',
48
+ cause = undefined,
49
+ } = {} ) {
50
+
51
+ super( message );
52
+ this.name = 'CliError';
53
+ this.exitCode = exitCode;
54
+ this.command = command;
55
+ this.args = args;
56
+ this.stdout = stdout;
57
+ this.stderr = stderr;
58
+ this.suggestion = suggestion;
59
+ if ( cause ) this.cause = cause;
60
+
61
+ }
62
+
63
+ }
64
+
65
+ const quoteArg = ( value ) => {
66
+
67
+ const str = String( value ?? '' );
68
+ if ( /^[A-Za-z0-9._-]+$/.test( str ) ) return str;
69
+ return `'${str.replace( /'/g, `'\\''` )}'`;
70
+
71
+ };
72
+
73
+ const formatCommand = ( cmd, args = [] ) => [ cmd, ...args ].map( quoteArg ).join( ' ' );
74
+
75
+ const cleanNpmEnv = ( extra = {} ) => {
76
+
77
+ const env = { ...process.env, ...extra };
78
+ for ( const key of Object.keys( env ) ) {
79
+
80
+ const normalized = key.replace( /-/g, '_' ).toLowerCase();
81
+ if ( BLOCKED_NPM_ENV_KEYS.has( normalized ) ) {
82
+
83
+ delete env[ key ];
84
+
85
+ }
86
+
87
+ }
88
+
89
+ return env;
90
+
44
91
  };
45
92
 
46
93
  const STEP_ICON = '⏺ ';
47
- const logInfo = (msg) => { console.log(`${STEP_ICON}${msg}`); };
48
- const logProgress = (msg) => { console.log(`${cyan(STEP_ICON)}${msg}`); };
49
- const logSuccess = (msg) => { console.log(`${green(STEP_ICON)}${msg}`); };
50
- const logWarn = (msg) => { console.log(`${yellow(STEP_ICON)}${msg}`); };
51
- const logError = (msg) => { console.error(`${red(STEP_ICON)}${msg}`); };
52
-
53
- const die = (m) => { logError(m); process.exit(1); };
54
- const run = (cmd, args, opts = {}) => {
55
- const r = spawnSync(cmd, args, { stdio: 'inherit', ...opts, env: cleanNpmEnv(opts.env) });
56
- if (r.status !== 0) process.exit(r.status ?? 1);
94
+ const logInfo = ( msg ) => {
95
+
96
+ console.log( `${STEP_ICON}${msg}` );
97
+
98
+ };
99
+
100
+ const logProgress = ( msg ) => {
101
+
102
+ console.log( `${cyan( STEP_ICON )}${msg}` );
103
+
104
+ };
105
+
106
+ const logSuccess = ( msg ) => {
107
+
108
+ console.log( `${green( STEP_ICON )}${msg}` );
109
+
110
+ };
111
+
112
+ const logWarn = ( msg ) => {
113
+
114
+ console.log( `${yellow( STEP_ICON )}${msg}` );
115
+
116
+ };
117
+
118
+ const logError = ( msg ) => {
119
+
120
+ console.error( `${red( STEP_ICON )}${msg}` );
121
+
122
+ };
123
+
124
+ const die = ( m ) => {
125
+
126
+ throw new CliError( m );
127
+
128
+ };
129
+
130
+ const run = ( cmd, args, opts = {} ) => {
131
+
132
+ const spawnArgs = Array.isArray( args ) ? args : [];
133
+ logDebug( `exec ${formatCommand( cmd, spawnArgs )}` );
134
+ const r = spawnSync( cmd, spawnArgs, { stdio: 'inherit', ...opts, env: cleanNpmEnv( opts.env ) } );
135
+ if ( r.error ) {
136
+
137
+ throw new CliError(
138
+ `Failed to start ${cmd}: ${r.error.message}`,
139
+ { command: cmd, args: spawnArgs, cause: r.error }
140
+ );
141
+
142
+ }
143
+
144
+ if ( r.status !== 0 ) {
145
+
146
+ throw new CliError(
147
+ `Command failed (${formatCommand( cmd, spawnArgs )}) [exit ${r.status}]`,
148
+ { exitCode: r.status ?? 1, command: cmd, args: spawnArgs, stdout: r.stdout ? r.stdout.toString() : '' }
149
+ );
150
+
151
+ }
152
+
153
+ return r;
154
+
57
155
  };
58
156
 
59
157
  // capture stdout (used for npm pack)
60
- const exec = (cmd, args, opts = {}) => {
61
- const r = spawnSync(cmd, args, { stdio: ['ignore', 'pipe', 'inherit'], ...opts, env: cleanNpmEnv(opts.env) });
62
- if (r.status !== 0) process.exit(r.status ?? 1);
63
- return (r.stdout || Buffer.alloc(0)).toString();
158
+ const exec = ( cmd, args, opts = {} ) => {
159
+
160
+ const spawnArgs = Array.isArray( args ) ? args : [];
161
+ logDebug( `exec ${formatCommand( cmd, spawnArgs )}` );
162
+ const r = spawnSync( cmd, spawnArgs, { stdio: [ 'ignore', 'pipe', 'pipe' ], ...opts, env: cleanNpmEnv( opts.env ) } );
163
+ const stdout = r.stdout ? r.stdout.toString() : '';
164
+ const stderr = r.stderr ? r.stderr.toString() : '';
165
+ if ( r.error ) {
166
+
167
+ throw new CliError(
168
+ `Failed to start ${cmd}: ${r.error.message}`,
169
+ { command: cmd, args: spawnArgs, stdout, stderr, cause: r.error }
170
+ );
171
+
172
+ }
173
+
174
+ if ( r.status !== 0 ) {
175
+
176
+ throw new CliError(
177
+ `Command failed (${formatCommand( cmd, spawnArgs )}) [exit ${r.status}]`,
178
+ { exitCode: r.status ?? 1, command: cmd, args: spawnArgs, stdout, stderr }
179
+ );
180
+
181
+ }
182
+
183
+ if ( stderr.trim() ) logDebug( `stderr ${formatCommand( cmd, spawnArgs )}\n${stderr.trim()}` );
184
+ return stdout;
185
+
64
186
  };
65
187
 
66
- async function ensureEmptyDir(dir) {
67
- try { await fsp.mkdir(dir, { recursive: true }); } catch {}
68
- const files = await fsp.readdir(dir).catch(() => []);
69
- if (files.length) die(`Target directory '${path.basename(dir)}' is not empty.`);
188
+ async function ensureEmptyDir( dir ) {
189
+
190
+ try {
191
+
192
+ await fsp.mkdir( dir, { recursive: true } );
193
+
194
+ } catch {}
195
+
196
+ const files = await fsp.readdir( dir ).catch( () => [] );
197
+ if ( files.length ) die( `Target directory '${path.basename( dir )}' is not empty.` );
198
+
70
199
  }
71
200
 
72
- async function promptHidden(label) {
73
- return await new Promise((resolve) => {
74
- const stdin = process.stdin;
75
- const stdout = process.stdout;
76
- let value = '';
77
- const cleanup = () => {
78
- stdin.removeListener('data', onData);
79
- if (stdin.isTTY) stdin.setRawMode(false);
80
- stdin.pause();
81
- };
82
- const onData = (chunk) => {
83
- const str = String(chunk);
84
- for (const ch of str) {
85
- if (ch === '\u0003') { cleanup(); process.exit(1); }
86
- if (ch === '\r' || ch === '\n' || ch === '\u0004') {
87
- stdout.write('\n');
88
- cleanup();
89
- return resolve(value.trim());
90
- }
91
- if (ch === '\u0008' || ch === '\u007f') {
92
- if (value.length) {
93
- value = value.slice(0, -1);
94
- readline.moveCursor(stdout, -1, 0);
95
- stdout.write(' ');
96
- readline.moveCursor(stdout, -1, 0);
97
- }
98
- continue;
99
- }
100
- // Ignore ESC start of control sequences
101
- if (ch === '\u001b') continue;
102
- value += ch;
103
- stdout.write('•');
104
- }
105
- };
106
- stdout.write(label);
107
- stdin.setEncoding('utf8');
108
- if (stdin.isTTY) stdin.setRawMode(true);
109
- stdin.resume();
110
- stdin.on('data', onData);
111
- });
201
+ async function promptHidden( label ) {
202
+
203
+ return await new Promise( ( resolve ) => {
204
+
205
+ const stdin = process.stdin;
206
+ const stdout = process.stdout;
207
+ let value = '';
208
+ const cleanup = () => {
209
+
210
+ stdin.removeListener( 'data', onData );
211
+ if ( stdin.isTTY ) stdin.setRawMode( false );
212
+ stdin.pause();
213
+
214
+ };
215
+
216
+ const onData = ( chunk ) => {
217
+
218
+ const str = String( chunk );
219
+ for ( const ch of str ) {
220
+
221
+ if ( ch === '\u0003' ) {
222
+
223
+ cleanup(); process.exit( 1 );
224
+
225
+ }
226
+
227
+ if ( ch === '\r' || ch === '\n' || ch === '\u0004' ) {
228
+
229
+ stdout.write( '\n' );
230
+ cleanup();
231
+ return resolve( value.trim() );
232
+
233
+ }
234
+
235
+ if ( ch === '\u0008' || ch === '\u007f' ) {
236
+
237
+ if ( value.length ) {
238
+
239
+ value = value.slice( 0, - 1 );
240
+ readline.moveCursor( stdout, - 1, 0 );
241
+ stdout.write( ' ' );
242
+ readline.moveCursor( stdout, - 1, 0 );
243
+
244
+ }
245
+
246
+ continue;
247
+
248
+ }
249
+
250
+ // Ignore ESC start of control sequences
251
+ if ( ch === '\u001b' ) continue;
252
+ value += ch;
253
+ stdout.write( '•' );
254
+
255
+ }
256
+
257
+ };
258
+
259
+ stdout.write( label );
260
+ stdin.setEncoding( 'utf8' );
261
+ if ( stdin.isTTY ) stdin.setRawMode( true );
262
+ stdin.resume();
263
+ stdin.on( 'data', onData );
264
+
265
+ } );
266
+
112
267
  }
113
268
 
114
- function mkTmpDir(prefix = 'three-blocks-') {
115
- return fs.mkdtempSync(path.join(os.tmpdir(), prefix));
269
+ function mkTmpDir( prefix = 'three-blocks-' ) {
270
+
271
+ return fs.mkdtempSync( path.join( os.tmpdir(), prefix ) );
272
+
116
273
  }
117
274
 
118
- function mask(s) {
119
- if (!s) return '';
120
- const v = String(s);
121
- if (v.length <= 6) return '••••';
122
- return v.slice(0, 3) + '••••' + v.slice(-4);
275
+ function mask( s ) {
276
+
277
+ if ( ! s ) return '';
278
+ const v = String( s );
279
+ if ( v.length <= 6 ) return '••••';
280
+ return v.slice( 0, 3 ) + '••••' + v.slice( - 4 );
281
+
123
282
  }
124
283
 
125
- const BROKER_DEFAULT_ENDPOINT = process.env.THREE_BLOCKS_BROKER_URL || 'http://localhost:3000/api/npm/token';
126
-
127
- const resolveBrokerEndpoint = (channel) => {
128
- let endpoint = BROKER_DEFAULT_ENDPOINT;
129
- try {
130
- const u = new URL(endpoint);
131
- if (channel && !u.searchParams.get('channel')) {
132
- u.searchParams.set('channel', channel);
133
- }
134
- endpoint = u.toString();
135
- } catch {}
136
- return endpoint;
284
+ const BROKER_DEFAULT_ENDPOINT = process.env.THREE_BLOCKS_BROKER_URL || 'https://www.threejs-blocks.com/api/npm/token';
285
+
286
+ const resolveBrokerEndpoint = ( channel ) => {
287
+
288
+ let endpoint = BROKER_DEFAULT_ENDPOINT;
289
+ try {
290
+
291
+ const u = new URL( endpoint );
292
+ if ( channel && ! u.searchParams.get( 'channel' ) ) {
293
+
294
+ u.searchParams.set( 'channel', channel );
295
+
296
+ }
297
+
298
+ endpoint = u.toString();
299
+
300
+ } catch {}
301
+
302
+ return endpoint;
303
+
137
304
  };
138
305
 
139
- const fetchTokenMetadata = async (license, channel) => {
140
- if (!license || typeof fetch !== 'function') return null;
141
- const endpoint = resolveBrokerEndpoint(channel);
142
- try {
143
- const res = await fetch(endpoint, {
144
- method: 'GET',
145
- headers: {
146
- authorization: `Bearer ${license}`,
147
- accept: 'application/json',
148
- 'x-three-blocks-channel': channel,
149
- },
150
- });
151
- if (!res.ok) {
152
- throw new Error(`HTTP ${res.status}`);
153
- }
154
- return await res.json();
155
- } catch (err) {
156
- const msg = err instanceof Error ? err.message : String(err);
157
- logWarn(`Continuing without token metadata (${msg})`);
158
- return null;
159
- }
306
+ const fetchTokenMetadata = async ( license, channel ) => {
307
+
308
+ if ( ! license || typeof fetch !== 'function' ) return null;
309
+ const endpoint = resolveBrokerEndpoint( channel );
310
+ try {
311
+
312
+ const res = await fetch( endpoint, {
313
+ method: 'GET',
314
+ headers: {
315
+ authorization: `Bearer ${license}`,
316
+ accept: 'application/json',
317
+ 'x-three-blocks-channel': channel,
318
+ },
319
+ } );
320
+ if ( ! res.ok ) {
321
+
322
+ throw new Error( `HTTP ${res.status}` );
323
+
324
+ }
325
+
326
+ return await res.json();
327
+
328
+ } catch ( err ) {
329
+
330
+ const msg = err instanceof Error ? err.message : String( err );
331
+ logWarn( `Continuing without token metadata (${msg})` );
332
+ return null;
333
+
334
+ }
335
+
160
336
  };
161
337
 
162
- const formatRegistryShort = (value) => {
163
- if (!value) return '';
164
- try {
165
- const u = new URL(value);
166
- const pathname = (u.pathname || '').replace(/\/$/, '');
167
- return `${u.host}${pathname}`;
168
- } catch {
169
- return String(value);
170
- }
338
+ const formatRegistryShort = ( value ) => {
339
+
340
+ if ( ! value ) return '';
341
+ try {
342
+
343
+ const u = new URL( value );
344
+ const pathname = ( u.pathname || '' ).replace( /\/$/, '' );
345
+ return `${u.host}${pathname}`;
346
+
347
+ } catch {
348
+
349
+ return String( value );
350
+
351
+ }
352
+
171
353
  };
172
354
 
173
- const formatExpiryLabel = (iso) => {
174
- if (!iso) return 'Expires: —';
175
- const dt = new Date(iso);
176
- if (Number.isNaN(dt.getTime())) return `Expires: ${iso}`;
177
- return `Expires: ${dt.toISOString().replace('T', ' ').replace('Z', 'Z')}`;
355
+ const formatExpiryLabel = ( iso ) => {
356
+
357
+ if ( ! iso ) return 'Expires: —';
358
+ const dt = new Date( iso );
359
+ if ( Number.isNaN( dt.getTime() ) ) return `Expires: ${iso}`;
360
+ return `Expires: ${dt.toISOString().replace( 'T', ' ' ).replace( 'Z', 'Z' )}`;
361
+
178
362
  };
179
363
 
180
364
  const HEADER_WIDTH = 118;
181
365
  const LEFT_WIDTH = 72;
182
366
  const RIGHT_WIDTH = HEADER_WIDTH - LEFT_WIDTH - 3;
183
367
 
184
- const repeatChar = (ch, len) => ch.repeat(Math.max(0, len));
185
- const stripAnsi = (value) => String(value ?? '').replace(/\u001b\[[0-9;]*m/g, '');
186
- const ellipsize = (value, width) => {
187
- const str = String(value ?? '');
188
- const plain = stripAnsi(str);
189
- if (plain.length <= width) return str;
190
- if (width <= 1) return plain.slice(0, width);
191
- const truncated = plain.slice(0, width - 1) + '…';
192
- return plain === str ? truncated : truncated;
368
+ const repeatChar = ( ch, len ) => ch.repeat( Math.max( 0, len ) );
369
+ const stripAnsi = ( value ) => String( value ?? '' ).replace( /\u001b\[[0-9;]*m/g, '' );
370
+ const ellipsize = ( value, width ) => {
371
+
372
+ const str = String( value ?? '' );
373
+ const plain = stripAnsi( str );
374
+ if ( plain.length <= width ) return str;
375
+ if ( width <= 1 ) return plain.slice( 0, width );
376
+ const truncated = plain.slice( 0, width - 1 ) + '…';
377
+ return plain === str ? truncated : truncated;
378
+
193
379
  };
194
- const visibleLength = (value) => stripAnsi(String(value ?? '')).length;
195
- const padText = (value, width, align = 'left') => {
196
- const text = ellipsize(value, width);
197
- const remaining = width - visibleLength(text);
198
- if (remaining <= 0) return text;
199
- if (align === 'center') {
200
- const left = Math.floor(remaining / 2);
201
- const right = remaining - left;
202
- return `${' '.repeat(left)}${text}${' '.repeat(right)}`;
203
- }
204
- if (align === 'right') {
205
- return `${' '.repeat(remaining)}${text}`;
206
- }
207
- return `${text}${' '.repeat(remaining)}`;
380
+
381
+ const visibleLength = ( value ) => stripAnsi( String( value ?? '' ) ).length;
382
+ const padText = ( value, width, align = 'left' ) => {
383
+
384
+ const text = ellipsize( value, width );
385
+ const remaining = width - visibleLength( text );
386
+ if ( remaining <= 0 ) return text;
387
+ if ( align === 'center' ) {
388
+
389
+ const left = Math.floor( remaining / 2 );
390
+ const right = remaining - left;
391
+ return `${' '.repeat( left )}${text}${' '.repeat( right )}`;
392
+
393
+ }
394
+
395
+ if ( align === 'right' ) {
396
+
397
+ return `${' '.repeat( remaining )}${text}`;
398
+
399
+ }
400
+
401
+ return `${text}${' '.repeat( remaining )}`;
402
+
208
403
  };
209
- const makeHeaderRow = (left, right = '', leftAlign = 'left', rightAlign = 'left') =>
210
- `│${padText(left, LEFT_WIDTH, leftAlign)}│${padText(right, RIGHT_WIDTH, rightAlign)}│`;
211
-
212
- const HEADER_COLOR = ESC(33);
213
- const CONTENT_COLOR = ESC(90);
214
- const reapplyColor = (value, color) => {
215
- const str = String(value ?? '');
216
- return `${color}${str.split(reset).join(`${reset}${color}`)}${reset}`;
404
+
405
+ const makeHeaderRow = ( left, right = '', leftAlign = 'left', rightAlign = 'left' ) =>
406
+ `│${padText( left, LEFT_WIDTH, leftAlign )}│${padText( right, RIGHT_WIDTH, rightAlign )}│`;
407
+
408
+ const HEADER_COLOR = ESC( 33 );
409
+ const CONTENT_COLOR = ESC( 90 );
410
+ const reapplyColor = ( value, color ) => {
411
+
412
+ const str = String( value ?? '' );
413
+ return `${color}${str.split( reset ).join( `${reset}${color}` )}${reset}`;
414
+
217
415
  };
218
416
 
219
- const applyHeaderColor = (row, { keepContentYellow = false, tintContent = true } = {}) => {
220
- if (keepContentYellow) return reapplyColor(row, HEADER_COLOR);
221
- if (!row.startsWith('│') || !row.endsWith('│')) return reapplyColor(row, HEADER_COLOR);
222
- const match = row.match(/^│(.*)(.*)│$/);
223
- if (!match) return reapplyColor(row, HEADER_COLOR);
224
- const [, leftContent, rightContent] = match;
225
- const leftSegment = tintContent ? reapplyColor(leftContent, CONTENT_COLOR) : leftContent;
226
- const rightSegment = tintContent ? reapplyColor(rightContent, CONTENT_COLOR) : rightContent;
227
- return `${HEADER_COLOR}│${reset}${leftSegment}${HEADER_COLOR}│${reset}${rightSegment}${HEADER_COLOR}│${reset}`;
417
+ const applyHeaderColor = ( row, { keepContentYellow = false, tintContent = true } = {} ) => {
418
+
419
+ if ( keepContentYellow ) return reapplyColor( row, HEADER_COLOR );
420
+ if ( ! row.startsWith( '│' ) || ! row.endsWith( '│' ) ) return reapplyColor( row, HEADER_COLOR );
421
+ const match = row.match( /^│(.*)│(.*)│$/ );
422
+ if ( ! match ) return reapplyColor( row, HEADER_COLOR );
423
+ const [ , leftContent, rightContent ] = match;
424
+ const leftSegment = tintContent ? reapplyColor( leftContent, CONTENT_COLOR ) : leftContent;
425
+ const rightSegment = tintContent ? reapplyColor( rightContent, CONTENT_COLOR ) : rightContent;
426
+ return `${HEADER_COLOR}│${reset}${leftSegment}${HEADER_COLOR}│${reset}${rightSegment}${HEADER_COLOR}│${reset}`;
427
+
228
428
  };
229
429
 
230
- const capitalize = (value) => {
231
- const str = String(value || '').trim();
232
- if (!str) return '';
233
- return str[0].toUpperCase() + str.slice(1);
430
+ const capitalize = ( value ) => {
431
+
432
+ const str = String( value || '' ).trim();
433
+ if ( ! str ) return '';
434
+ return str[ 0 ].toUpperCase() + str.slice( 1 );
435
+
234
436
  };
235
437
 
236
- const formatPlanLabel = (value) => {
237
- const str = String(value || '').trim();
238
- if (!str) return '';
239
- return str
240
- .split(/\s+/)
241
- .map((part) => (part ? capitalize(part.toLowerCase()) : ''))
242
- .join(' ')
243
- .trim();
438
+ const formatPlanLabel = ( value ) => {
439
+
440
+ const str = String( value || '' ).trim();
441
+ if ( ! str ) return '';
442
+ return str
443
+ .split( /\s+/ )
444
+ .map( ( part ) => ( part ? capitalize( part.toLowerCase() ) : '' ) )
445
+ .join( ' ' )
446
+ .trim();
447
+
244
448
  };
245
449
 
246
- const formatFirstName = (value) => {
247
- const name = String(value || '').trim();
248
- if (!name) return '';
249
- const first = name.split(/\s+/)[0];
250
- return capitalize(first);
450
+ const formatFirstName = ( value ) => {
451
+
452
+ const name = String( value || '' ).trim();
453
+ if ( ! name ) return '';
454
+ const first = name.split( /\s+/ )[ 0 ];
455
+ return capitalize( first );
456
+
251
457
  };
252
458
 
253
459
  const getUserDisplayName = () => {
254
- const candidate = process.env.THREE_BLOCKS_USER_NAME
460
+
461
+ const candidate = process.env.THREE_BLOCKS_USER_NAME
255
462
  || process.env.GIT_AUTHOR_NAME
256
463
  || process.env.USER
257
464
  || process.env.LOGNAME;
258
- if (candidate) return formatFirstName(candidate);
259
- try {
260
- return formatFirstName(os.userInfo().username);
261
- } catch {
262
- return '';
263
- }
465
+ if ( candidate ) return formatFirstName( candidate );
466
+ try {
467
+
468
+ return formatFirstName( os.userInfo().username );
469
+
470
+ } catch {
471
+
472
+ return '';
473
+
474
+ }
475
+
264
476
  };
265
477
 
266
- const inferPlan = (license) => {
267
- if (!license) return 'Unknown plan';
268
- if (/live/i.test(license)) return 'Pro Plan';
269
- if (/test/i.test(license)) return 'Sandbox Plan';
270
- if (/beta/i.test(license)) return 'Beta Plan';
271
- return 'Developer Plan';
478
+ const inferPlan = ( license ) => {
479
+
480
+ if ( ! license ) return 'Unknown plan';
481
+ if ( /live/i.test( license ) ) return 'Pro Plan';
482
+ if ( /test/i.test( license ) ) return 'Sandbox Plan';
483
+ if ( /beta/i.test( license ) ) return 'Beta Plan';
484
+ return 'Developer Plan';
485
+
272
486
  };
273
487
 
274
- const extractVersionFromTarball = (filename) => {
275
- if (!filename) return '';
276
- const match = filename.match(/-(\d+\.\d+\.\d+(?:-[^.]*)?)\.tgz$/);
277
- return match ? match[1] : '';
488
+ const extractVersionFromTarball = ( filename ) => {
489
+
490
+ if ( ! filename ) return '';
491
+ const match = filename.match( /-(\d+\.\d+\.\d+(?:-[^.]*)?)\.tgz$/ );
492
+ return match ? match[ 1 ] : '';
493
+
278
494
  };
279
495
 
280
- const renderHeader = ({
281
- starterVersion,
282
- userDisplayName,
283
- planName,
284
- repoPath,
285
- projectName,
286
- channel,
287
- coreVersion,
288
- license,
289
- registry,
290
- domain,
291
- region,
292
- repository,
293
- expiresAt,
294
- teamId,
295
- teamName,
296
- licenseId,
297
- }) => {
298
- const welcome = userDisplayName ? `Welcome back ${userDisplayName}!` : 'Welcome!';
299
- const normalizedPlan = planName || 'Unknown plan';
300
- const resolvedTeamName = teamName || teamId || '';
301
- const planSuffix = resolvedTeamName ? ` · Team: ${resolvedTeamName}` : '';
302
- const planLine = `@three-blocks/core ${coreVersion || (channel === 'stable' ? 'latest' : channel)} · ${normalizedPlan}${planSuffix}`;
303
- const channelDisplay = (channel || 'stable').toUpperCase();
304
- const channelLine = `Channel: ${channelDisplay}${region ? ` · Region: ${region}` : ''}`;
305
- const repositoryLineBase = repository ? `Repository: ${repository}` : 'Repository: —';
306
- const registryShort = formatRegistryShort(registry);
307
- const repositoryLine = registryShort ? `${repositoryLineBase} → ${registryShort}` : repositoryLineBase;
308
- const registryLine = `Registry: ${registryShort || '—'}`;
309
- const licenseLine = `License: ${mask(license)}${licenseId ? ` · ${licenseId}` : ''}`;
310
- const expiresLine = formatExpiryLabel(expiresAt);
311
- const projectLabel = projectName || path.basename(repoPath);
312
- const projectLine = `Project: ${projectLabel}`;
313
- const domainLine = domain ? `Domain: ${domain}` : '';
314
- const regionLine = region ? `Region: ${region}` : '';
315
- const title = `─── Three.js Blocks Starter v${starterVersion || '?.?.?'} `;
316
- const separatorRow = makeHeaderRow(repeatChar('─', LEFT_WIDTH), repeatChar('', RIGHT_WIDTH));
317
- const ascii = [
318
- 'THREE.JS',
319
- ' ______ __ ______ ______ __ __ ______ ',
320
- '/\\ == \\ /\\ \\ /\\ __ \\ /\\ ___\\ /\\ \\/ / /\\ ___\\ ',
321
- '\\ \\ __< \\ \\ \\____ \\ \\ \\/\\ \\ \\ \\ \\____ \\ \\ _"-. \\ \\___ \\ ',
322
- ' \\ \\_____\\ \\ \\_____\\ \\ \\_____\\ \\ \\_____\\ \\ \\_\\ \\_\\ \\/\\_____\\',
323
- ' \\/_____\/ \\/_____/ \\/_____/ \\/_____/ \\/_/ \/_/ \\/_____/'
324
- ];
325
- const lines = [
326
- applyHeaderColor(`╭${title}${repeatChar('─', HEADER_WIDTH - 2 - title.length)}╮`, { keepContentYellow: true }),
327
- ...ascii.map((row) => applyHeaderColor(`│${padText(row, LEFT_WIDTH + RIGHT_WIDTH + 1, 'center')}│`, { keepContentYellow: true })),
328
- applyHeaderColor(separatorRow, { keepContentYellow: true }),
329
- applyHeaderColor(makeHeaderRow(welcome, projectLine, 'center', 'center')),
330
- applyHeaderColor(separatorRow, { keepContentYellow: true }),
331
- applyHeaderColor(makeHeaderRow(planLine, channelLine)),
332
- applyHeaderColor(makeHeaderRow(repositoryLine, registryLine)),
333
- ...(domainLine || regionLine ? [applyHeaderColor(makeHeaderRow(domainLine || '', regionLine, 'left', 'center'))] : []),
334
- applyHeaderColor(makeHeaderRow(licenseLine, expiresLine)),
335
- applyHeaderColor(`╰${repeatChar('─', HEADER_WIDTH - 2)}╯`, { keepContentYellow: true }),
336
- ];
337
- for (const row of lines) console.log(row);
496
+ const renderHeader = ( {
497
+ starterVersion,
498
+ userDisplayName,
499
+ planName,
500
+ repoPath,
501
+ projectName,
502
+ channel,
503
+ coreVersion,
504
+ license,
505
+ registry,
506
+ domain,
507
+ region,
508
+ repository,
509
+ expiresAt,
510
+ teamId,
511
+ teamName,
512
+ licenseId,
513
+ } ) => {
514
+
515
+ const welcome = userDisplayName ? `Welcome back ${userDisplayName}!` : 'Welcome!';
516
+ const normalizedPlan = planName || 'Unknown plan';
517
+ const resolvedTeamName = teamName || teamId || '';
518
+ const planSuffix = resolvedTeamName ? ` · Team: ${resolvedTeamName}` : '';
519
+ const planLine = `@three-blocks/core ${coreVersion || ( channel === 'stable' ? 'latest' : channel )} · ${normalizedPlan}${planSuffix}`;
520
+ const channelDisplay = ( channel || 'stable' ).toUpperCase();
521
+ const channelLine = `Channel: ${channelDisplay}${region ? ` · Region: ${region}` : ''}`;
522
+ const repositoryLineBase = repository ? `Repository: ${repository}` : 'Repository: —';
523
+ const registryShort = formatRegistryShort( registry );
524
+ const repositoryLine = registryShort ? `${repositoryLineBase} → ${registryShort}` : repositoryLineBase;
525
+ const registryLine = `Registry: ${registryShort || ''}`;
526
+ const licenseLine = `License: ${mask( license )}${licenseId ? ` · ${licenseId}` : ''}`;
527
+ const expiresLine = formatExpiryLabel( expiresAt );
528
+ const projectLabel = projectName || path.basename( repoPath );
529
+ const projectLine = `Project: ${projectLabel}`;
530
+ const domainLine = domain ? `Domain: ${domain}` : '';
531
+ const regionLine = region ? `Region: ${region}` : '';
532
+ const title = `─── Three.js Blocks Starter v${starterVersion || '?.?.?'} `;
533
+ const separatorRow = makeHeaderRow( repeatChar( '─', LEFT_WIDTH ), repeatChar( '─', RIGHT_WIDTH ) );
534
+ const ascii = [
535
+ 'THREE.JS',
536
+ ' ______ __ ______ ______ __ __ ______ ',
537
+ '/\\ == \\ /\\ \\ /\\ __ \\ /\\ ___\\ /\\ \\/ / /\\ ___\\ ',
538
+ '\\ \\ __< \\ \\ \\____ \\ \\ \\/\\ \\ \\ \\ \\____ \\ \\ _"-. \\ \\___ \\ ',
539
+ ' \\ \\_____\\ \\ \\_____\\ \\ \\_____\\ \\ \\_____\\ \\ \\_\\ \\_\\ \\/\\_____\\',
540
+ ' \\/_____\/ \\/_____/ \\/_____/ \\/_____/ \\/_/ \/_/ \\/_____/'
541
+ ];
542
+ const lines = [
543
+ applyHeaderColor( `╭${title}${repeatChar( '─', HEADER_WIDTH - 2 - title.length )}╮`, { keepContentYellow: true } ),
544
+ ...ascii.map( ( row ) => applyHeaderColor( `│${padText( row, LEFT_WIDTH + RIGHT_WIDTH + 1, 'center' )}│`, { keepContentYellow: true } ) ),
545
+ applyHeaderColor( separatorRow, { keepContentYellow: true } ),
546
+ applyHeaderColor( makeHeaderRow( welcome, projectLine, 'center', 'center' ) ),
547
+ applyHeaderColor( separatorRow, { keepContentYellow: true } ),
548
+ applyHeaderColor( makeHeaderRow( planLine, channelLine ) ),
549
+ applyHeaderColor( makeHeaderRow( repositoryLine, registryLine ) ),
550
+ ...( domainLine || regionLine ? [ applyHeaderColor( makeHeaderRow( domainLine || '', regionLine, 'left', 'center' ) ) ] : [] ),
551
+ applyHeaderColor( makeHeaderRow( licenseLine, expiresLine ) ),
552
+ applyHeaderColor( `╰${repeatChar( '─', HEADER_WIDTH - 2 )}╯`, { keepContentYellow: true } ),
553
+ ];
554
+ for ( const row of lines ) console.log( row );
555
+
338
556
  };
339
557
 
340
558
  async function main() {
341
- const args = process.argv.slice(2);
342
- let appName = '';
343
- let channel = String(process.env.THREE_BLOCKS_CHANNEL || 'stable').toLowerCase();
344
- const userDisplayName = getUserDisplayName();
345
- const repoPath = process.cwd();
346
- for (let i = 0; i < args.length; i++) {
347
- const a = args[i];
348
- if (!a.startsWith('-') && !appName) { appName = a; continue; }
349
- if (a === '--channel' || a === '-c') { const v = args[i + 1]; if (v) { channel = String(v).toLowerCase(); i++; } continue; }
350
- const m = a.match(/^--channel=(.+)$/);
351
- if (m) { channel = String(m[1]).toLowerCase(); continue; }
352
- }
353
- if (!['stable', 'beta', 'alpha'].includes(channel)) channel = 'stable';
354
- if (!appName) {
355
- die(
356
- `Usage:\n` +
357
- ` THREE_BLOCKS_SECRET_KEY=sk_live_... npx three-blocks-create-app <directory>\n` +
358
- ` (or: npx three-blocks-create-app <directory> and enter the key when prompted)`
359
- );
360
- }
361
-
362
- const targetDir = path.resolve(process.cwd(), appName);
363
- await ensureEmptyDir(targetDir);
364
-
365
- // 1) License key (env or prompt)
366
- let license = process.env.THREE_BLOCKS_SECRET_KEY;
367
- if (license) {
368
- logInfo(`Using ${bold('THREE_BLOCKS_SECRET_KEY')} from environment ${dim(`(${mask(license)})`)}`);
369
- } else {
370
- console.log('');
371
- logInfo(bold(cyan('Three Blocks Starter')) + ' ' + dim(`[channel: ${channel}]`));
372
- logInfo(dim('Enter your license key to continue.'));
373
- logInfo(dim('Tip: paste it here; input is hidden. Press Enter to submit.'));
374
- license = await promptHidden(`${STEP_ICON}${bold('License key')} ${dim('(tb_…)')}: `);
375
- if (!license) die('License key is required to install private packages.');
376
- }
377
- let planName = inferPlan(license);
378
- const tokenMetadata = await fetchTokenMetadata(license, channel);
379
- let headerChannel = channel;
380
- if (tokenMetadata?.channel) {
381
- const maybeChannel = String(tokenMetadata.channel).toLowerCase();
382
- if (['stable', 'beta', 'alpha'].includes(maybeChannel)) headerChannel = maybeChannel;
383
- }
384
- if (tokenMetadata?.plan) {
385
- const label = formatPlanLabel(tokenMetadata.plan);
386
- if (label) {
387
- planName = label.toLowerCase().includes('plan') ? label : `${label} Plan`;
388
- }
389
- }
390
- let headerRegistry = tokenMetadata?.registry ? String(tokenMetadata.registry) : '';
391
- const headerDomain = tokenMetadata?.domain ? String(tokenMetadata.domain) : '';
392
- const headerRegion = tokenMetadata?.region ? String(tokenMetadata.region) : '';
393
- const headerRepository = tokenMetadata?.repository ? String(tokenMetadata.repository) : '';
394
- const headerExpires = tokenMetadata?.expiresAt ?? tokenMetadata?.expiresAtIso ?? null;
395
- const headerTeamId = tokenMetadata?.teamId ? String(tokenMetadata.teamId) : '';
396
- const headerTeamName = tokenMetadata?.teamName ? String(tokenMetadata.teamName) : '';
397
- const headerLicenseId = tokenMetadata?.licenseId ? String(tokenMetadata.licenseId) : '';
398
-
399
- // 2) Pre-login in a TEMP dir to generate a temp .npmrc (no always-auth)
400
- const tmp = mkTmpDir();
401
- const tmpNpmrc = path.join(tmp, '.npmrc');
402
- logProgress(`Fetching short-lived token (temp .npmrc) [channel: ${channel}] ...`);
403
- run('npx', ['-y', LOGIN_CLI, '--mode', 'project', '--scope', SCOPE, '--channel', channel], {
404
- cwd: tmp,
405
- env: { ...process.env, THREE_BLOCKS_SECRET_KEY: license, THREE_BLOCKS_CHANNEL: channel },
406
- });
407
- if (!fs.existsSync(tmpNpmrc)) die('Login failed: temp .npmrc not created.');
408
- // Extract registry URL from temp .npmrc so we can pass it explicitly to npm create
409
- let registryUrl = '';
410
- try {
411
- const txt = fs.readFileSync(tmpNpmrc, 'utf8');
412
- const m = txt.match(/^@[^:]+:registry=(.+)$/m);
413
- if (m && m[1]) registryUrl = m[1].trim();
414
- } catch {}
415
- if (!headerRegistry && registryUrl) headerRegistry = registryUrl;
416
-
417
- // 3) Scaffold the private starter by packing and extracting the tarball (avoids npm create naming transform)
418
- const starterSpec = `${STARTER_PKG}@${channel === 'stable' ? 'latest' : channel}`;
419
- logProgress(`Fetching starter tarball ${starterSpec} ...`);
420
- const createEnv = {
421
- ...process.env,
422
- THREE_BLOCKS_SECRET_KEY: license,
423
- NPM_CONFIG_USERCONFIG: tmpNpmrc,
424
- npm_config_userconfig: tmpNpmrc,
425
- };
426
- let packedOut = exec('npm', ['pack', starterSpec, '--json', '--silent'], { cwd: tmp, env: createEnv });
427
- let tarName = '';
428
- let starterVersion = '';
429
- try {
430
- const info = JSON.parse(packedOut);
431
- if (Array.isArray(info)) {
432
- tarName = info[0]?.filename || '';
433
- starterVersion = info[0]?.version || '';
434
- } else {
435
- tarName = info.filename || '';
436
- starterVersion = info.version || '';
437
- }
438
- } catch {
439
- const lines = String(packedOut || '').trim().split(/\r?\n/);
440
- tarName = lines[lines.length - 1] || '';
441
- }
442
- const tarPath = path.join(tmp, tarName);
443
- if (!tarName || !fs.existsSync(tarPath)) die('Failed to fetch starter tarball.');
444
- const headerStarterVersion = starterVersion || extractVersionFromTarball(tarName);
445
- const headerCoreVersion = headerChannel === 'stable' ? 'latest' : headerChannel;
446
- renderHeader({
447
- starterVersion: headerStarterVersion,
448
- userDisplayName,
449
- planName,
450
- repoPath,
451
- projectName: appName,
452
- channel: headerChannel,
453
- coreVersion: headerCoreVersion,
454
- license,
455
- registry: headerRegistry,
456
- domain: headerDomain,
457
- region: headerRegion,
458
- repository: headerRepository,
459
- expiresAt: headerExpires,
460
- teamId: headerTeamId,
461
- teamName: headerTeamName,
462
- licenseId: headerLicenseId,
463
- });
464
- logProgress('Extracting files ...');
465
- run('tar', ['-xzf', tarPath, '-C', targetDir, '--strip-components=1']);
466
-
467
- // 4) Write .env.local and .gitignore entries
468
- await fsp.writeFile(path.join(targetDir, '.env.local'),
469
- `THREE_BLOCKS_SECRET_KEY=${license}\nTHREE_BLOCKS_CHANNEL=${channel}\n`, { mode: 0o600 }).catch(() => {});
470
- const giPath = path.join(targetDir, '.gitignore');
471
- let gi = '';
472
- try { gi = await fsp.readFile(giPath, 'utf8'); } catch {}
473
- for (const line of ['.env.local', '.npmrc']) {
474
- if (!gi.includes(line)) gi += (gi.endsWith('\n') || gi === '' ? '' : '\n') + line + '\n';
475
- }
476
- await fsp.writeFile(giPath, gi);
477
-
478
- // 5) First install — the starter already has:
479
- // "preinstall": "npx -y three-blocks-login --mode project --scope @three-blocks"
480
- // so it will mint a fresh token and write a project .npmrc.
481
- try {
482
- const pkgPath = path.join(targetDir, 'package.json');
483
- const pkgRaw = await fsp.readFile(pkgPath, 'utf8');
484
- const pkg = JSON.parse(pkgRaw);
485
- pkg.scripts = pkg.scripts || {};
486
- if (!pkg.scripts.preinstall) {
487
- pkg.scripts.preinstall = `npx -y ${LOGIN_CLI} --mode project --scope ${SCOPE} --channel ${channel}`;
488
- }
489
- await fsp.writeFile(pkgPath, JSON.stringify(pkg, null, 2));
490
- logSuccess('Added preinstall to generated package.json to refresh token on installs.');
491
- } catch (e) {
492
- logWarn(`Warning: could not add preinstall to package.json: ${e?.message || String(e)}`);
493
- }
494
-
495
- logProgress('Installing dependencies (preinstall will refresh token) ...');
496
- const hasPnpm = spawnSync('pnpm', ['-v'], { stdio: 'ignore' }).status === 0;
497
- run(hasPnpm ? 'pnpm' : 'npm', [hasPnpm ? 'install' : 'ci'], {
498
- cwd: targetDir,
499
- env: {
500
- ...process.env,
501
- THREE_BLOCKS_SECRET_KEY: license,
502
- THREE_BLOCKS_CHANNEL: channel,
503
- },
504
- });
505
-
506
- {
507
- const coreSpec = `@three-blocks/core@${channel === 'stable' ? 'latest' : channel}`;
508
- logProgress(`Installing ${coreSpec} ...`);
509
- const addArgs = hasPnpm ? ['add', '--save-exact', coreSpec] : ['install', '--save-exact', coreSpec];
510
- const r = spawnSync(hasPnpm ? 'pnpm' : 'npm', addArgs, {
511
- stdio: 'inherit',
512
- cwd: targetDir,
513
- env: {
514
- ...process.env,
515
- THREE_BLOCKS_SECRET_KEY: license,
516
- THREE_BLOCKS_CHANNEL: channel,
517
- },
518
- });
519
- if (r.status !== 0) {
520
- logWarn(`Warning: could not install @three-blocks/core (exit ${r.status}).`);
521
- }
522
- }
523
-
524
- // 6) Cleanup temp dir
525
- try { fs.rmSync(tmp, { recursive: true, force: true }); } catch {}
526
-
527
- console.log('');
528
- logSuccess(`${appName} is ready.`);
529
- console.log('');
530
- logInfo('Next:');
531
- console.log(` cd ${appName}`);
532
- console.log(` ${hasPnpm ? 'pnpm dev' : 'npm run dev'}`);
533
- console.log('');
534
- logInfo('Notes:');
535
- console.log(` • Your license key is stored in .env.local (gitignored).`);
536
- console.log(` • ${SCOPE} packages are private; each install refreshes a short-lived token via preinstall.`);
559
+
560
+ const args = process.argv.slice( 2 );
561
+ let appName = '';
562
+ let channel = String( process.env.THREE_BLOCKS_CHANNEL || 'stable' ).toLowerCase();
563
+ let debug = DEBUG;
564
+ const userDisplayName = getUserDisplayName();
565
+ const repoPath = process.cwd();
566
+ for ( let i = 0; i < args.length; i ++ ) {
567
+
568
+ const a = args[ i ];
569
+ if ( ! a.startsWith( '-' ) && ! appName ) {
570
+
571
+ appName = a; continue;
572
+
573
+ }
574
+
575
+ if ( a === '--debug' || a === '-d' ) {
576
+
577
+ debug = true; continue;
578
+
579
+ }
580
+
581
+ if ( a === '--channel' || a === '-c' ) {
582
+
583
+ const v = args[ i + 1 ]; if ( v ) {
584
+
585
+ channel = String( v ).toLowerCase(); i ++;
586
+
587
+ }
588
+
589
+ continue;
590
+
591
+ }
592
+
593
+ const m = a.match( /^--channel=(.+)$/ );
594
+ if ( m ) {
595
+
596
+ channel = String( m[ 1 ] ).toLowerCase(); continue;
597
+
598
+ }
599
+
600
+ }
601
+
602
+ DEBUG = debug;
603
+ if ( DEBUG ) logDebug( 'Debug logging enabled.' );
604
+
605
+ if ( ! [ 'stable', 'beta', 'alpha' ].includes( channel ) ) channel = 'stable';
606
+ if ( ! appName ) {
607
+
608
+ die(
609
+ `Usage:\n` +
610
+ ` THREE_BLOCKS_SECRET_KEY=sk_live_... npx create-three-blocks-starter <directory> [--channel <stable|beta|alpha>]\n` +
611
+ ` npx create-three-blocks-starter <directory> (will prompt for the license key)\n` +
612
+ ` Add --debug for verbose logging.`
613
+ );
614
+
615
+ }
616
+
617
+ const targetDir = path.resolve( process.cwd(), appName );
618
+ await ensureEmptyDir( targetDir );
619
+
620
+ // 1) License key (env or prompt)
621
+ let license = process.env.THREE_BLOCKS_SECRET_KEY;
622
+ if ( license ) {
623
+
624
+ logInfo( `Using ${bold( 'THREE_BLOCKS_SECRET_KEY' )} from environment ${dim( `(${mask( license )})` )}` );
625
+
626
+ } else {
627
+
628
+ console.log( '' );
629
+ logInfo( bold( cyan( 'Three Blocks Starter' ) ) + ' ' + dim( `[channel: ${channel}]` ) );
630
+ logInfo( dim( 'Enter your license key to continue.' ) );
631
+ logInfo( dim( 'Tip: paste it here; input is hidden. Press Enter to submit.' ) );
632
+ license = await promptHidden( `${STEP_ICON}${bold( 'License key' )} ${dim( '(tb_…)' )}: ` );
633
+ if ( ! license ) die( 'License key is required to install private packages.' );
634
+
635
+ }
636
+
637
+ let planName = inferPlan( license );
638
+ const tokenMetadata = await fetchTokenMetadata( license, channel );
639
+ let headerChannel = channel;
640
+ if ( tokenMetadata?.channel ) {
641
+
642
+ const maybeChannel = String( tokenMetadata.channel ).toLowerCase();
643
+ if ( [ 'stable', 'beta', 'alpha' ].includes( maybeChannel ) ) headerChannel = maybeChannel;
644
+
645
+ }
646
+
647
+ if ( tokenMetadata?.plan ) {
648
+
649
+ const label = formatPlanLabel( tokenMetadata.plan );
650
+ if ( label ) {
651
+
652
+ planName = label.toLowerCase().includes( 'plan' ) ? label : `${label} Plan`;
653
+
654
+ }
655
+
656
+ }
657
+
658
+ let headerRegistry = tokenMetadata?.registry ? String( tokenMetadata.registry ) : '';
659
+ const headerDomain = tokenMetadata?.domain ? String( tokenMetadata.domain ) : '';
660
+ const headerRegion = tokenMetadata?.region ? String( tokenMetadata.region ) : '';
661
+ const headerRepository = tokenMetadata?.repository ? String( tokenMetadata.repository ) : '';
662
+ const headerExpires = tokenMetadata?.expiresAt ?? tokenMetadata?.expiresAtIso ?? null;
663
+ const headerTeamId = tokenMetadata?.teamId ? String( tokenMetadata.teamId ) : '';
664
+ const headerTeamName = tokenMetadata?.teamName ? String( tokenMetadata.teamName ) : '';
665
+ const headerLicenseId = tokenMetadata?.licenseId ? String( tokenMetadata.licenseId ) : '';
666
+
667
+ // 2) Pre-login in a TEMP dir to generate a temp .npmrc (no always-auth)
668
+ let tmp = '';
669
+ let tmpNpmrc = '';
670
+ try {
671
+
672
+ tmp = mkTmpDir();
673
+ tmpNpmrc = path.join( tmp, '.npmrc' );
674
+ logProgress( `Fetching short-lived token (temp .npmrc) [channel: ${channel}] ...` );
675
+ try {
676
+
677
+ run( 'npx', [ '-y', LOGIN_SPEC, '--mode', 'project', '--scope', SCOPE, '--channel', channel ], {
678
+ cwd: tmp,
679
+ env: { ...process.env, THREE_BLOCKS_SECRET_KEY: license, THREE_BLOCKS_CHANNEL: channel },
680
+ } );
681
+
682
+ } catch ( err ) {
683
+
684
+ if ( err instanceof CliError ) {
685
+
686
+ throw new CliError(
687
+ 'Login failed while minting short-lived token.',
688
+ {
689
+ exitCode: err.exitCode,
690
+ command: err.command,
691
+ args: err.args,
692
+ suggestion: 'Ensure the three-blocks-login CLI is reachable and your license key is valid.',
693
+ cause: err,
694
+ }
695
+ );
696
+
697
+ }
698
+
699
+ throw err;
700
+
701
+ }
702
+
703
+ if ( ! fs.existsSync( tmpNpmrc ) ) {
704
+
705
+ throw new CliError( 'Login failed: temp .npmrc not created.' );
706
+
707
+ }
708
+
709
+ // Extract registry URL from temp .npmrc so we can pass it explicitly to npm create
710
+ let registryUrl = '';
711
+ try {
712
+
713
+ const txt = fs.readFileSync( tmpNpmrc, 'utf8' );
714
+ const m = txt.match( /^@[^:]+:registry=(.+)$/m );
715
+ if ( m && m[ 1 ] ) registryUrl = m[ 1 ].trim();
716
+
717
+ } catch ( readErr ) {
718
+
719
+ logDebug( `Could not read temp .npmrc: ${readErr?.message || readErr}` );
720
+
721
+ }
722
+
723
+ if ( ! headerRegistry && registryUrl ) headerRegistry = registryUrl;
724
+
725
+ // 3) Scaffold the private starter by packing and extracting the tarball (avoids npm create naming transform)
726
+ const starterSpec = `${STARTER_PKG}@${channel === 'stable' ? 'latest' : channel}`;
727
+ logProgress( `Fetching starter tarball ${starterSpec} ...` );
728
+ const createEnv = {
729
+ ...process.env,
730
+ THREE_BLOCKS_SECRET_KEY: license,
731
+ NPM_CONFIG_USERCONFIG: tmpNpmrc,
732
+ npm_config_userconfig: tmpNpmrc,
733
+ };
734
+ const packArgs = [ 'pack', starterSpec, '--json' ];
735
+ if ( ! DEBUG ) packArgs.push( '--silent' );
736
+ let packedOut = '';
737
+ try {
738
+
739
+ packedOut = exec( 'npm', packArgs, { cwd: tmp, env: createEnv } );
740
+
741
+ } catch ( err ) {
742
+
743
+ if ( err instanceof CliError ) {
744
+
745
+ const baseMessage = `Failed to fetch starter tarball ${starterSpec}.`;
746
+ const detail = ( err.stderr || err.stdout || '' ).trim();
747
+ const message = detail ? baseMessage : `${baseMessage} ${err.message || ''}`.trim();
748
+ throw new CliError(
749
+ message,
750
+ {
751
+ exitCode: err.exitCode,
752
+ command: err.command,
753
+ args: err.args,
754
+ stdout: err.stdout,
755
+ stderr: err.stderr,
756
+ suggestion: 'Confirm your license has access to the selected channel and that the package version exists.',
757
+ cause: err,
758
+ }
759
+ );
760
+
761
+ }
762
+
763
+ throw new CliError(
764
+ `Failed to fetch starter tarball ${starterSpec}.`,
765
+ { cause: err }
766
+ );
767
+
768
+ }
769
+
770
+ let tarName = '';
771
+ let starterVersion = '';
772
+ try {
773
+
774
+ const info = JSON.parse( packedOut );
775
+ if ( Array.isArray( info ) ) {
776
+
777
+ tarName = info[ 0 ]?.filename || '';
778
+ starterVersion = info[ 0 ]?.version || '';
779
+
780
+ } else {
781
+
782
+ tarName = info.filename || '';
783
+ starterVersion = info.version || '';
784
+
785
+ }
786
+
787
+ } catch {
788
+
789
+ const lines = String( packedOut || '' ).trim().split( /\r?\n/ );
790
+ tarName = lines[ lines.length - 1 ] || '';
791
+
792
+ }
793
+
794
+ const tarPath = path.join( tmp, tarName );
795
+ if ( ! tarName || ! fs.existsSync( tarPath ) ) {
796
+
797
+ throw new CliError(
798
+ `Failed to fetch starter tarball ${starterSpec}.`,
799
+ { suggestion: 'Ensure the requested release is published and accessible for your channel.' }
800
+ );
801
+
802
+ }
803
+
804
+ const headerStarterVersion = starterVersion || extractVersionFromTarball( tarName );
805
+ const headerCoreVersion = headerChannel === 'stable' ? 'latest' : headerChannel;
806
+ renderHeader( {
807
+ starterVersion: headerStarterVersion,
808
+ userDisplayName,
809
+ planName,
810
+ repoPath,
811
+ projectName: appName,
812
+ channel: headerChannel,
813
+ coreVersion: headerCoreVersion,
814
+ license,
815
+ registry: headerRegistry,
816
+ domain: headerDomain,
817
+ region: headerRegion,
818
+ repository: headerRepository,
819
+ expiresAt: headerExpires,
820
+ teamId: headerTeamId,
821
+ teamName: headerTeamName,
822
+ licenseId: headerLicenseId,
823
+ } );
824
+ logProgress( 'Extracting files ...' );
825
+ try {
826
+
827
+ run( 'tar', [ '-xzf', tarPath, '-C', targetDir, '--strip-components=1' ] );
828
+
829
+ } catch ( err ) {
830
+
831
+ if ( err instanceof CliError ) {
832
+
833
+ throw new CliError(
834
+ 'Failed to extract starter files.',
835
+ {
836
+ exitCode: err.exitCode,
837
+ command: err.command,
838
+ args: err.args,
839
+ suggestion: 'Check file permissions and available disk space before retrying.',
840
+ cause: err,
841
+ }
842
+ );
843
+
844
+ }
845
+
846
+ throw err;
847
+
848
+ }
849
+
850
+ } finally {
851
+
852
+ if ( tmp ) {
853
+
854
+ try {
855
+
856
+ fs.rmSync( tmp, { recursive: true, force: true } );
857
+
858
+ } catch ( cleanupErr ) {
859
+
860
+ logDebug( `Unable to remove temp directory ${tmp}: ${cleanupErr?.message || cleanupErr}` );
861
+
862
+ }
863
+
864
+ }
865
+
866
+ }
867
+
868
+ // 4) Write .env.local and .gitignore entries
869
+ await fsp.writeFile( path.join( targetDir, '.env.local' ),
870
+ `THREE_BLOCKS_SECRET_KEY=${license}\nTHREE_BLOCKS_CHANNEL=${channel}\n`, { mode: 0o600 } ).catch( () => {} );
871
+ const giPath = path.join( targetDir, '.gitignore' );
872
+ let gi = '';
873
+ try {
874
+
875
+ gi = await fsp.readFile( giPath, 'utf8' );
876
+
877
+ } catch {}
878
+
879
+ for ( const line of [ '.env.local', '.npmrc' ] ) {
880
+
881
+ if ( ! gi.includes( line ) ) gi += ( gi.endsWith( '\n' ) || gi === '' ? '' : '\n' ) + line + '\n';
882
+
883
+ }
884
+
885
+ await fsp.writeFile( giPath, gi );
886
+
887
+ // 5) First install — the starter already has:
888
+ // "preinstall": "npx -y three-blocks-login --mode project --scope @three-blocks"
889
+ // so it will mint a fresh token and write a project .npmrc.
890
+ try {
891
+
892
+ const pkgPath = path.join( targetDir, 'package.json' );
893
+ const pkgRaw = await fsp.readFile( pkgPath, 'utf8' );
894
+ const pkg = JSON.parse( pkgRaw );
895
+ pkg.scripts = pkg.scripts || {};
896
+ if ( ! pkg.scripts.preinstall ) {
897
+
898
+ pkg.scripts.preinstall = `npx -y ${LOGIN_CLI}@latest --mode project --scope ${SCOPE} --channel ${channel}`;
899
+
900
+ }
901
+
902
+ await fsp.writeFile( pkgPath, JSON.stringify( pkg, null, 2 ) );
903
+ logSuccess( 'Added preinstall to generated package.json to refresh token on installs.' );
904
+
905
+ } catch ( e ) {
906
+
907
+ logWarn( `Warning: could not add preinstall to package.json: ${e?.message || String( e )}` );
908
+
909
+ }
910
+
911
+ logProgress( 'Installing dependencies (preinstall will refresh token) ...' );
912
+ const hasPnpm = spawnSync( 'pnpm', [ '-v' ], { stdio: 'ignore', env: cleanNpmEnv() } ).status === 0;
913
+ try {
914
+
915
+ run( hasPnpm ? 'pnpm' : 'npm', [ hasPnpm ? 'install' : 'ci' ], {
916
+ cwd: targetDir,
917
+ env: {
918
+ ...process.env,
919
+ THREE_BLOCKS_SECRET_KEY: license,
920
+ THREE_BLOCKS_CHANNEL: channel,
921
+ },
922
+ } );
923
+
924
+ } catch ( err ) {
925
+
926
+ if ( err instanceof CliError ) {
927
+
928
+ throw new CliError(
929
+ 'Dependency installation failed.',
930
+ {
931
+ exitCode: err.exitCode,
932
+ command: err.command,
933
+ args: err.args,
934
+ stdout: err.stdout,
935
+ stderr: err.stderr,
936
+ suggestion: 'Inspect the log above for npm/pnpm errors or retry with --debug for full output.',
937
+ cause: err,
938
+ }
939
+ );
940
+
941
+ }
942
+
943
+ throw err;
944
+
945
+ }
946
+
947
+ {
948
+
949
+ const coreSpec = `@three-blocks/core@${channel === 'stable' ? 'latest' : channel}`;
950
+ logProgress( `Installing ${coreSpec} ...` );
951
+ const addArgs = hasPnpm ? [ 'add', '--save-exact', coreSpec ] : [ 'install', '--save-exact', coreSpec ];
952
+ const r = spawnSync( hasPnpm ? 'pnpm' : 'npm', addArgs, {
953
+ stdio: 'inherit',
954
+ cwd: targetDir,
955
+ env: cleanNpmEnv( {
956
+ THREE_BLOCKS_SECRET_KEY: license,
957
+ THREE_BLOCKS_CHANNEL: channel,
958
+ } ),
959
+ } );
960
+ if ( r.status !== 0 ) {
961
+
962
+ logWarn( `Warning: could not install @three-blocks/core (exit ${r.status}).` );
963
+
964
+ }
965
+
966
+ }
967
+
968
+ console.log( '' );
969
+ logSuccess( `${appName} is ready.` );
970
+ console.log( '' );
971
+ logInfo( 'Next:' );
972
+ console.log( ` cd ${appName}` );
973
+ console.log( ` ${hasPnpm ? 'pnpm dev' : 'npm run dev'}` );
974
+ console.log( '' );
975
+ logInfo( 'Notes:' );
976
+ console.log( ` • Your license key is stored in .env.local (gitignored).` );
977
+ console.log( ` • ${SCOPE} packages are private; each install refreshes a short-lived token via preinstall.` );
978
+
537
979
  }
538
980
 
539
- main().catch((e) => {
540
- logError(e?.stack || e?.message || String(e));
541
- process.exit(1);
542
- });
981
+ main().catch( ( err ) => {
982
+
983
+ if ( err instanceof CliError ) {
984
+
985
+ logError( err.message );
986
+ const detail = ( err.stderr || err.stdout || '' ).trim();
987
+ if ( detail ) {
988
+
989
+ const lines = detail.split( /\r?\n/ );
990
+ for ( const line of lines ) console.error( dim( ` ${line}` ) );
991
+
992
+ }
993
+
994
+ if ( err.suggestion ) logInfo( dim( `Hint: ${err.suggestion}` ) );
995
+ if ( DEBUG && err.cause && err.cause !== err && err.cause?.stack ) {
996
+
997
+ console.error( dim( err.cause.stack ) );
998
+
999
+ }
1000
+
1001
+ process.exit( err.exitCode ?? 1 );
1002
+
1003
+ }
1004
+
1005
+ const fallback = err?.stack || err?.message || String( err );
1006
+ logError( fallback );
1007
+ process.exit( 1 );
1008
+
1009
+ } );