-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate-oslc-server.ts
More file actions
executable file
·1305 lines (1100 loc) · 43.3 KB
/
create-oslc-server.ts
File metadata and controls
executable file
·1305 lines (1100 loc) · 43.3 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
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
#!/usr/bin/env npx tsx
/*
* create-oslc-server.ts — Scaffold a new OSLC server project in the oslc4js workspace.
*
* Usage:
* npx tsx create-oslc-server.ts --name <server-name> [options]
*
* Options:
* --name <name> Server project name (required, e.g. bmm-server)
* --port <number> Port number (default: 3001)
* --vocab <file> RDF vocabulary file to copy into config/domain/
* --shapes <file> RDF shapes file to copy into config/domain/
* --managed <classes> Comma-separated class names for OSLC services
* (requires --shapes; e.g. Means,End,Strategy)
*
* Examples:
* # Minimal — sample config with TODOs
* npx tsx create-oslc-server.ts --name bmm-server --port 3003
*
* # With domain vocabulary, shapes, and managed classes
* npx tsx create-oslc-server.ts --name bmm-server --port 3003 \
* --vocab BMM.ttl --shapes BMM-Shapes.ttl \
* --managed Means,End,Strategy,Objective
*
* Copyright 2014 IBM Corporation.
* Licensed under the Apache License, Version 2.0.
*/
import { mkdirSync, writeFileSync, copyFileSync, readFileSync, existsSync } from 'node:fs';
import { join, dirname, basename, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import * as rdflib from 'rdflib';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// ── Well-known namespaces ─────────────────────────────────────────
const RDF = rdflib.Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#');
const RDFS = rdflib.Namespace('http://www.w3.org/2000/01/rdf-schema#');
const DCTERMS = rdflib.Namespace('http://purl.org/dc/terms/');
const OSLC = rdflib.Namespace('http://open-services.net/ns/core#');
const XSD = rdflib.Namespace('http://www.w3.org/2001/XMLSchema#');
const WELL_KNOWN_NAMESPACES = new Set([
'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
'http://www.w3.org/2000/01/rdf-schema#',
'http://www.w3.org/2002/07/owl#',
'http://www.w3.org/2001/XMLSchema#',
'http://www.w3.org/XML/1998/namespace',
'http://purl.org/dc/terms/',
'http://purl.org/dc/elements/1.1/',
'http://open-services.net/ns/core#',
'http://open-services.net/ns/am#',
'http://open-services.net/ns/cm#',
'http://open-services.net/ns/rm#',
'http://open-services.net/ns/config#',
'http://www.w3.org/ns/ldp#',
'http://xmlns.com/foaf/0.1/',
'http://www.w3.org/2004/02/skos/core#',
'http://www.w3.org/ns/shacl#',
'http://www.omg.org/spec/DD#',
]);
// ── Argument parsing ──────────────────────────────────────────────
interface CliArgs {
name: string;
port: number;
vocab: string[];
shapes: string[];
managed?: string[];
}
function parseArgs(argv: string[]): CliArgs {
const args = argv.slice(2);
let name = '';
let port = 3001;
// --vocab and --shapes are repeatable so a single server can be
// scaffolded over multiple domain vocabularies (e.g., a server that
// serves both BMM and a complementary domain), or over a single
// domain whose shapes have been refactored into independent files.
const vocab: string[] = [];
const shapes: string[] = [];
let managed: string[] | undefined;
for (let i = 0; i < args.length; i++) {
switch (args[i]) {
case '--name':
name = args[++i];
break;
case '--port':
port = Number(args[++i]);
break;
case '--vocab':
vocab.push(args[++i]);
break;
case '--shapes':
shapes.push(args[++i]);
break;
case '--managed':
managed = args[++i].split(',').map((s) => s.trim());
break;
default:
console.error(`Unknown option: ${args[i]}`);
process.exit(1);
}
}
if (!name) {
console.log(`Usage: npx tsx create-oslc-server.ts --name <server-name> [options]
Options:
--name <name> Server project name (required, e.g. bmm-server)
--port <number> Port number (default: 3001)
--vocab <file> RDF vocabulary file to copy into config/domain/.
Repeatable — pass once per domain or per refactored
vocabulary section.
--shapes <file> RDF shapes file to copy into config/domain/.
Repeatable — pass once per shapes file. Managed
classes are resolved across the union of all shapes;
each managed class's catalog reference points at
the shapes file that actually defines it.
--managed <classes> Comma-separated class names for OSLC services
(requires at least one --shapes; e.g. Means,End,Strategy)
Examples:
# Sample server with TODO placeholders
npx tsx create-oslc-server.ts --name bmm-server --port 3003
# Single domain
npx tsx create-oslc-server.ts --name bmm-server --port 3003 \\
--vocab BMM.ttl --shapes BMM-Shapes.ttl \\
--managed Vision,Goal,Strategy,Objective
# Multiple domains in one server
npx tsx create-oslc-server.ts --name lifecycle-server --port 3010 \\
--vocab BMM.ttl --shapes BMM-Shapes.ttl \\
--vocab MRM.ttl --shapes MRM-Shapes.ttl \\
--managed Vision,Goal,Program,Service`);
process.exit(1);
}
if (managed && shapes.length === 0) {
console.error('Error: --managed requires at least one --shapes');
process.exit(1);
}
for (const v of vocab) {
if (!existsSync(resolve(v))) {
console.error(`Error: Vocabulary file not found: ${v}`);
process.exit(1);
}
}
for (const s of shapes) {
if (!existsSync(resolve(s))) {
console.error(`Error: Shapes file not found: ${s}`);
process.exit(1);
}
}
if (isNaN(port) || port < 1 || port > 65535) {
console.error(`Error: Invalid port number: ${port}`);
process.exit(1);
}
return { name, port, vocab, shapes, managed };
}
// ── RDF helpers ───────────────────────────────────────────────────
interface DomainInfo {
prefix: string;
namespace: string;
}
/**
* Parse an RDF file into a graph. Detects content type from file extension.
*/
function parseRdfFile(filePath: string): rdflib.IndexedFormula {
const content = readFileSync(resolve(filePath), 'utf-8');
const store = rdflib.graph();
const ext = filePath.toLowerCase();
let contentType = 'text/turtle';
if (ext.endsWith('.jsonld') || ext.endsWith('.json')) {
contentType = 'application/ld+json';
} else if (ext.endsWith('.rdf') || ext.endsWith('.xml')) {
contentType = 'application/rdf+xml';
} else if (ext.endsWith('.nt') || ext.endsWith('.ntriples')) {
contentType = 'application/n-triples';
}
rdflib.parse(content, store, 'urn:scaffold:', contentType);
return store;
}
/**
* Find the domain namespace — the non-well-known namespace used for class
* definitions. Looks at oslc:describes objects, rdfs:Class subjects, and
* rdf:type objects to find URIs in a non-standard namespace.
*/
function findDomainNamespace(store: rdflib.IndexedFormula): DomainInfo | undefined {
// Collect candidate URIs from:
// 1. Objects of oslc:describes (most reliable — shapes file)
// 2. Subjects typed as rdfs:Class (vocab file)
// 3. Subjects typed as rdf:Property (vocab file)
const candidateURIs: string[] = [];
for (const st of store.statementsMatching(undefined, OSLC('describes'), undefined)) {
if (st.object.termType === 'NamedNode') {
candidateURIs.push(st.object.value);
}
}
for (const st of store.statementsMatching(undefined, RDF('type'), RDFS('Class'))) {
if (st.subject.termType === 'NamedNode') {
candidateURIs.push(st.subject.value);
}
}
// Find the first namespace that isn't well-known
for (const uri of candidateURIs) {
const hashIdx = uri.lastIndexOf('#');
const slashIdx = uri.lastIndexOf('/');
const splitIdx = Math.max(hashIdx, slashIdx);
if (splitIdx <= 0) continue;
const ns = uri.substring(0, splitIdx + 1);
if (!WELL_KNOWN_NAMESPACES.has(ns)) {
// Derive a prefix from the namespace: use the last path segment
// e.g. http://www.misa.org.ca/mrm# → mrm
// http://www.omg.org/spec/BMM# → bmm (lowercased)
const pathPart = ns.replace(/[#/]$/, '');
const lastSeg = pathPart.substring(pathPart.lastIndexOf('/') + 1);
const prefix = lastSeg.toLowerCase();
return { prefix, namespace: ns };
}
}
return undefined;
}
interface ShapeInfo {
shapeNode: rdflib.NamedNode;
fragmentId: string; // e.g. "MeansShape"
classURI: string; // e.g. "http://www.omg.org/spec/BMM#Means"
className: string; // e.g. "Means" (local name)
shapeTitle: string; // e.g. "Means" (from dcterms:title)
shapesFileBaseName: string; // basename without extension, e.g. "BMM-Shapes"
}
/**
* Extract all ResourceShape definitions from a parsed shapes graph.
* `shapesFileBaseName` is stamped onto each result so that later, when we
* generate the catalog template, each managed class's `oslc:resourceShape`
* reference points at the actual shapes document that defines it — important
* when a server is scaffolded over multiple shapes files.
*/
function extractShapes(store: rdflib.IndexedFormula, shapesFileBaseName: string): ShapeInfo[] {
const shapes: ShapeInfo[] = [];
// Find all subjects that are oslc:ResourceShape
const shapeStatements = store.statementsMatching(undefined, RDF('type'), OSLC('ResourceShape'));
for (const st of shapeStatements) {
const shapeNode = st.subject;
if (shapeNode.termType !== 'NamedNode') continue;
// Get oslc:describes
const describedClass = store.any(shapeNode, OSLC('describes'), undefined);
if (!describedClass || describedClass.termType !== 'NamedNode') continue;
// Get dcterms:title
const titleNode = store.any(shapeNode, DCTERMS('title'), undefined);
const shapeTitle = titleNode ? titleNode.value : '';
// Extract fragment ID from shape URI (e.g. "urn:scaffold:#ProgramShape" → "ProgramShape")
const shapeURI = shapeNode.value;
const hashIdx = shapeURI.lastIndexOf('#');
const fragmentId = hashIdx >= 0 ? shapeURI.substring(hashIdx + 1) : shapeURI;
// Extract local class name (e.g. "http://www.misa.org.ca/mrm#Program" → "Program")
const classURI = describedClass.value;
const classHashIdx = classURI.lastIndexOf('#');
const classSlashIdx = classURI.lastIndexOf('/');
const classSplitIdx = Math.max(classHashIdx, classSlashIdx);
const className = classSplitIdx >= 0 ? classURI.substring(classSplitIdx + 1) : classURI;
shapes.push({
shapeNode: shapeNode as rdflib.NamedNode,
fragmentId,
classURI,
className,
shapeTitle: shapeTitle || className,
shapesFileBaseName,
});
}
return shapes;
}
// ── Catalog template generation using rdflib ──────────────────────
interface ManagedClass {
className: string;
classURI: string;
shapeFragmentId: string;
displayTitle: string;
shapesFileBaseName: string;
}
function pluralize(word: string): string {
if (word.endsWith('s') || word.endsWith('x') || word.endsWith('sh') || word.endsWith('ch')) {
return word + 'es';
}
if (word.endsWith('y') && !'aeiou'.includes(word.charAt(word.length - 2))) {
return word.slice(0, -1) + 'ies';
}
return word + 's';
}
function generateCatalogTemplate(
serverName: string,
title: string,
domains: DomainInfo[],
managedClasses: ManagedClass[],
): string {
const store = rdflib.graph();
// Catalog template URIs
const catalogNode = rdflib.sym('urn:oslc:template/catalog');
const spNode = rdflib.sym('urn:oslc:template/sp');
const serviceNode = rdflib.sym('urn:oslc:template/sp/service');
// --- Catalog metadata ---
store.add(catalogNode, DCTERMS('title'), rdflib.lit(`${title} Service Provider Catalog`));
store.add(catalogNode, DCTERMS('description'), rdflib.lit(`Root ServiceProviderCatalog for ${serverName}`));
const publisherNode = rdflib.blankNode();
store.add(catalogNode, DCTERMS('publisher'), publisherNode);
store.add(publisherNode, RDF('type'), OSLC('Publisher'));
store.add(publisherNode, DCTERMS('identifier'), rdflib.lit(serverName));
store.add(publisherNode, DCTERMS('title'), rdflib.lit(title));
// --- ServiceProvider template ---
store.add(spNode, RDF('type'), OSLC('ServiceProvider'));
store.add(spNode, OSLC('service'), serviceNode);
// --- Service ---
// One oslc:domain per detected vocabulary namespace — a multi-domain
// server lists every domain it serves so MCP/LDM clients can discover
// the full vocabulary surface.
store.add(serviceNode, RDF('type'), OSLC('Service'));
for (const domain of domains) {
store.add(serviceNode, OSLC('domain'), rdflib.sym(domain.namespace.replace(/#$/, '')));
}
for (const mc of managedClasses) {
const classNode = rdflib.sym(mc.classURI);
// Use an absolute URI with the catalog base so rdflib serializes it as
// a relative reference (e.g. <domain/MRMS-Shapes#ProgramShape>).
// Each managed class points at its own shapes file — different managed
// classes may live in different shapes files when scaffolding a
// multi-domain server.
const shapeRef = rdflib.sym(`urn:oslc:template/domain/${mc.shapesFileBaseName}#${mc.shapeFragmentId}`);
// Creation Factory
const factoryNode = rdflib.blankNode();
store.add(serviceNode, OSLC('creationFactory'), factoryNode);
store.add(factoryNode, RDF('type'), OSLC('CreationFactory'));
store.add(factoryNode, DCTERMS('title'), rdflib.lit(pluralize(mc.displayTitle)));
store.add(factoryNode, OSLC('resourceType'), classNode);
store.add(factoryNode, OSLC('resourceShape'), shapeRef);
// Creation Dialog
const dialogNode = rdflib.blankNode();
store.add(serviceNode, OSLC('creationDialog'), dialogNode);
store.add(dialogNode, RDF('type'), OSLC('Dialog'));
store.add(dialogNode, DCTERMS('title'), rdflib.lit(`New ${mc.displayTitle}`));
store.add(dialogNode, OSLC('label'), rdflib.lit(mc.displayTitle));
store.add(dialogNode, OSLC('resourceType'), classNode);
store.add(dialogNode, OSLC('hintHeight'), rdflib.lit('505px'));
store.add(dialogNode, OSLC('hintWidth'), rdflib.lit('680px'));
store.add(dialogNode, OSLC('resourceShape'), shapeRef);
// Query Capability
const queryNode = rdflib.blankNode();
store.add(serviceNode, OSLC('queryCapability'), queryNode);
store.add(queryNode, RDF('type'), OSLC('QueryCapability'));
store.add(queryNode, DCTERMS('title'), rdflib.lit(`Query ${pluralize(mc.displayTitle)}`));
store.add(queryNode, OSLC('resourceType'), classNode);
store.add(queryNode, OSLC('resourceShape'), shapeRef);
}
// Serialize to Turtle
let result = '';
rdflib.serialize(undefined, store, 'urn:oslc:template/', 'text/turtle', (err, content) => {
if (err) {
console.error('Error serializing catalog template:', err);
process.exit(1);
}
result = content ?? '';
});
return result;
}
// ── File helpers ──────────────────────────────────────────────────
let projectDir: string;
function mkdirs(...paths: string[]): void {
for (const p of paths) {
mkdirSync(p, { recursive: true });
}
}
function writeFile(relativePath: string, content: string): void {
writeFileSync(join(projectDir, relativePath), content);
}
function copyFromOslcServer(relativePath: string): void {
copyFileSync(
join(__dirname, 'oslc-server', relativePath),
join(projectDir, relativePath),
);
}
// ── Main ──────────────────────────────────────────────────────────
const cli = parseArgs(process.argv);
const serverName = cli.name;
const port = cli.port;
// Derive display-friendly title (e.g. bmm-server -> Bmm Server)
const title = serverName
.split('-')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
// Derive Fuseki dataset name (strip -server suffix)
const dataset = serverName.replace(/-server$/, '');
projectDir = join(__dirname, serverName);
if (existsSync(projectDir)) {
console.error(`Error: Directory '${projectDir}' already exists.`);
process.exit(1);
}
// ── Parse vocab and shapes if provided ────────────────────────────
const domainInfos: DomainInfo[] = [];
const allShapes: ShapeInfo[] = [];
const managedClasses: ManagedClass[] = [];
const vocabFileNames: string[] = [];
const shapesFileNames: string[] = [];
// Multiple vocab/shapes files may resolve to the same domain (for
// example, a vocab refactored across a few files); only emit each
// namespace once on the ServiceProvider as oslc:domain.
const seenNamespaces = new Set<string>();
const addDomainInfo = (info: DomainInfo | undefined): void => {
if (info && !seenNamespaces.has(info.namespace)) {
seenNamespaces.add(info.namespace);
domainInfos.push(info);
}
};
for (const v of cli.vocab) {
const store = parseRdfFile(v);
addDomainInfo(findDomainNamespace(store));
vocabFileNames.push(basename(v));
}
for (const s of cli.shapes) {
const store = parseRdfFile(s);
const fileName = basename(s);
const baseName = fileName.replace(/\.\w+$/i, '');
const shapesFromFile = extractShapes(store, baseName);
if (shapesFromFile.length === 0) {
console.error(`Error: No ResourceShape definitions found in ${fileName}.`);
console.error('Expected oslc:ResourceShape instances with oslc:describes properties.');
process.exit(1);
}
allShapes.push(...shapesFromFile);
shapesFileNames.push(fileName);
// Shapes files often declare their domain too; pick up any new
// namespace they reveal that the vocab files didn't.
addDomainInfo(findDomainNamespace(store));
}
for (const fileName of vocabFileNames) {
console.log(` Vocabulary: ${fileName}`);
}
for (const fileName of shapesFileNames) {
console.log(` Shapes: ${fileName}`);
}
for (const d of domainInfos) {
console.log(` Domain: ${d.prefix}: <${d.namespace}>`);
}
if (allShapes.length > 0) {
console.log(` Resource shapes found: ${allShapes.length}`);
}
if (cli.managed && cli.shapes.length > 0) {
if (domainInfos.length === 0) {
console.error('Error: Could not detect a domain namespace from --vocab or --shapes files.');
console.error('Ensure at least one file defines classes in a non-standard namespace.');
process.exit(1);
}
// Resolve each managed class name across the union of all shapes
// files. Each managed class records the shapes file basename that
// actually defines it, so the catalog template can reference it
// correctly when the server is scaffolded over multiple shapes files.
for (const className of cli.managed) {
const matches = allShapes.filter((s) => s.className === className);
if (matches.length === 0) {
const available = allShapes.map((s) => s.className).join(', ');
console.error(`Error: No shape found for managed class '${className}'.`);
console.error(`Available classes across all shapes files: ${available}`);
process.exit(1);
}
if (matches.length > 1) {
const sources = matches.map((m) => m.shapesFileBaseName).join(', ');
console.error(`Error: Class '${className}' is defined in multiple shapes files (${sources}).`);
console.error('Managed class names must be unique across the supplied --shapes files.');
process.exit(1);
}
const shape = matches[0];
managedClasses.push({
className,
classURI: shape.classURI,
shapeFragmentId: shape.fragmentId,
displayTitle: shape.shapeTitle,
shapesFileBaseName: shape.shapesFileBaseName,
});
}
// Use the first detected domain prefix for the summary line. The
// catalog template emits one oslc:domain per detected vocabulary;
// managed classes resolve through their shape's URI, which is
// already qualified.
const primaryDomain = domainInfos[0];
console.log(` Managed: ${managedClasses.map((mc) => `${primaryDomain.prefix}:${mc.className}`).join(', ')}`);
}
const useDomainConfig = managedClasses.length > 0 && domainInfos.length > 0;
console.log(`\nCreating OSLC server project: ${serverName}`);
console.log(` Title: ${title}`);
console.log(` Port: ${port}`);
console.log(` Dataset: ${dataset}`);
console.log(` Path: ${projectDir}`);
console.log('');
// ── Create directory structure ────────────────────────────────────
mkdirs(
join(projectDir, 'config', 'domain'),
join(projectDir, 'dialog'),
join(projectDir, 'src'),
join(projectDir, 'ui', 'src'),
join(projectDir, 'ui', 'public', 'images'),
join(projectDir, 'ui', 'public', 'stylesheets'),
join(projectDir, 'public'),
join(projectDir, 'testing'),
);
// ── package.json ──────────────────────────────────────────────────
writeFile('package.json', JSON.stringify({
name: serverName,
version: '1.0.0',
description: `An OSLC 3.0 server for ${title} using oslc-service`,
license: 'Apache-2.0',
author: '',
type: 'module',
main: 'dist/app.js',
scripts: {
build: 'tsc',
clean: 'rm -rf dist',
start: 'node dist/app.js',
},
dependencies: {
'cors': '^2.8.6',
'express': '^5.0.1',
'jena-storage-service': '*',
'oslc-service': '*',
'storage-service': '*',
},
devDependencies: {
'@types/cors': '^2.8.19',
'@types/express': '^5.0.0',
'@types/node': '^22.0.0',
'typescript': '^5.7.0',
},
engines: {
node: '^22.11.0',
},
}, null, 2) + '\n');
// ── tsconfig.json ─────────────────────────────────────────────────
writeFile('tsconfig.json', JSON.stringify({
compilerOptions: {
target: 'ES2022',
module: 'Node16',
moduleResolution: 'Node16',
outDir: 'dist',
rootDir: 'src',
declaration: true,
declarationMap: true,
sourceMap: true,
strict: true,
esModuleInterop: true,
skipLibCheck: true,
forceConsistentCasingInFileNames: true,
resolveJsonModule: true,
},
exclude: ['ui', 'dist'],
}, null, 2) + '\n');
// ── config.json ───────────────────────────────────────────────────
writeFile('config.json', JSON.stringify({
scheme: 'http',
host: 'localhost',
port,
context: '/',
jenaURL: `http://localhost:3030/${dataset}/`,
}, null, 2) + '\n');
// ── src/app.ts ────────────────────────────────────────────────────
writeFile('src/app.ts', `\
/*
* Copyright 2014 IBM Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* ${serverName}: An OSLC 3.0 server for ${title} that uses
* oslc-service Express middleware. Initializes the server, connects
* to Fuseki via jena-storage-service, and serves OSLC resources.
*/
import express, { type Request, type Response, type NextFunction } from 'express';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { oslcService } from 'oslc-service';
import { JenaStorageService } from 'jena-storage-service';
import { env } from './env.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
console.log('configuration:');
console.dir(env);
const app = express();
// Serve static files
app.use(express.static(join(__dirname, '..', 'public')));
app.use('/dialog', express.static(join(__dirname, '..', 'dialog')));
// Initialize storage and mount OSLC service
const storage = new JenaStorageService();
try {
await storage.init(env);
app.use(await oslcService(env, storage));
} catch (err) {
console.error(err);
console.error("Can't initialize the Jena storage service.");
}
// Error handling
app.use((err: Error, _req: Request, res: Response, _next: NextFunction) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
app.listen(env.listenPort, env.listenHost, () => {
console.log('${serverName} running on ' + env.appBase);
});
`);
// ── src/env.ts ────────────────────────────────────────────────────
writeFile('src/env.ts', `\
/*
* Copyright 2014 IBM Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Looks at environment variables for app configuration (base URI, port, LDP
* context, etc.), falling back to what's in config.json.
*/
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { readFileSync } from 'node:fs';
import { format as formatURL } from 'node:url';
import type { StorageEnv } from 'storage-service';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
interface Config {
scheme: string;
host: string;
port: number;
context: string;
jenaURL: string;
}
const config: Config = JSON.parse(
readFileSync(join(__dirname, '..', 'config.json'), 'utf-8')
);
function addSlash(url: string): string {
return url.endsWith('/') ? url : url + '/';
}
interface URLFormatOptions {
protocol?: string;
hostname?: string;
host?: string;
port?: number;
pathname?: string;
}
function toURL(urlObj: URLFormatOptions): string {
const opts = { ...urlObj };
if ((opts.protocol === 'http' && opts.port === 80) ||
(opts.protocol === 'https' && opts.port === 443)) {
delete opts.port;
}
return formatURL(opts as Parameters<typeof formatURL>[0]);
}
export interface AppEnv extends StorageEnv {
listenHost: string;
listenPort: number;
scheme: string;
host: string;
port?: number;
context: string;
ldpBase: string;
templatePath?: string;
}
const listenHost = process.env.VCAP_APP_HOST || process.env.OPENSHIFT_NODEJS_IP || config.host;
const listenPort = Number(process.env.VCAP_APP_PORT || process.env.OPENSHIFT_NODEJS_PORT || config.port);
let scheme: string;
let host: string;
let port: number | undefined;
let context: string;
let appBase: string;
let ldpBase: string;
if (process.env.LDP_BASE) {
ldpBase = addSlash(process.env.LDP_BASE);
const parsed = new URL(ldpBase);
scheme = parsed.protocol.replace(':', '');
host = parsed.hostname;
port = parsed.port ? Number(parsed.port) : undefined;
context = parsed.pathname;
appBase = toURL({ protocol: scheme, hostname: host, port });
} else {
const appInfo = JSON.parse(process.env.VCAP_APPLICATION || '{}') as { application_uris?: string[] };
scheme = process.env.VCAP_APP_PORT ? 'http' : config.scheme;
if (appInfo.application_uris) {
host = appInfo.application_uris[0];
} else {
host = process.env.HOSTNAME || config.host;
}
if (!process.env.VCAP_APP_PORT) {
port = config.port;
}
context = addSlash(config.context);
appBase = toURL({ protocol: scheme, hostname: host, port });
ldpBase = toURL({ protocol: scheme, hostname: host, port, pathname: context });
}
export const env: AppEnv = {
listenHost,
listenPort,
scheme,
host,
port,
context,
appBase,
ldpBase,
jenaURL: config.jenaURL,
templatePath: join(__dirname, '..', 'config', 'catalog-template.ttl'),
};
`);
// ── config/catalog-template.ttl ──────────────────────────────────
if (useDomainConfig) {
writeFile('config/catalog-template.ttl',
generateCatalogTemplate(serverName, title, domainInfos, managedClasses));
} else {
// Default sample catalog with TODOs
writeFile('config/catalog-template.ttl', `\
@prefix dcterms: <http://purl.org/dc/terms/> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix oslc: <http://open-services.net/ns/core#> .
@prefix oslc_cm: <http://open-services.net/ns/cm#> .
@prefix oslc_rm: <http://open-services.net/ns/rm#> .
# --- Catalog properties ---
# TODO: Update the catalog title, description, and publisher for your server.
<urn:oslc:template/catalog>
dcterms:title "${title} Service Provider Catalog" ;
dcterms:description "Root ServiceProviderCatalog for ${serverName}" ;
dcterms:publisher [
a oslc:Publisher ;
dcterms:identifier "${serverName}" ;
dcterms:title "${title}"
] .
# --- Meta ServiceProvider definition ---
# TODO: Update the services, creation factories, dialogs, and query capabilities
# to match the resource types managed by your server.
<urn:oslc:template/sp>
a oslc:ServiceProvider ;
oslc:service <urn:oslc:template/sp/service> .
<urn:oslc:template/sp/service>
a oslc:Service ;
oslc:domain oslc_cm: , oslc_rm: ;
oslc:creationFactory [
a oslc:CreationFactory ;
dcterms:title "Change Management Resources" ;
oslc:resourceType oslc_cm:ChangeRequest ;
oslc:resourceShape <domain/ChangeRequest>
] ;
oslc:creationFactory [
a oslc:CreationFactory ;
dcterms:title "Requirements Management Resources" ;
oslc:resourceType oslc_rm:Requirement ;
oslc:resourceShape <domain/Requirement>
] ;
oslc:creationDialog [
a oslc:Dialog ;
dcterms:title "New Change Request" ;
oslc:label "Change Request" ;
oslc:resourceType oslc_cm:ChangeRequest ;
oslc:hintHeight "505px" ;
oslc:hintWidth "680px" ;
oslc:resourceShape <domain/ChangeRequest>
] ;
oslc:creationDialog [
a oslc:Dialog ;
dcterms:title "New Requirement" ;
oslc:label "Requirement" ;
oslc:resourceType oslc_rm:Requirement ;
oslc:hintHeight "505px" ;
oslc:hintWidth "680px" ;
oslc:resourceShape <domain/Requirement>
] ;
oslc:queryCapability [
a oslc:QueryCapability ;
dcterms:title "Query Change Requests" ;
oslc:resourceType oslc_cm:ChangeRequest ;
oslc:resourceShape <domain/ChangeRequest>
] ;
oslc:queryCapability [
a oslc:QueryCapability ;
dcterms:title "Query Requirements" ;
oslc:resourceType oslc_rm:Requirement ;
oslc:resourceShape <domain/Requirement>
] .
`);
}
// ── config/domain/ — shapes files ────────────────────────────────
if (cli.shapes.length > 0) {
for (let i = 0; i < cli.shapes.length; i++) {
copyFileSync(resolve(cli.shapes[i]), join(projectDir, 'config', 'domain', shapesFileNames[i]));
}
} else {
writeFile('config/domain/ChangeRequest.ttl', `\
@prefix dcterms: <http://purl.org/dc/terms/> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix oslc: <http://open-services.net/ns/core#> .
@prefix oslc_cm: <http://open-services.net/ns/cm#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
# TODO: Replace or extend this sample shape with your domain-specific resource shapes.
<>
a oslc:ResourceShape ;
dcterms:title "Change Request" ;
oslc:describes oslc_cm:ChangeRequest ;
oslc:property [
a oslc:Property ;
oslc:name "title" ;
oslc:propertyDefinition dcterms:title ;
dcterms:description "Title of the change request." ;
oslc:occurs oslc:Exactly-one ;
oslc:valueType xsd:string
] ;
oslc:property [
a oslc:Property ;
oslc:name "description" ;
oslc:propertyDefinition dcterms:description ;
dcterms:description "Description of the change request." ;
oslc:occurs oslc:Zero-or-one ;
oslc:valueType xsd:string
] ;
oslc:property [
a oslc:Property ;
oslc:name "identifier" ;
oslc:propertyDefinition dcterms:identifier ;
dcterms:description "Unique identifier for the change request." ;
oslc:occurs oslc:Exactly-one ;
oslc:valueType xsd:string ;
oslc:readOnly true
] ;
oslc:property [
a oslc:Property ;
oslc:name "type" ;
oslc:propertyDefinition rdf:type ;
dcterms:description "Resource type." ;
oslc:occurs oslc:Zero-or-many ;
oslc:valueType oslc:Resource ;
oslc:representation oslc:Reference
] .
`);
writeFile('config/domain/Requirement.ttl', `\
@prefix dcterms: <http://purl.org/dc/terms/> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix oslc: <http://open-services.net/ns/core#> .
@prefix oslc_rm: <http://open-services.net/ns/rm#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
# TODO: Replace or extend this sample shape with your domain-specific resource shapes.
<>
a oslc:ResourceShape ;
dcterms:title "Requirement" ;
oslc:describes oslc_rm:Requirement ;
oslc:property [
a oslc:Property ;
oslc:name "title" ;
oslc:propertyDefinition dcterms:title ;
dcterms:description "Title of the requirement." ;
oslc:occurs oslc:Exactly-one ;
oslc:valueType xsd:string
] ;