Repository navigation
Expand file tree
/
Copy pathstructured-data.mjs
More file actions
286 lines (277 loc) · 15.9 KB
/
Copy pathstructured-data.mjs
File metadata and controls
286 lines (277 loc) · 15.9 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
import {alumniInDirectoryOrder} from './alumni.mjs';
import {fields} from './fields.mjs';
import {clipUrl, videoId} from './media.mjs';
import {publicationAnchor, publicationSchema} from './publication-schema.mjs';
const canonicalOrigin = 'https://rairlab.org';
const memberPage = slug => '/members/' + slug + '/';
const ref = id => ({'@id': id});
const organization = (name, url) => ({'@type': 'Organization', name, url});
const nonempty = values => values?.length ? values : undefined;
const unique = values => [...new Set(values.filter(Boolean))];
const bibliographyUrl = 'https://github.com/RAIRLab/Publications/tree/1a3f8e6befecc3aeebdad2a509d36ba3724668b6';
const aliases = {
'James T. Oswald': 'James Oswald',
'Michael Giancola': 'Mike Giancola',
'Naveen Sundar G.': 'Naveen Sundar Govindarajulu',
'Thomas M. Ferguson': 'Thomas Ferguson',
'Thomas Macaulay Ferguson': 'Thomas Ferguson'
};
const degreeNames = {PhD: 'Doctor of Philosophy', MS: 'Master of Science', BS: 'Bachelor of Science'};
const topicUrl = (topic, interestArticles) => 'https://en.wikipedia.org/wiki/' +
encodeURIComponent((interestArticles[topic] ?? topic).replaceAll(' ', '_'));
export {topicUrl};
export const orcidUrl = id => 'https://orcid.org/' + id;
// Escape markup delimiters before inserting JSON into a raw-text script element.
export const jsonLd = nodes => '<script type="application/ld+json">\n' +
JSON.stringify({'@context': 'https://schema.org', '@graph': nodes}).replaceAll('<', '\\u003c') +
'\n</script>';
function list(id, name, entries, url) {
return {
'@type': 'ItemList', '@id': id, name, url, numberOfItems: entries.length,
itemListElement: entries.map(({node, url}, i) => ({
'@type': 'ListItem', position: i + 1, url, item: ref(node['@id'])
}))
};
}
function byUniqueKey(items, key) {
const result = new Map();
for (const item of items) {
const value = key(item);
if (!value || result.has(value)) throw new Error('Missing or duplicate structured data key: ' + value);
result.set(value, item);
}
return result;
}
export function buildStructuredData({full, description, people, alumni, publications, catalog, sponsorLogos, stories, mediaSources,
sources, interestArticles}) {
const url = route => new URL(route, canonicalOrigin).href;
const orgId = url('/#lab'), siteId = url('/#website');
const rpi = {'@type': 'CollegeOrUniversity', '@id': 'https://www.rpi.edu/#organization',
name: 'Rensselaer Polytechnic Institute', alternateName: 'RPI', url: 'https://www.rpi.edu/'};
const labRef = ref(orgId);
const rpiRef = ref(rpi['@id']);
const roster = byUniqueKey(people, p => p.name);
const alumniGroups = new Map();
for (const a of alumniInDirectoryOrder(alumni)) {
if (!alumniGroups.has(a.name)) alumniGroups.set(a.name, []);
alumniGroups.get(a.name).push(a);
}
const alumniId = a => url('/members/#' + a.slug);
const profileId = p => url(memberPage(p.slug) + '#person');
const current = people.filter(p => p.group !== 'associated-faculty');
const faculty = people.filter(p => p.group === 'associated-faculty');
const topics = names => names.map(name => ({'@type': 'DefinedTerm', name, url: topicUrl(name, interestArticles)}));
const cleanPerson = name => aliases[name] ?? name;
function person(citedName) {
const name = cleanPerson(citedName);
const p = roster.get(name);
const a = alumniGroups.get(name)?.[0];
const id = p ? profileId(p) : a ? alumniId(a) : undefined;
return {'@type': 'Person', '@id': id, name,
url: p ? url(memberPage(p.slug)) : a ? id : undefined};
}
const director = person('Selmer Bringsjord');
const mediaContact = {'@type': 'ContactPoint', contactType: 'Media inquiries and interview arrangements',
email: 'newsmedia@rpi.edu', url: 'https://news.rpi.edu/media-relations'};
const lab = {
'@type': 'Organization', '@id': orgId, url: url('/'), name: full, alternateName: ['RAIR Lab', 'RAIR Laboratory'],
description, parentOrganization: rpiRef, location: {'@type': 'Place', address: {
'@type': 'PostalAddress', addressLocality: 'Troy', addressRegion: 'New York', addressCountry: 'US'
}},
logo: {'@type': 'ImageObject', contentUrl: url('/brand/rair-avatar.png'), width: 460, height: 460},
sameAs: ['https://github.com/RAIRLab', 'https://www.youtube.com/@rairlab7306'],
knowsAbout: topics(['Artificial intelligence', 'Cognitive science', 'Mathematical logic', 'Automated reasoning']),
member: {'@type': 'OrganizationRole', roleName: 'Director', member: director},
contactPoint: mediaContact
};
const site = {'@type': 'WebSite', '@id': siteId, url: url('/'), name: full, alternateName: 'RAIR Lab',
publisher: labRef, inLanguage: 'en'};
const profile = p => ({
...person(p.name), mainEntityOfPage: url(memberPage(p.slug) + '#webpage'),
alternateName: nonempty(Object.keys(aliases).filter(n => aliases[n] === p.name)),
jobTitle: p.role, memberOf: p.group === 'associated-faculty' ? undefined : labRef,
affiliation: p.group === 'associated-faculty' ? [labRef, rpiRef] : rpiRef,
worksFor: p.group === 'associated-faculty' ? rpiRef : undefined,
knowsAbout: topics(p.interests),
email: p.contact,
sameAs: nonempty(unique([p.url, p.profileSource, p.orcid && orcidUrl(p.orcid)])),
identifier: p.orcid ? {'@type': 'PropertyValue', propertyID: 'ORCID', value: p.orcid, url: orcidUrl(p.orcid)} : undefined,
image: p.photo ? {'@type': 'ImageObject', contentUrl: url(p.photo), caption: p.name} : undefined,
});
function graduate(entries) {
const [a] = entries;
const employer = entries.find(a => a.organization)?.organization;
const placement = entries.find(a => a.title && a.organization?.label === employer?.label);
return {
...person(a.name),
alternateName: nonempty(Object.keys(aliases).filter(n => aliases[n] === a.name)),
alumniOf: entries.some(a => !a.expected) ? [labRef, rpiRef] : undefined,
jobTitle: placement?.title,
worksFor: employer && employer.label !== 'Undisclosed startup' ? organization(employer.label, employer.url) : undefined,
sameAs: nonempty(unique(entries.map(a => a.url).filter(u => u && !new URL(u).pathname.endsWith('.pdf')))),
hasCredential: nonempty(entries.filter(a => degreeNames[a.degree] && !a.expected).map(a => {
const subject = a.fields.map(code => fields[code].name);
const name = degreeNames[a.degree] + (subject.length ? ' in ' + subject.join(' and ') : '');
return {'@type': 'EducationalOccupationalCredential', name, credentialCategory: a.degree,
description: a.year ? 'Graduation year: ' + a.year : undefined,
about: nonempty(topics(subject)), recognizedBy: rpiRef};
})),
description: nonempty(entries.filter(a => a.expected).map(a => 'Expected ' + a.degree + ' graduation year: ' + a.year))?.join('. ')
};
}
const grads = [...alumniGroups.values()].map(graduate);
byUniqueKey([...people.map(profile), ...grads], n => n['@id']);
const projectsById = byUniqueKey(catalog.projects, p => p.id);
const paperForUrl = byUniqueKey(publications.filter(p => p.url), p => p.url);
const projectForPaper = new Map();
const projectRefs = ids => (ids ?? []).map(id => {
if (!projectsById.has(id)) throw new Error('Unknown structured data project: ' + id);
return ref(url('/projects/#' + id));
});
const sponsorDirectory = Object.fromEntries(Object.entries(catalog.sponsors).map(([key, name]) => {
const mark = sponsorLogos[key];
const historical = key === 'ARDA' || key === 'DTO';
return [key, {
'@type': key === 'IBM' ? 'Organization' : 'GovernmentOrganization',
'@id': url('/projects/#sponsor-' + key.toLowerCase()),
name, alternateName: key, url: historical ? undefined : mark?.website,
subjectOf: historical && mark?.website ? {'@type': 'CreativeWork', url: mark.website} : undefined,
logo: mark && catalog.banner.includes(key) ? {'@type': 'ImageObject', contentUrl: url('/brand/sponsors/' + mark.file),
width: mark.width, height: mark.height} : undefined
}];
}));
function award(link, project, id) {
const grantId = new URL(link.url).pathname.match(/^\/award\/ASST_NON_([\w-]+)_\d+\/$/)?.[1] ||
new URL(link.url).searchParams.get('AWD_ID');
if (!grantId) return null;
const sponsor = project.sponsors.length === 1 ? project.sponsors[0] :
project.sponsors.find(key => link.label.startsWith(key + ' '));
if (!sponsor) throw new Error('Unknown funder for award ' + grantId);
return {'@type': 'MonetaryGrant', '@id': link.url, name: link.label, url: link.url,
identifier: grantId, funder: sponsorDirectory[sponsor], fundedItem: ref(id)};
}
const paperRecord = p => url('/publications/#' + publicationAnchor(p));
const projectNodes = catalog.projects.map(project => {
const id = url('/projects/#' + project.id);
const grants = [], coverage = [];
for (const link of project.links) {
const grant = award(link, project, id);
if (grant) {
grants.push(grant);
continue;
}
const paper = paperForUrl.get(link.publication || link.url);
if (link.publication && !paper) throw new Error('Unknown publication for ' + project.id + ': ' + link.publication);
if (paper) {
if (!projectForPaper.has(paper)) projectForPaper.set(paper, []);
projectForPaper.get(paper).push(ref(id));
coverage.push(ref(paperRecord(paper)));
} else {
coverage.push({'@type': 'CreativeWork', name: link.label, url: link.url});
}
}
const years = project.period.match(/^(\d{4})(?:–(\d{4}))?(?: kickoff)?$/);
if (!years) throw new Error('Unrecognized project period: ' + project.period);
const temporalCoverage = years[2] ? years[1] + '/' + years[2] : years[1];
return {
'@type': 'ResearchProject', '@id': id, url: id, name: project.title, description: project.description,
funder: project.sponsors.map(s => sponsorDirectory[s]),
funding: nonempty(grants),
member: [labRef, ...(project.team ?? []).map(({name, role}) => role
? {'@type': 'OrganizationRole', roleName: role, member: person(name)}
: person(name))],
subjectOf: [{'@type': 'WebPageElement', '@id': id + '-summary', url: id, name: project.title,
description: project.description, isPartOf: ref(url('/projects/#webpage')), temporalCoverage}, ...coverage]
};
});
const paperNodes = publications.map(p => publicationSchema(p, {
id: paperRecord(p), recordUrl: paperRecord(p), person, project: projectForPaper.get(p)
}));
byUniqueKey(paperNodes, p => p['@id']);
const storyNodes = stories.map(s => {
const local = url('/media/#' + s.id);
const video = s.type === 'VideoObject';
const audio = s.type === 'AudioObject';
const youtube = video && videoId(s.url);
const embeds = youtube ? 'https://www.youtube.com/embed/' + youtube : undefined;
const about = [...(s.people ?? []).map(person), ...projectRefs(s.projects)];
if (!about.length && !s.event) about.push(labRef);
// Stock images, unrelated portraits, and equipment illustrations stay on the lab’s cards.
const image = s.image?.path && !s.image.path.startsWith('/portraits/') && !s.projects?.length
? {'@type': 'ImageObject', contentUrl: url(s.image.path), width: s.image.width, height: s.image.height} : undefined;
const publisher = s.publisher ? organization(s.publisher) : undefined;
const references = unique([mediaSources.supportingSources[s.id], mediaSources.appearanceDates[s.id],
s.clips?.length ? mediaSources.clips : undefined]).filter(link => link !== s.url);
const date = s.dateKind ? undefined : s.date;
return {
'@type': s.type, '@id': local, name: s.title, headline: !video && !audio ? s.title : undefined,
alternateName: s.alternateName, genre: s.genre, description: s.description, url: s.url,
inLanguage: s.language ?? 'en', keywords: s.keywords,
publisher, isPartOf: s.periodical ? {'@type': 'Periodical', name: s.periodical, publisher} : undefined,
author: s.authors?.map(a => typeof a === 'string' ? person(a) : organization(a.organization)),
contributor: s.participants?.map(person),
about: nonempty(about),
datePublished: date,
dateModified: s.dateKind === 'modified' ? s.date : undefined,
uploadDate: s.uploadDate, embedUrl: embeds, contentUrl: s.contentUrl, encodingFormat: s.encodingFormat,
image: !video ? image : undefined,
thumbnailUrl: video ? image?.contentUrl ?? mediaSources.images[s.id + '.webp'] : undefined,
citation: nonempty([...references, ...(s.links ?? []).filter(l => !l.url.startsWith('/'))
.map(l => ({'@type': 'CreativeWork', name: l.name, url: l.url}))]),
recordedAt: s.event ? {'@type': 'Event', '@id': local + '-event', name: s.event.name,
startDate: s.date, location: {'@type': 'Place', name: s.event.location}, performer: director} : undefined,
hasPart: s.clips?.map(c => ({'@type': 'Clip', '@id': local + '-clip-' + c.start,
name: c.name, url: clipUrl(s.url, c), startOffset: c.start, endOffset: c.end, isPartOf: ref(local)})),
};
});
byUniqueKey(storyNodes, s => s['@id']);
const sections = new Map();
const addDirectory = (route, nodeLists, citations) => {
const nodes = nodeLists.flatMap(({nodes}) => nodes);
const lists = nodeLists.map(({id, name, nodes, anchors}) => list(url(route + '#' + id), name,
nodes.map((node, i) => ({node, url: anchors?.[i] ?? node.url})), url(route + '#' + id)));
sections.set(route, {type: 'CollectionPage', main: lists.map(node => ref(node['@id'])), nodes: [...lists, ...nodes], citations});
};
addDirectory('/members/', [
{id: 'current-members', name: 'Current members', nodes: current.map(profile)},
{id: 'associated-faculty', name: 'Affiliated Faculty', nodes: faculty.map(profile)},
{id: 'alumni', name: 'Alumni', nodes: grads}
], [sources.members]);
addDirectory('/projects/', [{id: 'research-projects', name: 'Research projects', nodes: projectNodes}], [sources.projects]);
addDirectory('/publications/', [{id: 'bibliography', name: 'Publication bibliography', nodes: paperNodes,
anchors: publications.map(paperRecord)}], [bibliographyUrl]);
addDirectory('/media/', [{id: 'selected-appearances', name: 'Media appearances', nodes: storyNodes,
anchors: stories.map(s => url('/media/#' + s.id))}], [mediaSources.index, mediaSources.clips]);
for (const p of people) {
sections.set(memberPage(p.slug), {type: 'ProfilePage', main: ref(profileId(p)), nodes: [profile(p)],
citations: unique([p.profileSource || sources.members, p.photoSource, p.orcidSource])});
}
sections.set('/', {main: labRef});
const pressId = url('/media/press-kit/#kit');
sections.set('/media/press-kit/', {main: ref(pressId), nodes: [{
'@type': 'CreativeWork', '@id': pressId, name: 'RAIR Lab Press Kit', about: labRef, publisher: labRef,
encoding: {'@type': 'MediaObject', contentUrl: url('/press/rair-press-kit.zip'), encodingFormat: 'application/zip'},
hasPart: {'@type': 'DigitalDocument', name: 'RAIR Lab fact sheet', url: url('/press/lab-facts.txt'), encodingFormat: 'text/plain'}
}]});
return {
url,
graph(route, title, description, crumbs) {
const canonical = url(route);
const {type, main, nodes, citations} = sections.get(route) ?? {};
const breadcrumbs = crumbs.length > 1 ? {
'@type': 'BreadcrumbList', '@id': canonical + '#breadcrumb',
itemListElement: crumbs.map(([route, name], index) => ({
'@type': 'ListItem', position: index + 1, name, item: url(route)
}))
} : undefined;
const webpage = {
'@type': type ?? 'WebPage', '@id': canonical + '#webpage', url: canonical, name: title, description,
inLanguage: 'en', isPartOf: ref(siteId), publisher: labRef,
about: type === 'ProfilePage' ? main : labRef, mainEntity: main,
breadcrumb: breadcrumbs ? ref(breadcrumbs['@id']) : undefined,
citation: nonempty(citations)
};
return [webpage, site, lab, rpi, ...(breadcrumbs ? [breadcrumbs] : []), ...(nodes ?? [])];
}
};
}