1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
|
import boxen from 'boxen';
import { diffWords } from 'diff';
import { execa } from 'execa';
import { bold, cyan, dim, green, magenta, red, yellow } from 'kleur/colors';
import fsMod, { existsSync, promises as fs } from 'node:fs';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import ora from 'ora';
import preferredPM from 'preferred-pm';
import prompts from 'prompts';
import type yargs from 'yargs-parser';
import { loadTSConfig, resolveConfigPath, resolveRoot } from '../../core/config/index.js';
import {
defaultTSConfig,
presets,
updateTSConfigForFramework,
type frameworkWithTSSettings,
} from '../../core/config/tsconfig.js';
import { debug, info, type LogOptions } from '../../core/logger/core.js';
import * as msg from '../../core/messages.js';
import { printHelp } from '../../core/messages.js';
import { appendForwardSlash } from '../../core/path.js';
import { apply as applyPolyfill } from '../../core/polyfill.js';
import { parseNpmName } from '../../core/util.js';
import { eventCliSession, telemetry } from '../../events/index.js';
import { createLoggingFromFlags } from '../flags.js';
import { generate, parse, t, visit } from './babel.js';
import { ensureImport } from './imports.js';
import { wrapDefaultExport } from './wrapper.js';
interface AddOptions {
flags: yargs.Arguments;
}
interface IntegrationInfo {
id: string;
packageName: string;
dependencies: [name: string, version: string][];
type: 'integration' | 'adapter';
}
const ALIASES = new Map([
['solid', 'solid-js'],
['tailwindcss', 'tailwind'],
]);
const ASTRO_CONFIG_STUB = `import { defineConfig } from 'astro/config';\n\nexport default defineConfig({});`;
const TAILWIND_CONFIG_STUB = `/** @type {import('tailwindcss').Config} */
module.exports = {
content: ['./src/**/*.{astro,html,js,jsx,md,mdx,svelte,ts,tsx,vue}'],
theme: {
extend: {},
},
plugins: [],
}\n`;
const SVELTE_CONFIG_STUB = `\
import { vitePreprocess } from '@astrojs/svelte';
export default {
preprocess: vitePreprocess(),
};
`;
const LIT_NPMRC_STUB = `\
# Lit libraries are required to be hoisted due to dependency issues.
public-hoist-pattern[]=*lit*
`;
const OFFICIAL_ADAPTER_TO_IMPORT_MAP: Record<string, string> = {
netlify: '@astrojs/netlify/functions',
vercel: '@astrojs/vercel/serverless',
cloudflare: '@astrojs/cloudflare',
node: '@astrojs/node',
deno: '@astrojs/deno',
};
// Users might lack access to the global npm registry, this function
// checks the user's project type and will return the proper npm registry
//
// A copy of this function also exists in the create-astro package
async function getRegistry(): Promise<string> {
const packageManager = (await preferredPM(process.cwd()))?.name || 'npm';
try {
const { stdout } = await execa(packageManager, ['config', 'get', 'registry']);
return stdout?.trim()?.replace(/\/$/, '') || 'https://registry.npmjs.org';
} catch (e) {
return 'https://registry.npmjs.org';
}
}
export async function add(names: string[], { flags }: AddOptions) {
telemetry.record(eventCliSession('add'));
applyPolyfill();
if (flags.help || names.length === 0) {
printHelp({
commandName: 'astro add',
usage: '[...integrations] [...adapters]',
tables: {
Flags: [
['--yes', 'Accept all prompts.'],
['--help', 'Show this help message.'],
],
'UI Frameworks': [
['react', 'astro add react'],
['preact', 'astro add preact'],
['vue', 'astro add vue'],
['svelte', 'astro add svelte'],
['solid-js', 'astro add solid-js'],
['lit', 'astro add lit'],
['alpinejs', 'astro add alpinejs'],
],
'SSR Adapters': [
['netlify', 'astro add netlify'],
['vercel', 'astro add vercel'],
['deno', 'astro add deno'],
['cloudflare', 'astro add cloudflare'],
['node', 'astro add node'],
],
Others: [
['tailwind', 'astro add tailwind'],
['image', 'astro add image'],
['mdx', 'astro add mdx'],
['partytown', 'astro add partytown'],
['sitemap', 'astro add sitemap'],
['prefetch', 'astro add prefetch'],
],
},
description: `For more integrations, check out: ${cyan('https://astro.build/integrations')}`,
});
return;
}
// Some packages might have a common alias! We normalize those here.
const cwd = flags.root;
const logging = createLoggingFromFlags(flags);
const integrationNames = names.map((name) => (ALIASES.has(name) ? ALIASES.get(name)! : name));
const integrations = await validateIntegrations(integrationNames);
let installResult = await tryToInstallIntegrations({ integrations, cwd, flags, logging });
const rootPath = resolveRoot(cwd);
const root = pathToFileURL(rootPath);
// Append forward slash to compute relative paths
root.href = appendForwardSlash(root.href);
switch (installResult) {
case UpdateResult.updated: {
if (integrations.find((integration) => integration.id === 'tailwind')) {
await setupIntegrationConfig({
root,
logging,
flags,
integrationName: 'Tailwind',
possibleConfigFiles: [
'./tailwind.config.cjs',
'./tailwind.config.mjs',
'./tailwind.config.js',
],
defaultConfigFile: './tailwind.config.cjs',
defaultConfigContent: TAILWIND_CONFIG_STUB,
});
}
if (integrations.find((integration) => integration.id === 'svelte')) {
await setupIntegrationConfig({
root,
logging,
flags,
integrationName: 'Svelte',
possibleConfigFiles: ['./svelte.config.js', './svelte.config.cjs', './svelte.config.mjs'],
defaultConfigFile: './svelte.config.js',
defaultConfigContent: SVELTE_CONFIG_STUB,
});
}
// Some lit dependencies needs to be hoisted, so for strict package managers like pnpm,
// we add an .npmrc to hoist them
if (
integrations.find((integration) => integration.id === 'lit') &&
(await preferredPM(fileURLToPath(root)))?.name === 'pnpm'
) {
await setupIntegrationConfig({
root,
logging,
flags,
integrationName: 'Lit',
possibleConfigFiles: ['./.npmrc'],
defaultConfigFile: './.npmrc',
defaultConfigContent: LIT_NPMRC_STUB,
});
}
break;
}
case UpdateResult.cancelled: {
info(
logging,
null,
msg.cancelled(
`Dependencies ${bold('NOT')} installed.`,
`Be sure to install them manually before continuing!`
)
);
break;
}
case UpdateResult.failure: {
throw createPrettyError(new Error(`Unable to install dependencies`));
}
}
const rawConfigPath = await resolveConfigPath({
root: rootPath,
configFile: flags.config,
fs: fsMod,
});
let configURL = rawConfigPath ? pathToFileURL(rawConfigPath) : undefined;
if (configURL) {
debug('add', `Found config at ${configURL}`);
} else {
info(logging, 'add', `Unable to locate a config file, generating one for you.`);
configURL = new URL('./astro.config.mjs', root);
await fs.writeFile(fileURLToPath(configURL), ASTRO_CONFIG_STUB, { encoding: 'utf-8' });
}
let ast: t.File | null = null;
try {
ast = await parseAstroConfig(configURL);
debug('add', 'Parsed astro config');
const defineConfig = t.identifier('defineConfig');
ensureImport(
ast,
t.importDeclaration(
[t.importSpecifier(defineConfig, defineConfig)],
t.stringLiteral('astro/config')
)
);
wrapDefaultExport(ast, defineConfig);
debug('add', 'Astro config ensured `defineConfig`');
for (const integration of integrations) {
if (isAdapter(integration)) {
const officialExportName = OFFICIAL_ADAPTER_TO_IMPORT_MAP[integration.id];
if (officialExportName) {
await setAdapter(ast, integration, officialExportName);
} else {
info(
logging,
null,
`\n ${magenta(
`Check our deployment docs for ${bold(
integration.packageName
)} to update your "adapter" config.`
)}`
);
}
} else {
await addIntegration(ast, integration);
}
debug('add', `Astro config added integration ${integration.id}`);
}
} catch (err) {
debug('add', 'Error parsing/modifying astro config: ', err);
throw createPrettyError(err as Error);
}
let configResult: UpdateResult | undefined;
if (ast) {
try {
configResult = await updateAstroConfig({
configURL,
ast,
flags,
logging,
logAdapterInstructions: integrations.some(isAdapter),
});
} catch (err) {
debug('add', 'Error updating astro config', err);
throw createPrettyError(err as Error);
}
}
switch (configResult) {
case UpdateResult.cancelled: {
info(logging, null, msg.cancelled(`Your configuration has ${bold('NOT')} been updated.`));
break;
}
case UpdateResult.none: {
const pkgURL = new URL('./package.json', configURL);
if (existsSync(fileURLToPath(pkgURL))) {
const { dependencies = {}, devDependencies = {} } = await fs
.readFile(fileURLToPath(pkgURL))
.then((res) => JSON.parse(res.toString()));
const deps = Object.keys(Object.assign(dependencies, devDependencies));
const missingDeps = integrations.filter(
(integration) => !deps.includes(integration.packageName)
);
if (missingDeps.length === 0) {
info(logging, null, msg.success(`Configuration up-to-date.`));
break;
}
}
info(logging, null, msg.success(`Configuration up-to-date.`));
break;
}
default: {
const list = integrations.map((integration) => ` - ${integration.packageName}`).join('\n');
info(
logging,
null,
msg.success(
`Added the following integration${
integrations.length === 1 ? '' : 's'
} to your project:\n${list}`
)
);
}
}
const updateTSConfigResult = await updateTSConfig(cwd, logging, integrations, flags);
switch (updateTSConfigResult) {
case UpdateResult.none: {
break;
}
case UpdateResult.cancelled: {
info(
logging,
null,
msg.cancelled(`Your TypeScript configuration has ${bold('NOT')} been updated.`)
);
break;
}
case UpdateResult.failure: {
throw new Error(
`Unknown error parsing tsconfig.json or jsconfig.json. Could not update TypeScript settings.`
);
}
default:
info(logging, null, msg.success(`Successfully updated TypeScript settings`));
}
}
function isAdapter(
integration: IntegrationInfo
): integration is IntegrationInfo & { type: 'adapter' } {
return integration.type === 'adapter';
}
async function parseAstroConfig(configURL: URL): Promise<t.File> {
const source = await fs.readFile(fileURLToPath(configURL), { encoding: 'utf-8' });
const result = parse(source);
if (!result) throw new Error('Unknown error parsing astro config');
if (result.errors.length > 0)
throw new Error('Error parsing astro config: ' + JSON.stringify(result.errors));
return result;
}
// Convert an arbitrary NPM package name into a JS identifier
// Some examples:
// - @astrojs/image => image
// - @astrojs/markdown-component => markdownComponent
// - astro-cast => cast
// - markdown-astro => markdown
// - some-package => somePackage
// - example.com => exampleCom
// - under_score => underScore
// - 123numeric => numeric
// - @npm/thingy => npmThingy
// - @jane/foo.js => janeFoo
// - @tokencss/astro => tokencss
const toIdent = (name: string) => {
const ident = name
.trim()
// Remove astro or (astrojs) prefix and suffix
.replace(/[-_\.\/]?astro(?:js)?[-_\.]?/g, '')
// drop .js suffix
.replace(/\.js/, '')
// convert to camel case
.replace(/(?:[\.\-\_\/]+)([a-zA-Z])/g, (_, w) => w.toUpperCase())
// drop invalid first characters
.replace(/^[^a-zA-Z$_]+/, '');
return `${ident[0].toLowerCase()}${ident.slice(1)}`;
};
function createPrettyError(err: Error) {
err.message = `Astro could not update your astro.config.js file safely.
Reason: ${err.message}
You will need to add these integration(s) manually.
Documentation: https://docs.astro.build/en/guides/integrations-guide/`;
return err;
}
async function addIntegration(ast: t.File, integration: IntegrationInfo) {
const integrationId = t.identifier(toIdent(integration.id));
ensureImport(
ast,
t.importDeclaration(
[t.importDefaultSpecifier(integrationId)],
t.stringLiteral(integration.packageName)
)
);
visit(ast, {
// eslint-disable-next-line @typescript-eslint/no-shadow
ExportDefaultDeclaration(path) {
if (!t.isCallExpression(path.node.declaration)) return;
const configObject = path.node.declaration.arguments[0];
if (!t.isObjectExpression(configObject)) return;
let integrationsProp = configObject.properties.find((prop) => {
if (prop.type !== 'ObjectProperty') return false;
if (prop.key.type === 'Identifier') {
if (prop.key.name === 'integrations') return true;
}
if (prop.key.type === 'StringLiteral') {
if (prop.key.value === 'integrations') return true;
}
return false;
}) as t.ObjectProperty | undefined;
const integrationCall = t.callExpression(integrationId, []);
if (!integrationsProp) {
configObject.properties.push(
t.objectProperty(t.identifier('integrations'), t.arrayExpression([integrationCall]))
);
return;
}
if (integrationsProp.value.type !== 'ArrayExpression')
throw new Error('Unable to parse integrations');
const existingIntegrationCall = integrationsProp.value.elements.find(
(expr) =>
t.isCallExpression(expr) &&
t.isIdentifier(expr.callee) &&
expr.callee.name === integrationId.name
);
if (existingIntegrationCall) return;
integrationsProp.value.elements.push(integrationCall);
},
});
}
async function setAdapter(ast: t.File, adapter: IntegrationInfo, exportName: string) {
const adapterId = t.identifier(toIdent(adapter.id));
ensureImport(
ast,
t.importDeclaration([t.importDefaultSpecifier(adapterId)], t.stringLiteral(exportName))
);
visit(ast, {
// eslint-disable-next-line @typescript-eslint/no-shadow
ExportDefaultDeclaration(path) {
if (!t.isCallExpression(path.node.declaration)) return;
const configObject = path.node.declaration.arguments[0];
if (!t.isObjectExpression(configObject)) return;
let outputProp = configObject.properties.find((prop) => {
if (prop.type !== 'ObjectProperty') return false;
if (prop.key.type === 'Identifier') {
if (prop.key.name === 'output') return true;
}
if (prop.key.type === 'StringLiteral') {
if (prop.key.value === 'output') return true;
}
return false;
}) as t.ObjectProperty | undefined;
if (!outputProp) {
configObject.properties.push(
t.objectProperty(t.identifier('output'), t.stringLiteral('server'))
);
}
let adapterProp = configObject.properties.find((prop) => {
if (prop.type !== 'ObjectProperty') return false;
if (prop.key.type === 'Identifier') {
if (prop.key.name === 'adapter') return true;
}
if (prop.key.type === 'StringLiteral') {
if (prop.key.value === 'adapter') return true;
}
return false;
}) as t.ObjectProperty | undefined;
let adapterCall;
switch (adapter.id) {
// the node adapter requires a mode
case 'node': {
adapterCall = t.callExpression(adapterId, [
t.objectExpression([
t.objectProperty(t.identifier('mode'), t.stringLiteral('standalone')),
]),
]);
break;
}
default: {
adapterCall = t.callExpression(adapterId, []);
}
}
if (!adapterProp) {
configObject.properties.push(t.objectProperty(t.identifier('adapter'), adapterCall));
return;
}
adapterProp.value = adapterCall;
},
});
}
const enum UpdateResult {
none,
updated,
cancelled,
failure,
}
async function updateAstroConfig({
configURL,
ast,
flags,
logging,
logAdapterInstructions,
}: {
configURL: URL;
ast: t.File;
flags: yargs.Arguments;
logging: LogOptions;
logAdapterInstructions: boolean;
}): Promise<UpdateResult> {
const input = await fs.readFile(fileURLToPath(configURL), { encoding: 'utf-8' });
let output = await generate(ast);
const comment = '// https://astro.build/config';
const defaultExport = 'export default defineConfig';
output = output.replace(`\n${comment}`, '');
output = output.replace(`${defaultExport}`, `\n${comment}\n${defaultExport}`);
if (input === output) {
return UpdateResult.none;
}
const diff = getDiffContent(input, output);
if (!diff) {
return UpdateResult.none;
}
const message = `\n${boxen(diff, {
margin: 0.5,
padding: 0.5,
borderStyle: 'round',
title: configURL.pathname.split('/').pop(),
})}\n`;
info(
logging,
null,
`\n ${magenta('Astro will make the following changes to your config file:')}\n${message}`
);
if (logAdapterInstructions) {
info(
logging,
null,
magenta(
` For complete deployment options, visit\n ${bold(
'https://docs.astro.build/en/guides/deploy/'
)}\n`
)
);
}
if (await askToContinue({ flags })) {
await fs.writeFile(fileURLToPath(configURL), output, { encoding: 'utf-8' });
debug('add', `Updated astro config`);
return UpdateResult.updated;
} else {
return UpdateResult.cancelled;
}
}
interface InstallCommand {
pm: string;
command: string;
flags: string[];
dependencies: string[];
}
async function getInstallIntegrationsCommand({
integrations,
cwd = process.cwd(),
}: {
integrations: IntegrationInfo[];
cwd?: string;
}): Promise<InstallCommand | null> {
const pm = await preferredPM(cwd);
debug('add', `package manager: ${JSON.stringify(pm)}`);
if (!pm) return null;
let dependencies = integrations
.map<[string, string | null][]>((i) => [[i.packageName, null], ...i.dependencies])
.flat(1)
.filter((dep, i, arr) => arr.findIndex((d) => d[0] === dep[0]) === i)
.map(([name, version]) =>
version === null ? name : `${name}@${version.split(/\s*\|\|\s*/).pop()}`
)
.sort();
switch (pm.name) {
case 'npm':
return { pm: 'npm', command: 'install', flags: [], dependencies };
case 'yarn':
return { pm: 'yarn', command: 'add', flags: [], dependencies };
case 'pnpm':
return { pm: 'pnpm', command: 'add', flags: [], dependencies };
default:
return null;
}
}
// Allow forwarding of standard `npm install` flags
// See https://docs.npmjs.com/cli/v8/commands/npm-install#description
const INHERITED_FLAGS = new Set<string>([
'P',
'save-prod',
'D',
'save-dev',
'E',
'save-exact',
'no-save',
]);
async function tryToInstallIntegrations({
integrations,
cwd,
flags,
logging,
}: {
integrations: IntegrationInfo[];
cwd?: string;
flags: yargs.Arguments;
logging: LogOptions;
}): Promise<UpdateResult> {
const installCommand = await getInstallIntegrationsCommand({ integrations, cwd });
const inheritedFlags = Object.entries(flags)
.map(([flag]) => {
if (flag == '_') return;
if (INHERITED_FLAGS.has(flag)) {
if (flag.length === 1) return `-${flag}`;
return `--${flag}`;
}
})
.filter(Boolean)
.flat() as string[];
if (installCommand === null) {
return UpdateResult.none;
} else {
const coloredOutput = `${bold(installCommand.pm)} ${installCommand.command}${[
'',
...installCommand.flags,
...inheritedFlags,
].join(' ')} ${cyan(installCommand.dependencies.join(' '))}`;
const message = `\n${boxen(coloredOutput, {
margin: 0.5,
padding: 0.5,
borderStyle: 'round',
})}\n`;
info(
logging,
null,
`\n ${magenta('Astro will run the following command:')}\n ${dim(
'If you skip this step, you can always run it yourself later'
)}\n${message}`
);
if (await askToContinue({ flags })) {
const spinner = ora('Installing dependencies...').start();
try {
await execa(
installCommand.pm,
[
installCommand.command,
...installCommand.flags,
...inheritedFlags,
...installCommand.dependencies,
],
{ cwd }
);
spinner.succeed();
return UpdateResult.updated;
} catch (err) {
spinner.fail();
debug('add', 'Error installing dependencies', err);
// eslint-disable-next-line no-console
console.error('\n', (err as any).stdout, '\n');
return UpdateResult.failure;
}
} else {
return UpdateResult.cancelled;
}
}
}
async function fetchPackageJson(
scope: string | undefined,
name: string,
tag: string
): Promise<object | Error> {
const packageName = `${scope ? `${scope}/` : ''}${name}`;
const registry = await getRegistry();
const res = await fetch(`${registry}/${packageName}/${tag}`);
if (res.status === 404) {
return new Error();
} else {
return await res.json();
}
}
export async function validateIntegrations(integrations: string[]): Promise<IntegrationInfo[]> {
const spinner = ora('Resolving packages...').start();
try {
const integrationEntries = await Promise.all(
integrations.map(async (integration): Promise<IntegrationInfo> => {
const parsed = parseIntegrationName(integration);
if (!parsed) {
throw new Error(`${bold(integration)} does not appear to be a valid package name!`);
}
let { scope, name, tag } = parsed;
let pkgJson;
let pkgType: 'first-party' | 'third-party';
if (scope && scope !== '@astrojs') {
pkgType = 'third-party';
} else {
const firstPartyPkgCheck = await fetchPackageJson('@astrojs', name, tag);
if (firstPartyPkgCheck instanceof Error) {
spinner.warn(
yellow(`${bold(integration)} is not an official Astro package. Use at your own risk!`)
);
const response = await prompts({
type: 'confirm',
name: 'askToContinue',
message: 'Continue?',
initial: true,
});
if (!response.askToContinue) {
throw new Error(
`No problem! Find our official integrations at ${cyan(
'https://astro.build/integrations'
)}`
);
}
spinner.start('Resolving with third party packages...');
pkgType = 'third-party';
} else {
pkgType = 'first-party';
pkgJson = firstPartyPkgCheck as any;
}
}
if (pkgType === 'third-party') {
const thirdPartyPkgCheck = await fetchPackageJson(scope, name, tag);
if (thirdPartyPkgCheck instanceof Error) {
throw new Error(`Unable to fetch ${bold(integration)}. Does the package exist?`);
} else {
pkgJson = thirdPartyPkgCheck as any;
}
}
const resolvedScope = pkgType === 'first-party' ? '@astrojs' : scope;
const packageName = `${resolvedScope ? `${resolvedScope}/` : ''}${name}`;
let dependencies: IntegrationInfo['dependencies'] = [
[pkgJson['name'], `^${pkgJson['version']}`],
];
if (pkgJson['peerDependencies']) {
const meta = pkgJson['peerDependenciesMeta'] || {};
for (const peer in pkgJson['peerDependencies']) {
const optional = meta[peer]?.optional || false;
const isAstro = peer === 'astro';
if (!optional && !isAstro) {
dependencies.push([peer, pkgJson['peerDependencies'][peer]]);
}
}
}
let integrationType: IntegrationInfo['type'];
const keywords = Array.isArray(pkgJson['keywords']) ? pkgJson['keywords'] : [];
if (keywords.includes('astro-integration')) {
integrationType = 'integration';
} else if (keywords.includes('astro-adapter')) {
integrationType = 'adapter';
} else {
throw new Error(
`${bold(
packageName
)} doesn't appear to be an integration or an adapter. Find our official integrations at ${cyan(
'https://astro.build/integrations'
)}`
);
}
return { id: integration, packageName, dependencies, type: integrationType };
})
);
spinner.succeed();
return integrationEntries;
} catch (e) {
if (e instanceof Error) {
spinner.fail(e.message);
process.exit(1);
} else {
throw e;
}
}
}
async function updateTSConfig(
cwd = process.cwd(),
logging: LogOptions,
integrationsInfo: IntegrationInfo[],
flags: yargs.Arguments
): Promise<UpdateResult> {
const integrations = integrationsInfo.map(
(integration) => integration.id as frameworkWithTSSettings
);
const firstIntegrationWithTSSettings = integrations.find((integration) =>
presets.has(integration)
);
if (!firstIntegrationWithTSSettings) {
return UpdateResult.none;
}
const inputConfig = loadTSConfig(cwd, false);
const configFileName = inputConfig.exists ? inputConfig.path.split('/').pop() : 'tsconfig.json';
if (inputConfig.reason === 'invalid-config') {
return UpdateResult.failure;
}
if (inputConfig.reason === 'not-found') {
debug('add', "Couldn't find tsconfig.json or jsconfig.json, generating one");
}
const outputConfig = updateTSConfigForFramework(
inputConfig.exists ? inputConfig.config : defaultTSConfig,
firstIntegrationWithTSSettings
);
const input = inputConfig.exists ? JSON.stringify(inputConfig.config, null, 2) : '';
const output = JSON.stringify(outputConfig, null, 2);
const diff = getDiffContent(input, output);
if (!diff) {
return UpdateResult.none;
}
const message = `\n${boxen(diff, {
margin: 0.5,
padding: 0.5,
borderStyle: 'round',
title: configFileName,
})}\n`;
info(
logging,
null,
`\n ${magenta(`Astro will make the following changes to your ${configFileName}:`)}\n${message}`
);
// Every major framework, apart from Vue and Svelte requires different `jsxImportSource`, as such it's impossible to config
// all of them in the same `tsconfig.json`. However, Vue only need `"jsx": "preserve"` for template intellisense which
// can be compatible with some frameworks (ex: Solid)
const conflictingIntegrations = [...Object.keys(presets).filter((config) => config !== 'vue')];
const hasConflictingIntegrations =
integrations.filter((integration) => presets.has(integration)).length > 1 &&
integrations.filter((integration) => conflictingIntegrations.includes(integration)).length > 0;
if (hasConflictingIntegrations) {
info(
logging,
null,
red(
` ${bold(
'Caution:'
)} Selected UI frameworks require conflicting tsconfig.json settings, as such only settings for ${bold(
firstIntegrationWithTSSettings
)} were used.\n More information: https://docs.astro.build/en/guides/typescript/#errors-typing-multiple-jsx-frameworks-at-the-same-time\n`
)
);
}
if (await askToContinue({ flags })) {
await fs.writeFile(inputConfig?.path ?? path.join(cwd, 'tsconfig.json'), output, {
encoding: 'utf-8',
});
debug('add', `Updated ${configFileName} file`);
return UpdateResult.updated;
} else {
return UpdateResult.cancelled;
}
}
function parseIntegrationName(spec: string) {
const result = parseNpmName(spec);
if (!result) return;
let { scope, name } = result;
let tag = 'latest';
if (scope) {
name = name.replace(scope + '/', '');
}
if (name.includes('@')) {
const tagged = name.split('@');
name = tagged[0];
tag = tagged[1];
}
return { scope, name, tag };
}
async function askToContinue({ flags }: { flags: yargs.Arguments }): Promise<boolean> {
if (flags.yes || flags.y) return true;
const response = await prompts({
type: 'confirm',
name: 'askToContinue',
message: 'Continue?',
initial: true,
});
return Boolean(response.askToContinue);
}
function getDiffContent(input: string, output: string): string | null {
let changes = [];
for (const change of diffWords(input, output)) {
let lines = change.value.trim().split('\n').slice(0, change.count);
if (lines.length === 0) continue;
if (change.added) {
if (!change.value.trim()) continue;
changes.push(change.value);
}
}
if (changes.length === 0) {
return null;
}
let diffed = output;
for (let newContent of changes) {
const coloredOutput = newContent
.split('\n')
.map((ln) => (ln ? green(ln) : ''))
.join('\n');
diffed = diffed.replace(newContent, coloredOutput);
}
return diffed;
}
async function setupIntegrationConfig(opts: {
root: URL;
logging: LogOptions;
flags: yargs.Arguments;
integrationName: string;
possibleConfigFiles: string[];
defaultConfigFile: string;
defaultConfigContent: string;
}) {
const possibleConfigFiles = opts.possibleConfigFiles.map((p) =>
fileURLToPath(new URL(p, opts.root))
);
let alreadyConfigured = false;
for (const possibleConfigPath of possibleConfigFiles) {
if (existsSync(possibleConfigPath)) {
alreadyConfigured = true;
break;
}
}
if (!alreadyConfigured) {
info(
opts.logging,
null,
`\n ${magenta(`Astro will generate a minimal ${bold(opts.defaultConfigFile)} file.`)}\n`
);
if (await askToContinue({ flags: opts.flags })) {
await fs.writeFile(
fileURLToPath(new URL(opts.defaultConfigFile, opts.root)),
opts.defaultConfigContent,
{
encoding: 'utf-8',
}
);
debug('add', `Generated default ${opts.defaultConfigFile} file`);
}
} else {
debug('add', `Using existing ${opts.integrationName} configuration`);
}
}
|