-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathmodules.mjs
More file actions
2294 lines (1946 loc) · 74.4 KB
/
modules.mjs
File metadata and controls
2294 lines (1946 loc) · 74.4 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
/*
* Copyright 2021 Comcast Cable Communications Management, LLC
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
import helpers from 'crocks/helpers/index.js'
const { compose, getPathOr, setPath } = helpers
import safe from 'crocks/Maybe/safe.js'
import find from 'crocks/Maybe/find.js'
import getPath from 'crocks/Maybe/getPath.js'
import pointfree from 'crocks/pointfree/index.js'
const { chain, filter, option, map } = pointfree
import logic from 'crocks/logic/index.js'
const { and, not } = logic
import isString from 'crocks/core/isString.js'
import predicates from 'crocks/predicates/index.js'
import { getExternalSchemaPaths, isDefinitionReferencedBySchema, isNull, localizeDependencies, isSchema, getLocalSchemaPaths, replaceRef, getPropertySchema, dereferenceAndMergeAllOfs, getPath as getRefDefinition, getAllValuesForName, replaceUri, getReferencedSchema } from './json-schema.mjs'
import { extension, getNotifier, isEvent, isNotifier, isPusher, isRegistration, name as methodName, rename as methodRename, provides } from './methods.mjs'
const { isObject, isArray, propEq, pathSatisfies, hasProp, propSatisfies } = predicates
// TODO remove these when major/rpc branch is merged
const name = method => method.name.split('.').pop()
const rename = (method, renamer) => method.name.split('.').map((x, i, arr) => i === (arr.length-1) ? renamer(x) : x).join('.')
// util for visually debugging crocks ADTs
const inspector = obj => {
if (obj.inspect) {
console.log(obj.inspect())
} else {
console.log(obj)
}
}
const isEnum = compose(
filter(x => x.type === 'string' && Array.isArray(x.enum) && x.title),
map(([_, val]) => val),
filter(([_key, val]) => isObject(val))
)
// Maybe methods array of objects
const getMethods = compose(
option([]),
map(filter(isObject)),
chain(safe(isArray)),
getPath(['methods'])
)
const isProviderInterfaceMethod = method => {
let tag = method.tags.find(t => t.name === 'capabilities')
const isProvider = tag['x-provides'] && !tag['x-allow-focus-for'] && !tag['x-response-for'] && !tag['x-error-for'] && !tag['x-push'] && !method.tags.find(t => t.name === 'registration')
tag = method.tags.find(t => t.name.startsWith('polymorphic-pull'))
const isPuller = !!tag
return isProvider && !isPuller //(!method.tags.find(t => t.name.startsWith('polymorphic-pull')))
}
const getProvidedCapabilities = (json) => {
return Array.from(new Set([...getMethods(json).filter(isProviderInterfaceMethod).map(method => method.tags.find(tag => tag['x-provides'])['x-provides'])]))
}
const getProviderInterfaceMethods = (_interface, json, prefix) => {
return json.methods.filter(method => method.name.split('.')[0] === _interface).filter(isProviderInterfaceMethod)
//return getMethods(json).filter(method => methodName(method).startsWith(prefix) && method.tags && method.tags.find(tag => tag['x-provides'] === _interface))
}
const getInterfaces = (json) => {
const list = Array.from(new Set((json.methods || []).filter(m => m.tags.find(t => t['x-provides']))
.filter(m => !m.tags.find(t => t.name.startsWith('registration')))
.filter(m => !m.tags.find(t => t.name.startsWith('polymorphic-pull')))
.filter(m => !extension(m, 'x-push'))
.map(m => m.name.split('.')[0])))
return list
}
function getProviderInterface(_interface, module) {
module = JSON.parse(JSON.stringify(module))
const iface = getProviderInterfaceMethods(_interface, module).map(method => dereferenceAndMergeAllOfs(method, module))
if (iface.length && iface.every(method => methodName(method).startsWith('onRequest'))) {
console.log(`Transforming legacy provider interface ${_interface}`)
updateUnidirectionalProviderInterface(iface, module)
}
return iface
}
function getUnidirectionalProviderInterfaceName(_interface, capability, document = {}) {
const iface = getProviderInterface(_interface, document)
const [ module, method ] = iface[0].name.split('.')
const uglyName = capability.split(":").slice(-2).map(capitalize).reverse().join('') + "Provider"
let name = iface.length === 1 ? method.charAt(0).toUpperCase() + method.substr(1) + "Provider" : uglyName
if (document.info['x-interface-names']) {
name = document.info['x-interface-names'][capability] || name
}
return name
}
function updateUnidirectionalProviderInterface(iface, module) {
iface.forEach(method => {
const payload = getPayloadFromEvent(method)
const focusable = method.tags.find(t => t['x-allow-focus'])
// remove `onRequest`
method.name = methodRename(method, name => name.charAt(9).toLowerCase() + name.substr(10))
const schema = getPropertySchema(payload, 'properties.parameters', module)
method.params = [
{
"name": "parameters",
"required": true,
"schema": schema
}
]
// TODO: we used to say !extractProviderSchema, which CPP sets to true and therefor skips this. not sure why...
if (true) {
let exampleResult = null
if (method.tags.find(tag => tag['x-response'])) {
const result = method.tags.find(tag => tag['x-response'])['x-response']
method.result = {
"name": "result",
"schema": result
}
if (result.examples && result.examples[0]) {
exampleResult = result.examples[0]
}
}
else {
method.result = {
"name": "result",
"schema": {
"const": null
}
}
}
method.examples = method.examples.map( example => (
{
params: [
{
name: "parameters",
value: example.result.value.parameters
},
{
name: "correlationId",
value: example.result.value.correlationId
}
],
result: {
name: "result",
value: exampleResult
}
}
))
// remove event tag
method.tags = method.tags.filter(tag => tag.name !== 'event')
}
})
}
const addMissingTitles = ([k, v]) => {
if (v && !v.hasOwnProperty('title')) {
v.title = k
}
return v
}
// Maybe an array of <key, value> from the schema
const getSchemas = compose(
option([]),
chain(safe(isArray)),
map(Object.entries), // Maybe Array<Array<key, value>>
chain(safe(isObject)), // Maybe Object
getPath(['components', 'schemas']) // Maybe any
)
const getEnums = compose(
filter(x => x[1].enum),
getSchemas
)
const getTypes = compose(
// filter(x => !x.enum),
getSchemas
)
const isEventMethod = compose(
option(false),
map(_ => true),
chain(find(propEq('name', 'event'))),
getPath(['tags'])
)
const isEventMethodWithContext = compose(
and(
compose(
option(false),
map(_ => true),
chain(find(propEq('name', 'event'))),
getPath(['tags'])
),
compose(
map(params => {
return params.length > 1
}),
//propSatisfies('length', length => length > 1),
getPath(['params'])
)
)
)
const isPolymorphicPullMethod = compose(
option(false),
map(_ => true),
chain(find(hasProp('x-pulls-for'))),
getPath(['tags'])
)
const isTemporalSetMethod = compose(
option(false),
map(_ => true),
chain(find(propEq('name', 'temporal-set'))),
getPath(['tags'])
)
const isCallsMetricsMethod = compose(
option(false),
map(_ => true),
chain(find(propEq('name', 'calls-metrics'))),
getPath(['tags'])
)
const getMethodAttributes = compose(
option(null),
map(props => props.reduce( (val, item) => {
val[item['__key']] = item;
delete item['__key'];
return val
}, {})),
map(filter(hasProp('x-method'))),
map(props => props.map(([k, v]) => ({ "__key": k, ...v}))),
map(Object.entries),
map(schema => schema.items ? schema.items.properties || {} : schema.properties || {}),
getPath(['result', 'schema'])
)
const hasMethodAttributes = compose(
option(false),
map(_ => true),
chain(find(hasProp('x-method'))),
map(Object.values),
map(schema => schema.items ? schema.items.properties || {} : schema.properties || {}),
getPath(['result', 'schema'])
)
const isPublicEventMethod = and(
compose(
option(true),
map(_ => false),
chain(find(propEq('name', 'rpc-only'))),
getPath(['tags'])
),
compose(
option(false),
map(_ => true),
chain(find(propEq('name', 'event'))),
getPath(['tags'])
)
)
const isExcludedMethod = compose(
option(false),
map(_ => true),
chain(find(propEq('name', 'exclude-from-sdk'))),
getPath(['tags'])
)
const isRPCOnlyMethod = compose(
option(false),
map(_ => true),
chain(find(propEq('name', 'rpc-only'))),
getPath(['tags'])
)
const isPolymorphicReducer = compose(
option(false),
map(_ => true),
chain(find(propEq('name', 'polymorphic-reducer'))),
getPath(['tags'])
)
const isAllowFocusMethod = compose(
option(false),
map(_ => true),
chain(find(and(
hasProp('x-uses'),
propSatisfies('x-allow-focus', focus => (focus === true))
))),
getPath(['tags'])
)
const hasTitle = compose(
option(false),
map(isString),
getPath(['info', 'title'])
)
const hasExamples = compose(
option(false),
map(isObject),
getPath(['examples', 0])
)
const getParamsFromMethod = compose(
option([]),
getPath(['params'])
)
const getPayloadFromEvent = (event, appApi) => {
try {
if (event.result) {
const choices = (event.result.schema.oneOf || event.result.schema.anyOf)
if (choices) {
const choice = choices.find(schema => schema.title !== 'ListenResponse' && !(schema['$ref'] || '').endsWith('/ListenResponse'))
return choice
}
else if (appApi) {
const payload = getNotifier(event, appApi).params.slice(-1)[0].schema
return payload
}
else {
return event.result.schema
}
}
} catch (error) {
throw error
}
}
const getSetterFor = (property, json) => {
const fullProperty = `${json?.info?.title}.${property}`;
return json.methods && json.methods.find(m =>
m.tags && m.tags.find(t => t['x-setter-for'] === property || t['x-setter-for'] === fullProperty)
);
};
const getSubscriberFor = (property, json) => json.methods.find(m => m.tags && m.tags.find(t => t['x-alternative'] === property))
const providerHasNoParameters = (schema) => {
if (schema.allOf || schema.oneOf) {
return !!(schema.allOf || schema.oneOf).find(schema => providerHasNoParameters(schema))
}
else if (schema.properties && schema.properties.parameters) {
return isNull(schema.properties.parameters)
}
else {
console.dir(schema, {depth: 10})
throw "Invalid ProviderRequest"
}
}
const validEvent = and(
pathSatisfies(['name'], isString),
pathSatisfies(['name'], x => x.match(/on[A-Z]/))
)
// Pick events out of the methods array
const getEvents = compose(
option([]),
map(filter(validEvent)),
// Maintain the side effect of process.exit here if someone is violating the rules
map(map(e => {
if (!e.name.match(/on[A-Z]/)) {
console.error(`ERROR: ${e.name} method is tagged as an event, but does not match the pattern "on[A-Z]"`)
process.exit(1) // Non-zero exit since we don't want to continue. Useful for CI/CD pipelines.
}
return e
})),
inspector,
map(filter(isEventMethod)),
getMethods
)
const getPublicEvents = compose(
map(filter(isPublicEventMethod)),
getEvents
)
const hasPublicInterfaces = json => json.methods && json.methods.filter(m => m.tags && m.tags.find(t=>t['x-provides'])).length > 0
const hasPublicAPIs = json => hasPublicInterfaces(json) || (json.methods && json.methods.filter( method => !method.tags.find(tag => tag.name === 'rpc-only')).length > 0)
const hasAllowFocusMethods = json => json.methods && json.methods.filter(m => isAllowFocusMethod(m)).length > 0
const eventDefaults = event => {
event.tags = [
{
'name': 'notifier'
}
]
return event
}
const createEventResultSchemaFromProperty = (property, type='Changed') => {
const subscriberType = property.tags.map(t => t['x-subscriber-type']).find(t => typeof t === 'string') || 'context'
const caps = property.tags.find(t => t.name === 'capabilities')
let name = caps['x-provided-by'] ? caps['x-provided-by'].split('.').pop().replace('onRequest', '') : property.name
name = name.charAt(0).toUpperCase() + name.substring(1)
if ( subscriberType === 'global') {
// wrap the existing result and the params in a new result object
const schema = {
title: methodRename(property, name => name.charAt(0).toUpperCase() + name.substring(1) + type + 'Info').split('.').pop(),
type: "object",
properties: {
},
required: []
}
// add all of the params
property.params.filter(p => p.name !== 'listen').forEach(p => {
schema.properties[p.name] = p.schema
schema.required.push(p.name)
})
// add the result (which might override a param of the same name)
schema.properties[property.result.name] = property.result.schema
!schema.required.includes(property.result.name) && schema.required.push(property.result.name)
return schema
}
}
const createEventFromProperty = (property, type='', alternative, json) => {
const provider = (property.tags.find(t => t['x-provided-by']) || {})['x-provided-by']
const pusher = provider ? provider.replace('onRequest', '').split('.').map((x, i, arr) => (i === arr.length-1) ? x.charAt(0).toLowerCase() + x.substr(1) : x).join('.') : undefined
const event = eventDefaults(JSON.parse(JSON.stringify(property)))
// event.name = (module ? module + '.' : '') + 'on' + event.name.charAt(0).toUpperCase() + event.name.substr(1) + type
event.name = provider ? provider.split('.').pop().replace('onRequest', '') : event.name.charAt(0).toUpperCase() + event.name.substr(1) + type
event.name = event.name.split('.').map((x, i, arr) => (i === arr.length-1) ? 'on' + x.charAt(0).toUpperCase() + x.substr(1) : x).join('.')
const subscriberFor = pusher || (json.info.title + '.' + property.name)
const old_tags = JSON.parse(JSON.stringify(property.tags))
alternative && (event.tags[0]['x-alternative'] = alternative)
!provider && event.tags.unshift({
name: "subscriber",
'x-subscriber-for': subscriberFor
})
const subscriberType = property.tags.map(t => t['x-subscriber-type']).find(t => typeof t === 'string') || 'context'
// if the subscriber type is global, zap all of the parameters and change the result type to the schema that includes them
if (subscriberType === 'global') {
// wrap the existing result and the params in a new result object
const result = {
name: "data",
schema: {
$ref: "#/components/schemas/" + event.name.substring(2) + 'Info'
}
}
event.examples.map(example => {
const result = {}
example.params.filter(p => p.name !== 'listen').forEach(p => {
result[p.name] = p.value
})
result[example.result.name] = example.result.value
example.params = example.params.filter(p => p.name === 'listen')
example.result.name = "data"
example.result.value = result
})
event.result = result
// remove the params
event.params = event.params.filter(p => p.name === 'listen')
}
old_tags.forEach(t => {
if (t.name !== 'property' && !t.name.startsWith('property:') && t.name !== 'push-pull')
{
event.tags.push(t)
}
})
provider && (event.tags.find(t => t.name === 'capabilities')['x-provided-by'] = subscriberFor)
return event
}
const createNotifierFromProperty = (property, type='Changed') => {
const subscriberType = property.tags.map(t => t['x-subscriber-type']).find(t => typeof t === 'string') || 'context'
const notifier = JSON.parse(JSON.stringify(property))
notifier.name = methodRename(notifier, name => name + type)
Object.assign(notifier.tags.find(t => t.name.startsWith('property')), {
name: 'notifier',
'x-notifier-for': property.name,
'x-event': methodRename(notifier, name => 'on' + name.charAt(0).toUpperCase() + name.substring(1))
})
if (subscriberType === 'global') {
notifier.params = [
{
name: "info",
schema: {
"$ref": "#/components/schemas/" + methodRename(notifier, name => name.charAt(0).toUpperCase() + name.substr(1) + 'Info')
}
}
]
}
else {
notifier.params.push(notifier.result)
}
delete notifier.result
if (subscriberType === 'global') {
notifier.examples = property.examples.map(example => ({
name: example.name,
params: [
{
name: "info",
value: Object.assign(Object.fromEntries(example.params.map(p => [p.name, p.value])), Object.fromEntries([[example.result.name, example.result.value]]))
}
]
}))
}
else {
notifier.examples.forEach(example => {
example.params.push(example.result)
delete example.result
})
}
return notifier
}
// create foo() notifier from onFoo() event
const createNotifierFromEvent = (event, json) => {
const push = JSON.parse(JSON.stringify(event))
const caps = push.tags.find(t => t.name === 'capabilities')
push.name = caps['x-provided-by']
delete caps['x-provided-by']
caps['x-provides'] = caps['x-uses'].pop()
delete caps['x-uses']
push.tags = push.tags.filter(t => t.name !== 'event')
push.result.required = true
push.params.push(push.result)
push.result = {
"name": "result",
"schema": {
"type": "null"
}
}
push.examples.forEach(example => {
example.params.push(example.result)
example.result = {
"name": "result",
"value": null
}
})
return push
}
const createPushEvent = (requestor, json) => {
return createEventFromProperty(requestor, '', undefined, json)
}
const createPullEventFromPush = (pusher, json) => {
const event = JSON.parse(JSON.stringify(pusher))
event.params = []
event.name = methodRename(event, name => 'pull' + name.charAt(0).toUpperCase() + name.substr(1))
const old_tags = pusher.tags.concat()
event.tags = [
{
name: "notifier",
'x-event': methodRename(pusher, name => 'onPull' + name.charAt(0).toUpperCase() + name.substr(1))
}
]
event.tags[0]['x-pulls-for'] = pusher.name
event.tags.unshift({
name: 'polymorphic-pull-event'
})
const requestType = methodRename(pusher, name => name.charAt(0).toUpperCase() + name.substr(1) + "FederatedRequest")
event.params.push({
name: "request",
summary: "A " + requestType + " object.",
schema: {
"$ref": "#/components/schemas/" + requestType
}
})
delete event.result
const exampleResult = {
name: "request",
value: JSON.parse(JSON.stringify(getPathOr(null, ['components', 'schemas', requestType, 'examples', 0], json)))
}
event.examples && event.examples.forEach(example => {
delete example.result
example.params = [
exampleResult
]
})
old_tags.forEach(t => {
if (t.name !== 'polymorphic-pull' && t.name)
{
event.tags.push(t)
}
})
return event
}
const createPullProvider = (requestor) => {
const provider = JSON.parse(JSON.stringify(requestor))
provider.name = requestor.tags.find(t => t['x-provided-by'])['x-provided-by']
const old_tags = JSON.parse(JSON.stringify(requestor.tags))
const caps = provider.tags.find(t => t.name === 'capabilities')
caps['x-provides'] = caps['x-uses'].pop() || caps['x-manages'].pop()
caps['x-requestor'] = requestor.name
delete caps['x-uses']
delete caps['x-manages']
delete caps['x-provided-by']
return provider
}
const createPullProviderParams = (requestor) => {
const copy = JSON.parse(JSON.stringify(requestor))
// grab onRequest<foo> and turn into <foo>
const name = copy.tags.find(t => t['x-provided-by'])['x-provided-by'].split('.').pop().substring(9)
const paramsSchema = {
"title": name.charAt(0).toUpperCase() + name.substr(1) + "ProviderParameters",
"type": "object",
"required": [],
"properties": {
},
"additionalProperties": false
}
copy.params.forEach(p => {
paramsSchema.properties[p.name] = p.schema
if (p.required) {
paramsSchema.required.push(p.name)
}
})
return paramsSchema
}
const createPullRequestor = (pusher, json) => {
const module = pusher.tags.find(t => t.name === 'push-pull')['x-requesting-interface']
const requestor = JSON.parse(JSON.stringify(pusher))
requestor.name = (module ? module + '.' : '') + 'request' + requestor.name.charAt(0).toUpperCase() + requestor.name.substr(1)
const value = requestor.params.pop()
delete value.required
requestor.tags = requestor.tags.filter(t => t.name !== 'push-pull')
requestor.tags.unshift({
"name": "requestor",
"x-requestor-for": json.info.title + '.' + pusher.name
})
const caps = requestor.tags.find(t => t.name === 'capabilities')
caps['x-provided-by'] = json.info.title + '.' + pusher.name
caps['x-uses'] = [ caps['x-provides'] ]
delete caps['x-provides']
requestor.tags.find(t => t.name === 'capabilities')['x-provided-by'] = json.info.title + '.' + pusher.name
requestor.result = value
requestor.examples.forEach(example => {
example.result = example.params.pop()
})
return requestor
}
const createTemporalEventMethod = (method, json, name) => {
const event = createEventFromMethod(method, json, name, 'x-temporal-for', ['temporal-set'])
// copy the array items schema to the main result for individual events
event.result.schema = method.result.schema.items
event.tags = event.tags.filter(t => t.name !== 'temporal-set')
event.params.unshift({
name: "correlationId",
required: true,
schema: {
type: "string"
}
})
event.examples && event.examples.forEach(example => {
example.params.unshift({
name: "correlationId",
value: "xyz"
})
example.result.value = example.result.value[0]
})
return event
}
const createEventFromMethod = (method, json, name, correlationExtension, tagsToRemove = []) => {
const event = eventDefaults(JSON.parse(JSON.stringify(method)))
event.name = methodRename(event, _ => 'on' + name)
const old_tags = JSON.parse(JSON.stringify(method.tags))
event.tags[0][correlationExtension] = method.name
event.tags.unshift({
name: 'rpc-only'
})
old_tags.forEach(t => {
if (!tagsToRemove.find(t => tagsToRemove.includes(t.name)))
{
event.tags.push(t)
}
})
return event
}
const createTemporalStopMethod = (method, jsoname) => {
const stop = JSON.parse(JSON.stringify(method))
stop.name = methodRename(stop, name => 'stop' + name.charAt(0).toUpperCase() + name.substr(1))
stop.tags = stop.tags.filter(tag => tag.name !== 'temporal-set')
stop.tags.unshift({
name: "rpc-only"
})
// copy the array items schema to the main result for individual events
stop.result.name = "result"
stop.result.schema = {
type: "null"
}
stop.params = [{
name: "correlationId",
required: true,
schema: {
type: "string"
}
}]
stop.examples && stop.examples.forEach(example => {
example.params = [{
name: "correlationId",
value: "xyz"
}]
example.result = {
name: "result",
value: null
}
})
return stop
}
const createSetterFromProperty = property => {
const setter = JSON.parse(JSON.stringify(property))
setter.name = methodRename(setter, name => 'set' + name.charAt(0).toUpperCase() + name.substr(1))
const old_tags = setter.tags
setter.tags = [
{
'name': 'setter',
'x-setter-for': property.name
}
]
const param = setter.result
param.name = 'value'
param.required = true
setter.params.push(param)
setter.result = {
name: 'result',
schema: {
type: "null"
}
}
setter.examples && setter.examples.forEach(example => {
example.params.push({
name: 'value',
value: example.result.value
})
example.result.value = null
})
old_tags.forEach(t => {
if (t.name !== 'property' && !t.name.startsWith('property:'))
{
if (t.name === 'capabilities') {
setter.tags.push({
name: 'capabilities',
'x-manages': t['x-uses'] || t['x-manages']
})
} else {
setter.tags.push(t)
}
}
})
return setter
}
const createFocusFromProvider = provider => {
const ready = JSON.parse(JSON.stringify(provider))
ready.name = methodRename(ready, name => name.charAt(9).toLowerCase() + name.substr(10) + 'Focus')
ready.summary = `Internal API for ${methodName(provider).substr(9)} Provider to request focus for UX purposes.`
ready.tags = ready.tags.filter(t => t.name !== 'event')
ready.tags.find(t => t.name === 'capabilities')['x-allow-focus-for'] = provider.name
ready.params = []
ready.result = {
name: 'result',
schema: {
type: "null"
}
}
ready.examples = [
{
name: "Example",
params: [],
result: {
name: "result",
value: null
}
}
]
return ready
}
// type = Response | Error
const createResponseFromProvider = (provider, type, json) => {
const response = JSON.parse(JSON.stringify(provider))
response.name = methodRename(response, name => name.charAt(9).toLowerCase() + name.substr(10) + type)
response.summary = `Internal API for ${methodName(provider).substr(9)} Provider to send back ${type.toLowerCase()}.`
response.tags = response.tags.filter(t => t.name !== 'event')
response.tags.find(t => t.name === 'capabilities')[`x-${type.toLowerCase()}-for`] = provider.name
const paramExamples = []
if (provider.tags.find(t => t[`x-${type.toLowerCase()}`])) {
response.params = [
{
name: "correlationId",
schema: {
type: "string"
},
required: true
},
{
name: type === 'Error' ? 'error' : "result",
schema: provider.tags.find(t => t[`x-${type.toLowerCase()}`])[`x-${type.toLowerCase()}`],
required: true
}
]
if (!provider.tags.find(t => t['x-error'])) {
provider.tags.find(t => t.name === 'event')['x-error'] = {
//"$ref": "https://meta.open-rpc.org/#definitions/errorObject"
// TODO: replace this with ref above (requires merge of `fix/rpc.discover`)
"type": "object",
"additionalProperties": false,
"required": [
"code",
"message"
],
"properties": {
"code": {
"title": "errorObjectCode",
"description": "A Number that indicates the error type that occurred. This MUST be an integer. The error codes from and including -32768 to -32000 are reserved for pre-defined errors. These pre-defined errors SHOULD be assumed to be returned from any JSON-RPC api.",
"type": "integer"
},
"message": {
"title": "errorObjectMessage",
"description": "A String providing a short description of the error. The message SHOULD be limited to a concise single sentence.",
"type": "string"
},
"data": {
"title": "errorObjectData",
"description": "A Primitive or Structured value that contains additional information about the error. This may be omitted. The value of this member is defined by the Server (e.g. detailed error information, nested errors etc.)."
}
}
}
}
const schema = localizeDependencies(provider.tags.find(t => t[`x-${type.toLowerCase()}`])[`x-${type.toLowerCase()}`], json)
let n = 1
if (schema.examples && schema.examples.length) {
paramExamples.push(... (schema.examples.map( param => ({
name: schema.examples.length === 1 ? "Example" : `Example #${n++}`,
params: [
{
name: 'correlationId',
value: '123'
},
{
name: 'result',
value: param
}
],
result: {
name: 'result',
value: null
}
})) || []))
delete schema.examples
}
else if (schema['$ref']) {
paramExamples.push({
name: 'Generated Example',
params: [
{
name: `${type.toLowerCase()}`,
value: {
correlationId: "123",
result: {
'$ref': schema['$ref'] + '/examples/0'
}
}
}
],
result: {
name: 'result',
value: null
}
})
}
}
if (paramExamples.length === 0) {
const value = type === 'Error' ? { code: 1, message: 'Error' } : {}
paramExamples.push(
{
name: 'Example 1',
params: [
{
name: 'correlationId',
value: '123'