-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathgatsby-node.ts
More file actions
653 lines (578 loc) · 17.8 KB
/
gatsby-node.ts
File metadata and controls
653 lines (578 loc) · 17.8 KB
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
/* eslint-disable import/no-nodejs-modules */
import { detectSnapLocation, getSnapFiles } from '@metamask/snaps-controllers';
import type {
SnapsRegistryDatabase,
VerifiedSnap,
} from '@metamask/snaps-registry';
import { verify } from '@metamask/snaps-registry';
import {
getLocalizedSnapManifest,
getValidatedLocalizationFiles,
type SnapManifest,
} from '@metamask/snaps-utils';
import { assert, getErrorMessage } from '@metamask/utils';
import deepEqual from 'fast-deep-equal';
import { rm } from 'fs/promises';
import type { GatsbyNode, NodeInput } from 'gatsby';
import {
createFileNodeFromBuffer,
createRemoteFileNode,
} from 'gatsby-source-filesystem';
import { GraphQLJSONObject } from 'graphql-type-json';
import type { RequestInfo, RequestInit } from 'node-fetch';
import fetch from 'node-fetch';
// @ts-expect-error - No types available for this package.
import { fetchBuilder, FileSystemCache } from 'node-fetch-cache';
import { ReadableStream } from 'node:stream/web';
import { resolve } from 'path';
import { NormalModuleReplacementPlugin } from 'webpack';
import { getLatestSnapVersion } from './src/utils';
import type { Fields } from './src/utils';
import {
createCategoryImage,
createInstalledImage,
createSnapImage,
} from './src/utils/seo';
type Description = {
description: string;
trusted: boolean;
};
type SnapNode = NodeInput & {
name: string;
description: Description;
author?:
| {
name: string;
website: string;
}
| undefined;
slug: string;
latestVersion: string;
icon?: string | undefined;
permissionsJson: string;
};
// eslint-disable-next-line no-restricted-globals
const IS_STAGING = process.env.GATSBY_STAGING === 'true';
const REGISTRY_URL = 'https://acl.execution.metamask.io/latest/registry.json';
const SIGNATURE_URL = 'https://acl.execution.metamask.io/latest/signature.json';
const PUBLIC_KEY =
'0x025b65308f0f0fb8bc7f7ff87bfc296e0330eee5d3c1d1ee4a048b2fd6a86fa0a6';
const STATS_URL = 'https://data.snaps.metamask.io/';
const HEADERS = {
'User-Agent':
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36',
};
const LEGACY_CATEGORIES: Record<string, string> = {
'transaction insights': 'security',
notifications: 'communication',
};
/**
* Normalize the description to ensure it ends with a period. This also replaces
* "Metamask" with "MetaMask".
*
* @param description - The description to normalize.
* @returns The normalized description.
*/
function normalizeDescription(description: string) {
let normalizedDescription = description.trim();
if (!description.endsWith('.') && !description.endsWith('!')) {
normalizedDescription = `${description}.`;
}
return normalizedDescription.replace(/Metamask/gu, 'MetaMask');
}
/**
* Get the description object for the given snap and manifest. If the registry
* has a description, it will be used. Otherwise, the manifest description will
* be used.
*
* @param snap - The snap data from the registry.
* @param manifest - The snap manifest.
* @returns The description object.
*/
function getDescription(
snap: VerifiedSnap,
manifest: SnapManifest,
): Description {
if (snap.metadata.description) {
return {
description: normalizeDescription(snap.metadata.description),
trusted: true,
};
}
return {
description: normalizeDescription(manifest.description),
trusted: false,
};
}
/**
* Get the registry and custom fetch function to use for fetching tarballs.
*
* @returns The registry and custom fetch function.
*/
async function getRegistry() {
const cachedTarballFetch = fetchBuilder.withCache(
new FileSystemCache({ cacheDirectory: 'node_modules/.cache/npm/tarballs' }),
);
const fetchCachePath = 'node_modules/.cache/npm/fetch';
const cachedFetch = fetchBuilder.withCache(
new FileSystemCache({ cacheDirectory: fetchCachePath }),
);
const rawRegistry = await fetch(REGISTRY_URL, {
headers: HEADERS,
}).then(async (response) => response.text());
const signature = await fetch(SIGNATURE_URL, {
headers: HEADERS,
}).then(async (response) => response.json());
const isRegistryValid = verify({
registry: rawRegistry,
signature,
publicKey: PUBLIC_KEY,
});
assert(isRegistryValid, 'Invalid registry signature.');
const registry: SnapsRegistryDatabase = JSON.parse(rawRegistry);
const cachedRegistry = await cachedFetch(REGISTRY_URL, {
headers: HEADERS,
}).then(async (response: any) => response.json());
// If the registry has changed, we need to clear the fetch cache to ensure
// that we get the latest tarballs.
if (!deepEqual(cachedRegistry, registry)) {
await rm(resolve(fetchCachePath), { recursive: true });
}
/**
* Custom fetch function to use for fetching tarballs. This is used to cache
* tarballs and decrease build times on subsequent builds.
*
* @param url - The URL to fetch.
* @param options - The fetch options.
* @returns The fetch response.
*/
const customFetch = async (url: RequestInfo, options?: RequestInit) => {
if (url.toString().endsWith('.tgz')) {
const response = await cachedTarballFetch(url, options);
// We have to recreate the response since node-fetch doesn't provide a web stream.
return new Response(ReadableStream.from(response.body), {
headers: response.headers,
status: response.status,
statusText: response.statusText,
});
}
return cachedFetch(url, options);
};
return { registry, customFetch };
}
export const sourceNodes: GatsbyNode[`sourceNodes`] = async ({
actions,
createNodeId,
createContentDigest,
getNodesByType,
cache,
getCache,
}) => {
const { createNode } = actions;
const { registry, customFetch } = await getRegistry();
const rawStats = await customFetch(STATS_URL, { headers: HEADERS }).then(
async (response: any) => response.text(),
);
const stats = rawStats
.split('\n')
.slice(0, -1)
.reduce((acc, json) => {
const snap = JSON.parse(json);
acc[snap.snap_id] = parseInt(snap.installs, 10);
return acc;
}, {});
const verifiedSnaps = Object.values(registry.verifiedSnaps)
.filter((snap) => IS_STAGING || Boolean(snap.metadata.category))
.filter((snap) => IS_STAGING || snap.metadata.hidden !== true);
for (const snap of verifiedSnaps) {
const latestVersion = getLatestSnapVersion(snap);
const location = detectSnapLocation(snap.id, {
versionRange: latestVersion as any,
fetch: customFetch as any,
});
try {
const { result: rawManifest } = await location.manifest();
const { iconPath } = rawManifest.source.location.npm;
const icon = iconPath
? `data:image/svg+xml;utf8,${encodeURIComponent(
(await location.fetch(iconPath)).toString(),
)}`
: undefined;
const localizationFiles = await getSnapFiles(
location,
rawManifest.source.locales,
);
const validatedLocalizationFiles = getValidatedLocalizationFiles(
localizationFiles,
).map((file) => file.result);
// For now, just use the English translation
const manifest = getLocalizedSnapManifest(
rawManifest,
'en',
validatedLocalizationFiles,
);
const [snapLocation, slug] = snap.id.split(':') as [string, string];
const summary = normalizeDescription(
snap.metadata.summary ?? manifest.description,
);
const registryJson = await customFetch(
`https://registry.npmjs.org/${slug}`,
).then(async (response: any) => response.json());
const { time } = registryJson;
const lastUpdated = new Date(time[latestVersion]).getTime();
const installs = stats[snap.id] ?? 0;
const nodeId = createNodeId(`snap__${snap.id}`);
const screenshots = snap.metadata.screenshots ?? [];
const screenshotNodes = await Promise.all(
screenshots.map(async (path) =>
createRemoteFileNode({
url: new URL(
path,
'https://raw.githubusercontent.com/MetaMask/snaps-registry/main/src/',
).toString(),
createNode,
createNodeId,
getCache,
cache,
parentNodeId: nodeId,
}),
),
);
const migratedCategory =
snap.metadata.category && LEGACY_CATEGORIES[snap.metadata.category];
const category = migratedCategory ?? snap.metadata.category;
const content = {
...snap.metadata,
category,
snapId: snap.id,
name: manifest.proposedName,
description: getDescription(snap, manifest),
summary,
location: snapLocation,
slug,
latestVersion,
icon,
installs,
lastUpdated,
screenshotFiles: screenshotNodes.map(
(screenshotNode) => screenshotNode.id,
),
// We need to stringify the permissions because Gatsby doesn't support
// JSON objects in GraphQL out of the box. This field is turned into a
// JSON object in the `createResolvers` function. The `permissionsJson`
// field should not be used directly.
permissionsJson: JSON.stringify(manifest.initialPermissions),
};
const node: SnapNode = {
...content,
parent: null,
children: [],
id: nodeId,
internal: {
type: 'Snap',
content: JSON.stringify(content),
contentDigest: createContentDigest(content),
},
};
await createNode(node);
} catch (error) {
// Skip Snaps that have been unpublished
if (
getErrorMessage(error).endsWith('was not found in the NPM registry')
) {
continue;
}
throw error;
}
}
const categories = Object.values(registry.verifiedSnaps).reduce(
(result, snap) => {
if (snap.metadata.category) {
result.add(snap.metadata.category);
}
return result;
},
new Set<string>([
...Object.keys(LEGACY_CATEGORIES),
...Object.values(LEGACY_CATEGORIES),
]),
);
for (const category of categories) {
// For legacy categories, we map to the new name.
const legacyMapping = LEGACY_CATEGORIES[category];
const categoryData = { name: category, legacyMapping };
const node = {
...categoryData,
parent: null,
children: [],
id: createNodeId(`category__${category}`),
internal: {
type: 'Category',
content: JSON.stringify(categoryData),
contentDigest: createContentDigest(categoryData),
},
};
await createNode(node);
}
const snaps = getNodesByType('Snap') as unknown as Fields<
Queries.Snap,
'name' | 'icon' | 'lastUpdated'
>[];
// The SEO banner that is used on the main `/installed` page. This is
// statically queried by the name.
const installedImage = await createInstalledImage(snaps);
await createFileNodeFromBuffer({
buffer: installedImage,
name: 'main-installed-banner',
ext: '.png',
createNode,
createNodeId,
cache,
getCache,
});
// The SEO banner that is used on the main `/latest` page. This is
// statically queried by the name.
const latestImage = await createCategoryImage(
[...snaps].sort((a, b) => b.lastUpdated - a.lastUpdated).slice(0, 6),
6,
);
await createFileNodeFromBuffer({
buffer: latestImage,
name: 'latest-banner',
ext: '.png',
createNode,
createNodeId,
cache,
getCache,
});
};
/**
* Create the schema customization for the Snap and Category nodes. This adds
* the `banner` field to the Snap and Category nodes.
*
* @param args - The Gatsby arguments.
* @param args.actions - The Gatsby actions.
* @see https://www.gatsbyjs.com/docs/reference/graphql-data-layer/schema-customization/#creating-type-definitions
*/
export const createSchemaCustomization: GatsbyNode['createSchemaCustomization'] =
({ actions }) => {
const { createTypes } = actions;
createTypes(`
type Snap implements Node {
banner: File @link(from: "fields.localFile")
onboard: Boolean
privateCode: Boolean
additionalSourceCode: [SnapAdditionalSourceCode]
privacyPolicy: String
termsOfUse: String
screenshots: [File] @link(from: "screenshotFiles")
}
type SnapAdditionalSourceCode {
name: String
url: String
}
type SnapSupport {
keyRecovery: String
}
type Category implements Node {
banner: File @link(from: "fields.localFile")
installedBanner: File @link(from: "fields.installedLocalFile")
}
`);
};
/**
* Create the banner images for the Snap and Category nodes.
*
* @param args - The Gatsby arguments.
* @param args.node - The node that was created.
* @param args.actions - The Gatsby actions.
* @param args.createNodeId - A function to create a node ID.
* @param args.cache - The Gatsby cache.
* @param args.getCache - A function to get the Gatsby cache.
* @param args.getNodesByType - A function to get nodes by type.
*/
export const onCreateNode: GatsbyNode[`onCreateNode`] = async ({
node,
actions,
createNodeId,
cache,
getCache,
getNodesByType,
}) => {
if (node.internal.type === 'Snap') {
const snapNode = node as unknown as Fields<
Queries.Snap,
keyof Queries.Snap
>;
const { createNode, createNodeField } = actions;
const banner = await createSnapImage(
snapNode.name,
snapNode.author?.name,
snapNode.icon,
);
const bannerNode = await createFileNodeFromBuffer({
buffer: banner,
name: 'banner',
ext: '.png',
parentNodeId: snapNode.id,
createNode,
createNodeId,
cache,
getCache,
});
createNodeField({
node,
name: 'localFile',
value: bannerNode.id,
});
}
if (node.internal.type === 'Category') {
const categoryNode = node as unknown as Fields<
Queries.Category,
keyof Queries.Category
>;
const { createNode, createNodeField } = actions;
const name = categoryNode.legacyMapping ?? categoryNode.name;
const snaps = getNodesByType('Snap').filter(
(snap) => snap.category === name,
) as unknown as Fields<Queries.Snap, keyof Queries.Snap>[];
const banner = await createCategoryImage(snaps);
const bannerNode = await createFileNodeFromBuffer({
buffer: banner,
name: 'banner',
ext: '.png',
parentNodeId: categoryNode.id,
createNode,
createNodeId,
cache,
getCache,
});
createNodeField({
node,
name: 'localFile',
value: bannerNode.id,
});
const installedBanner = await createInstalledImage(snaps);
const installedBannerNode = await createFileNodeFromBuffer({
buffer: installedBanner,
name: 'installed-banner',
ext: '.png',
parentNodeId: categoryNode.id,
createNode,
createNodeId,
cache,
getCache,
});
createNodeField({
node,
name: 'installedLocalFile',
value: installedBannerNode.id,
});
}
};
/**
* Create the resolvers for the Snap node. This adds the `permissions` field to
* the Snap node.
*
* @param args - The Gatsby arguments.
* @param args.createResolvers - The Gatsby createResolvers function.
*/
export const createResolvers: GatsbyNode['createResolvers'] = ({
// eslint-disable-next-line @typescript-eslint/no-shadow
createResolvers,
}) => {
createResolvers({
Snap: {
permissions: {
// Using `GraphQLJSONObject` here allows us to query the permissions
// object in GraphQL, without having to specify the fields.
type: GraphQLJSONObject,
resolve: ({ permissionsJson }: SnapNode) => {
return JSON.parse(permissionsJson);
},
},
},
});
};
/**
* Modify the Webpack configuration to handle SVGs using SVGR. This makes it
* possible to import SVGs as React components.
*
* To do this we need to remove SVG from the default file-loader and add a new
* rule for SVGs that uses `@svgr/webpack`.
*
* @param args - The Gatsby arguments.
* @param args.actions - The Gatsby actions.
* @param args.getConfig - A function to get the current Webpack configuration.
*/
export const onCreateWebpackConfig: GatsbyNode['onCreateWebpackConfig'] = ({
actions,
getConfig,
}) => {
const { replaceWebpackConfig } = actions;
const config = getConfig();
const rules = config.module.rules.map((rule: Record<string, unknown>) => {
if (String(rule.test).includes('svg|')) {
return {
...rule,
test: /\.(ico|jpg|jpeg|png|gif|webp|avif)(\?.*)?$/u,
};
}
return rule;
});
replaceWebpackConfig({
...config,
plugins: [
...config.plugins,
new NormalModuleReplacementPlugin(/node:/u, (resource) => {
resource.request = resource.request.replace(/^node:/u, '');
}),
],
resolve: {
...config.resolve,
fallback: {
...config.resolve.fallback,
assert: false,
http: false,
https: false,
crypto: false,
path: false,
stream: false,
url: false,
util: false,
zlib: false,
},
},
module: {
...config.module,
rules: [
...rules,
{
test: /\.svg$/u,
issuer: /\.tsx?$/u,
oneOf: [
{
loader: '@svgr/webpack',
resourceQuery: /^((?!raw).)*$/u,
options: {
svgo: true,
svgoConfig: {
plugins: ['removeTitle', 'removeDesc'],
},
svgProps: {
accessibilityRole: 'image',
},
},
},
{
// Allows for importing SVGs as raw strings using
// `import file from './file.svg?raw';`.
resourceQuery: /raw/u,
type: 'asset/resource',
},
],
},
],
},
});
};