This repository has been archived by the owner on Jan 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathview_model.ts
275 lines (241 loc) · 8.78 KB
/
view_model.ts
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
import * as ko from 'knockout'
import * as amf from 'amf-client-js'
import { CommonViewModel } from '../view_models/common_view_model'
import { LoadModal, LoadFileEvent } from '../view_models/load_modal'
import { WebApiParser as wap } from 'webapi-parser'
import { UI } from "../view_models/ui";
import AnyShape = amf.model.domain.AnyShape
export type NavigatorSection = 'shapes' | 'errors'
interface Shape {
id: string,
target: string,
message: string,
isCustom: boolean
}
const createModel = function (text, mode) {
return globalThis.monaco.editor.createModel(text, mode)
}
export class ViewModel extends CommonViewModel {
public env: amf.client.environment.Environment = null;
public navigatorSection: ko.Observable<NavigatorSection> = ko.observable<NavigatorSection>('errors');
public shapes: ko.ObservableArray<Shape> = ko.observableArray<Shape>([]);
public errors: ko.ObservableArray<amf.client.validate.ValidationResult> = ko.observableArray<amf.client.validate.ValidationResult>([]);
public selectedModel: ko.Observable<amf.model.document.BaseUnit|null> = ko.observable(null);
public editorSection: ko.Observable<string> = ko.observable<string>('raml');
public validationSection: ko.Observable<string> = ko.observable<string>('custom');
public customValidation?: string;
public selectedError: ko.Observable<any> = ko.observable<any>();
public errorsMapShape: {[id: string]: boolean} = {};
public model: any | null = null;
public modelSyntax: string | null = null;
public modelText: string | null = null;
public changesFromLastUpdate = 0;
public documentModelChanged = false;
public RELOAD_PERIOD = 1000;
public ui: UI = new UI();
public ramlParser?
public profileName: amf.ProfileName;
public profilePath: string = 'http://a.ml/amf/default_document';
public init (): Promise<any> {
return amf.AMF.init()
}
public constructor (public profileEditor: any, public ramlEditor: any) {
super()
this.ramlParser = amf.AMF.raml10Parser()
const parsingApiFn = () => {
if (this.editorSection() === 'raml') {
const toParse = ramlEditor.getValue()
this.ramlParser.parseStringAsync(toParse).then((parsed: amf.model.document.Document) => {
this.selectedModel(parsed)
const oldErrors = this.errors()
try {
this.doValidate()
} catch (e) {
console.error(`Exception parsing API: ${e}`)
this.errors(oldErrors)
}
}).catch((e) => {
console.error(`Exception parsing API: ${e}`)
})
}
}
const parsingProfileFn = (cb?: () => void) => {
if (this.validationSection() === 'custom') {
return amf.AMF.loadValidationProfile(this.profilePath, this.getEnv())
.then((profileName) => {
this.profileName = profileName
this.loadShapes()
if (cb) {
cb()
} else {
this.doValidate()
}
})
}
}
this.editorSection.subscribe((section) => this.onEditorSectionChange(section))
this.validationSection.subscribe((section) => this.onValidationSectionChange(section))
this.init()
.then(() => parsingProfileFn(parsingApiFn))
.then(() => {
return this.loadShapes()
}).catch((e) => {
console.error(`Error: ${e}`)
})
ramlEditor.onDidChangeModelContent(() => {
this.changesFromLastUpdate++
this.documentModelChanged = true;
((number) => {
setTimeout(() => {
if (this.changesFromLastUpdate === number) {
this.changesFromLastUpdate = 0
parsingApiFn()
}
}, this.RELOAD_PERIOD)
})(this.changesFromLastUpdate)
})
profileEditor.onDidChangeModelContent(() => {
this.changesFromLastUpdate++
this.documentModelChanged = true;
((number) => {
setTimeout(() => {
if (this.changesFromLastUpdate === number) {
this.changesFromLastUpdate = 0
parsingProfileFn()
}
}, this.RELOAD_PERIOD)
})(this.changesFromLastUpdate)
})
this.loadModal.on(LoadModal.LOAD_FILE_EVENT, (evt: LoadFileEvent) => {
return wap.raml10.parse(evt.location)
.then((parsedModel) => {
this.getMainModel().setValue(parsedModel.raw)
this.validationSection('custom')
parsingProfileFn()
})
})
}
public getEnv () {
const profilePath = this.profilePath
const editor = this.profileEditor
const EditorProfileLoader = {
fetch: function (resource: string): Promise<amf.client.remote.Content> {
return new Promise(function (resolve, reject) {
resolve(new amf.client.remote.Content(
editor.getValue(), profilePath))
})
},
accepts: function (resource: string): boolean {
return true
}
}
const env = new amf.client.environment.Environment()
return env.addClientLoader(EditorProfileLoader)
}
public hasError (shape: AnyShape): boolean {
const errors = this.errorsMapShape || {}
return errors[(shape.id || '').split('#').pop()] || false
}
public selectError (error: any) {
if (this.selectedError() == null || this.selectedError().id !== error.id) {
this.selectedError(error)
}
}
public apply () {
globalThis.viewModel = this
ko.applyBindings(this)
}
public doValidate () {
const model = this.selectedModel()
if (model != null) {
this.ramlParser.reportValidation((this.profileName || 'RAML 1.0'), 'RAML').then((report) => {
var violations = report.results.filter((result) => {
return result.level === 'Violation'
})
const editorModel = this.ramlEditor.getModel()
const monacoErrors = report.results.map((result) => this.buildMonacoErro(result))
globalThis.monaco.editor.setModelMarkers(editorModel, editorModel.id, monacoErrors)
this.errors(violations)
this.errorsMapShape = this.errors()
.map(e => {
return e.validationId.split('#').pop()
})
.reduce((a, s) => { a[s] = true; return a }, {})
globalThis.resizeFn()
}).catch((e) => {
console.error(`Error validating API: ${e}`)
})
}
}
private onEditorSectionChange (section: string) {
if (this.selectedModel() !== null) {
if (section === 'raml') {
amf.Core.generator('RAML 1.0', 'application/yaml').generateString(this.selectedModel())
.then((generated) => {
this.ramlEditor.setModel(createModel(generated, 'yaml'))
})
} else if (section === 'api-model') {
amf.AMF.amfGraphGenerator().generateString(this.selectedModel(), new amf.render.RenderOptions().withCompactUris)
.then((generated) => {
const json = JSON.parse(generated)
this.ramlEditor.setModel(createModel(JSON.stringify(json, null, 2), 'json'))
})
}
globalThis.resizeFn()
}
}
private onValidationSectionChange (section: string) {
if (section === 'custom') {
this.profileEditor.setModel(createModel(this.customValidation, 'yaml'))
} else {
this.customValidation = this.profileEditor.getValue()
const shapes = amf.AMF.emitShapesGraph(this.profileName)
const json = JSON.parse(shapes)
this.profileEditor.setModel(createModel(JSON.stringify(json, null, 2), 'json'))
}
}
Hint = 1;
Info = 2;
Warning = 4;
Error = 8;
protected buildMonacoErro (error: amf.client.validate.ValidationResult): any {
let severity = this.Info
if (error.level == 'Violation') { severity = this.Error }
if (error.level === 'Warning') { severity = this.Warning }
const startLineNumber = error.position.start.line
const startColumn = error.position.start.column
const endLineNumber = error.position.end.line
const endColumn = error.position.end.column
const message = error.message
return {
severity, // hardcoded error severity
startLineNumber,
startColumn,
endLineNumber,
endColumn,
message
}
}
protected loadShapes () {
const shapes = amf.AMF.emitShapesGraph(this.profileName)
const shapesModels = JSON.parse(shapes).map((n) => {
const id = n['@id'].split('#').pop()
const isCustom = n['@id'].indexOf('amf/parser#') > -1
const message = (n['http://www.w3.org/ns/shacl#message'] || {})['@value'] || ''
const targetId = ((n['http://www.w3.org/ns/shacl#targetClass'] || [])[0] || {})['@id'] || ''
const target = this.ui.bindingLabel({ token: 'uri', value: targetId })
return {
id,
target,
isCustom,
message
}
})
this.shapes(shapesModels)
}
public getMainModel (): any {
return this.ramlEditor.getModel()
}
public parseEditorSection () {}
public updateEditorsModels () {}
}