-
Notifications
You must be signed in to change notification settings - Fork 35
/
gatsby-node.js
382 lines (294 loc) · 10.8 KB
/
gatsby-node.js
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
const path = require('path');
const fs = require('fs');
const { Client: GoogleMapsAPIClient } = require('@googlemaps/google-maps-services-js');
const { Translate } = require('@google-cloud/translate').v2;
const { startCase, differenceWith } = require('lodash');
const config = require('./config');
const createCitationPages = require('./page-creators/createCitationPages');
const createWordCountsPages = require('./page-creators/createWordCountsPage');
const createLandingPage = require('./page-creators/createLandingPage');
const createBackupsPage = require('./page-creators/createBackupsPage');
const createTaxonomyPages = require('./page-creators/createTaxonomyPages');
const createDownloadIndexPage = require('./page-creators/createDownloadIndexPage');
const createDuplicatePages = require('./page-creators/createDuplicatePages');
const createTsneVisualizationPage = require('./page-creators/createTsneVisualizationPage');
const createEntitiesPages = require('./page-creators/createEntitiesPages');
const createReportPages = require('./page-creators/createReportPages');
const createBlogPages = require('./page-creators/createBlogPages');
const createDocPages = require('./page-creators/createDocPages');
const createMissingTranslationsPage = require('./page-creators/createMissingTranslationsPage');
const algoliasearch = require('algoliasearch');
const Translator = require('./src/utils/Translator');
const { MongoClient } = require('mongodb');
const { getLanguages } = require('./i18n');
const AlgoliaUpdater = require('./src/utils/AlgoliaUpdater');
const typeDefs = require('./typeDefs');
const googleMapsApiClient = new GoogleMapsAPIClient({});
const LookupIndex = require('./src/utils/LookupIndex');
exports.createPages = async ({ actions, graphql, reporter }) => {
const { createRedirect, createPage } = actions;
const redirects = [
['/about_apps/1-discover', '/about_apps'],
['/about_apps/2-submit', '/about_apps'],
['/about_apps/3-your_app_here', '/about_apps'],
['/apps/quickadd', '/apps/submit'],
['/discover', '/apps/discover'],
['/discover', '/apps/discover'],
['/summaries', '/about_apps'],
['/about/1-governance', '/about'],
['/about/blog', '/blog'],
['/research/4-taxonomies', '/taxonomies'],
['/research', '/research/snapshots'],
['/apps/newsSearch', '/apps/newsdigest'],
['/research/related-work', '/research/4-related-work'],
['/blog/incident-report-2022-january', '/blog/incident-report-2023-january'],
];
redirects.forEach((pair) => {
createRedirect({ fromPath: pair[0], toPath: pair[1], isPermanent: true });
});
for (const pageCreator of [
createMissingTranslationsPage,
createBlogPages,
createCitationPages,
createWordCountsPages,
createLandingPage,
createBackupsPage,
createTaxonomyPages,
createDownloadIndexPage,
createDuplicatePages,
createTsneVisualizationPage,
createEntitiesPages,
createReportPages,
createDocPages,
]) {
if (!(process.env.SKIP_PAGE_CREATOR || '').split(',').includes(pageCreator.name)) {
reporter.info(`Page creation: ${pageCreator.name}`);
await pageCreator(graphql, createPage, { reporter, languages: getLanguages() });
}
}
};
exports.onCreateWebpackConfig = ({ actions }) => {
actions.setWebpackConfig({
resolve: {
modules: [path.resolve(__dirname, 'src'), 'node_modules'],
alias: {
components: path.resolve(__dirname, 'src/components'),
hooks: path.resolve(__dirname, 'src/hooks'),
contexts: path.resolve(__dirname, 'src/contexts'),
mongodb: path.resolve(__dirname, 'src/mongodb'),
pages: path.resolve(__dirname, 'src/pages'),
services: path.resolve(__dirname, 'src/services'),
templates: path.resolve(__dirname, 'src/templates'),
utils: path.resolve(__dirname, 'src/utils'),
plugins: path.resolve(__dirname, 'plugins'),
},
fallback: { crypto: false },
},
});
};
exports.onCreateBabelConfig = ({ actions }) => {
actions.setBabelPlugin({
name: '@babel/plugin-proposal-export-default-from',
});
actions.setBabelPlugin({
name: 'graphql-codegen-babel',
options: {
artifactDirectory: './server/generated/',
gqlTagName: 'gql',
},
});
if (process.env.INSTRUMENT) {
actions.setBabelPlugin({
name: 'babel-plugin-istanbul',
options: {
include: ['src/**/*.js'],
},
});
}
};
exports.onCreateNode = async ({ node, getNode, actions }) => {
const { createNodeField } = actions;
if (node.internal.type === `Mdx`) {
const parent = getNode(node.parent);
let value = parent.relativePath.replace(parent.ext, '');
if (value === 'index') {
value = '';
}
if (parent.sourceInstanceName === 'blog') {
value = `blog/${value}`;
}
createNodeField({
name: `slug`,
node,
value: `/${value}`,
});
createNodeField({
name: 'id',
node,
value: node.id,
});
createNodeField({
name: 'title',
node,
value: node.frontmatter.title || startCase(parent.name),
});
createNodeField({
name: 'previewText',
node,
value: node.frontmatter.previewText || startCase(parent.name),
});
}
if (node.internal.type == 'mongodbAiidprodClassifications') {
let value = { geometry: { location: { lat: 0, lng: 0 } } };
if (config.google.mapsApiKey) {
const locationAttribute = node.attributes.find((a) => a.short_name == 'Location');
try {
if (locationAttribute) {
const locationValue = JSON.parse(locationAttribute.value_json);
if (locationValue && locationValue !== '') {
const {
data: {
results: { 0: geometry },
},
} = await googleMapsApiClient.geocode({
params: { key: config.google.mapsApiKey, address: locationValue },
});
value = geometry;
}
}
} catch (e) {
console.log(e);
console.log('Error fetching geocode data for', locationAttribute?.value_json);
}
}
createNodeField({
name: 'geocode',
node,
value,
});
}
};
exports.createSchemaCustomization = ({ actions }) => {
const { createTypes } = actions;
createTypes(typeDefs);
};
exports.createResolvers = ({ createResolvers }) => {
const resolvers = {
mongodbAiidprodIncidents: {
Alleged_deployer_of_AI_system: {
type: '[String]',
resolve(source) {
return source['Alleged deployer of AI system'];
},
},
Alleged_developer_of_AI_system: {
type: '[String]',
resolve(source) {
return source['Alleged developer of AI system'];
},
},
Alleged_harmed_or_nearly_harmed_parties: {
type: '[String]',
resolve(source) {
return source['Alleged harmed or nearly harmed parties'];
},
},
},
};
createResolvers(resolvers);
};
exports.onPreInit = async ({ reporter }) => {
reporter.log('Creating lookup index...');
const mongoClient = new MongoClient(config.mongodb.translationsConnectionString);
const lookupIndex = new LookupIndex({
client: mongoClient,
filePath: path.join(__dirname, 'netlify', 'functions', 'lookupIndex.json'),
});
await lookupIndex.run();
reporter.log('Lookup index created.');
};
exports.onPreBootstrap = async ({ reporter }) => {
const migrationsActivity = reporter.activityTimer(`Migrations`);
if (!process.env.MONGODB_MIGRATIONS_CONNECTION_STRING) {
console.warn('MONGODB_MIGRATIONS_CONNECTION_STRING is not set, skipping migrations.');
} else if (process.env.CONTEXT !== 'production') {
console.info('Netlify CONTEXT is not production, skipping migrations.');
} else {
migrationsActivity.start();
migrationsActivity.setStatus('Running...');
const migrator = require('./migrator');
await migrator.umzug.runAsCLI(['up']);
migrationsActivity.setStatus('Finished!');
migrationsActivity.end();
}
if (process.env.CONTEXT === 'production') {
const translationsActivity = reporter.activityTimer(`Translations`);
translationsActivity.start();
const configuredLanguages = getLanguages();
const unavailableLanguages = differenceWith(
config.i18n.availableLanguages,
configuredLanguages,
(aLang, cLang) => {
return cLang.code === aLang;
}
);
if (unavailableLanguages.length > 0) {
throw `Language config error. Review your GATSBY_AVAILABLE_LANGUAGES variable. You've included a language that hasn't been configured yet: ${unavailableLanguages
.map((l) => l)
.join(', ')}`;
}
if (
config.mongodb.translationsConnectionString &&
config.i18n.translateApikey &&
config.i18n.availableLanguages &&
config.header.search.algoliaAdminKey &&
config.header.search.algoliaAppId
) {
if (process.env.TRANSLATE_DRY_RUN !== 'false') {
reporter.warn(
'Please set `TRANSLATE_DRY_RUN=false` to disable dry running of translation process.'
);
}
translationsActivity.setStatus('Translating incident reports...');
const translateClient = new Translate({ key: config.i18n.translateApikey });
const mongoClient = new MongoClient(config.mongodb.translationsConnectionString);
const languages = getLanguages();
const translator = new Translator({ mongoClient, translateClient, languages, reporter });
await translator.run();
translationsActivity.setStatus('Updating incidents indexes...');
try {
const algoliaClient = algoliasearch(
config.header.search.algoliaAppId,
config.header.search.algoliaAdminKey
);
const algoliaUpdater = new AlgoliaUpdater({
languages,
mongoClient,
algoliaClient,
reporter,
});
await algoliaUpdater.run();
} catch (e) {
reporter.panicOnBuild('Error updating Algolia index:', e);
}
} else {
throw `Missing environment variable, can't run translation process.`;
}
translationsActivity.end();
} else {
reporter.warn('Netlify CONTEXT is not production, skipping translations.');
}
};
exports.onPreBuild = function ({ reporter }) {
if (!config.google.mapsApiKey) {
reporter.warn('Missing environment variable GOOGLE_MAPS_API_KEY.');
}
};
exports.onPostBuild = ({ reporter }) => {
reporter.info('Replacing Env variables on static file...');
const filePath = `${process.cwd()}/public/rollbar.js`;
reporter.info(`Replacing "GATSBY_ROLLBAR_TOKEN" variable on static "${filePath}" file...`);
const fileContent = fs.readFileSync(filePath, 'utf8');
const newFileContent = fileContent.replace(/GATSBY_ROLLBAR_TOKEN/g, config.rollbar.token);
fs.writeFileSync(filePath, newFileContent);
};