-
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathHelpers.ts
More file actions
223 lines (199 loc) · 7.49 KB
/
Helpers.ts
File metadata and controls
223 lines (199 loc) · 7.49 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
import * as _ from 'lodash'
import YAML from 'js-yaml'
import { OptimizableComponentGroup, NewReport, ReportElement, OptimizableComponent } from 'types'
/**
* Checks if a component's parent is a ref or not.
*/
export const hasParent = (reportElement: ReportElement, asyncapiFile: any): boolean => {
const childPath = reportElement.path
const parentPath = childPath.substring(0, childPath.lastIndexOf('.'))
const parent = _.get(asyncapiFile, parentPath)
return !_.has(parent, '$ref')
}
export const createReport = (
reportFn: (optimizableComponent: OptimizableComponentGroup) => ReportElement[],
optimizeableComponents: OptimizableComponentGroup[],
reporterType: string
): NewReport => {
const elements = optimizeableComponents
.map((optimizeableComponent) => reportFn(optimizeableComponent))
.flat()
const type = reporterType
return { type, elements }
}
export const sortReportElements = (report: NewReport): NewReport => {
report.elements.sort((a, b) => a.action.length - b.action.length || b.path.length - a.path.length)
return report
}
// Utility function to get all targets of reports with type 'reuseComponents'
const getReuseComponentTargets = (
reports: { type: string; elements: ReportElement[] }[]
): Set<string> => {
const targets = new Set<string>()
for (const report of reports) {
if (report.type === 'reuseComponents') {
for (const element of report.elements) {
if (element.target) {
targets.add(element.target)
}
}
}
}
return targets
}
// Main function to filter report elements
export const filterReportElements = (
reports: { type: string; elements: ReportElement[] }[]
): NewReport[] => {
const reuseTargets = getReuseComponentTargets(reports)
return reports.map((report) => {
if (report.type === 'removeComponents') {
const filteredElements = report.elements.filter((element) => {
return !reuseTargets.has(element.path)
})
return { type: report.type, elements: filteredElements }
}
return report
})
}
const isExtension = (fieldName: string): boolean => {
return fieldName.startsWith('x-')
}
const backwardsCheck = (x: any, y: any): boolean => {
for (const p in y) {
if (_.has(y, p) && !_.has(x, p)) {
return false
}
}
return true
}
const compareComponents = (x: any, y: any): boolean => {
// if they are not strictly equal, they both need to be Objects
if (!(x instanceof Object) || !(y instanceof Object)) {
return false
}
for (const p in x) {
//extensions have different values for objects that are equal (duplicated.) If you don't skip the extensions this function always returns false.
if (isExtension(p)) {
continue
}
if (!_.has(x, p)) {
continue
}
// allows to compare x[ p ] and y[ p ] when set to undefined
if (!_.has(y, p)) {
return false
}
// if they have the same strict value or identity then they are equal
if (x[String(p)] === y[String(p)]) {
continue
}
// Numbers, Strings, Functions, Booleans must be strictly equal
if (typeof x[String(p)] !== 'object') {
return false
}
// Objects and Arrays must be tested recursively
if (!compareComponents(x[String(p)], y[String(p)])) {
return false
}
}
return backwardsCheck(x, y)
}
/**
*
* @param component1 The first component that you want to compare with the second component.
* @param component2 The second component.
* @param referentialEqualityCheck If `true` the function will return true if the two components have referential equality OR they have the same structure. If `false` the it will only return true if they have the same structure but they are NOT referentially equal.
* @returns whether the two components are equal.
*/
const isEqual = (component1: any, component2: any, referentialEqualityCheck: boolean): boolean => {
if (referentialEqualityCheck) {
return component1 === component2 || compareComponents(component1, component2)
}
return component1 !== component2 && compareComponents(component1, component2)
}
/**
* checks if a component is located in `components` section of an asyncapi document.
*/
const isInComponents = (optimizableComponent: OptimizableComponent): boolean => {
return optimizableComponent.path.startsWith('components.')
}
/**
* checks if a component is located in `channels` section of an asyncapi document.
*/
const isInChannels = (component: OptimizableComponent): boolean => {
return component.path.startsWith('channels.')
}
/**
* Converts JSON or YAML string object.
*/
const toJS = (asyncapiYAMLorJSON: any): any => {
if (asyncapiYAMLorJSON.constructor && asyncapiYAMLorJSON.constructor.name === 'Object') {
//NOTE: this approach can have problem with circular references between object and JSON.stringify doesn't support it.
//more info: https://github.com/asyncapi/parser-js/issues/293
return JSON.parse(JSON.stringify(asyncapiYAMLorJSON))
}
if (typeof asyncapiYAMLorJSON === 'string') {
return YAML.load(asyncapiYAMLorJSON)
}
throw new Error(
'Unknown input: Please make sure that your input is an Object/String of a valid AsyncAPI specification document.'
)
}
/**
* Converts a lodash path (potentially with bracket notation) to an array of path segments.
* e.g., "channels['user.fifo'].publish.message" → ["channels", "user.fifo", "publish", "message"]
*/
const lodashPathToSegments = (lodashPath: string): string[] => {
// lodash already supports parsing bracket notation and numeric indices safely.
// Examples:
// - _.toPath("channels['user.fifo'].publish") => ["channels","user.fifo","publish"]
// - _.toPath("channels.myChannel.messages[0]") => ["channels","myChannel","messages","0"]
return _.toPath(lodashPath).map((segment) => String(segment))
}
const getComponentName = (component: OptimizableComponent): string => {
let componentName
if (component.component['x-origin']) {
componentName = String(component.component['x-origin']).split('/').reverse()[0]
} else {
// Use lodashPathToSegments to properly handle bracket notation paths
// e.g., "operations['user/deleteAccount.subscribe']" should return "user/deleteAccount.subscribe"
const segments = lodashPathToSegments(component.path)
componentName = segments[segments.length - 1]
}
return componentName
}
/**
* Converts a property name to a lodash path segment.
* Uses bracket notation if the name contains a dot to prevent lodash from
* interpreting it as nested properties.
* e.g., "user.fifo" → "['user.fifo']", "simple" → "simple"
*/
const toLodashPathSegment = (name: string): string => {
if (name.includes('.')) {
return `['${name}']`
}
return name
}
/**
* Escapes special characters for JSON Pointer format.
* According to RFC 6901:
* - '~' must be escaped as '~0'
* - '/' must be escaped as '~1'
*/
const escapeJsonPointerSegment = (segment: string): string => {
return segment.replace(/~/g, '~0').replace(/\//g, '~1')
}
/**
* Converts a lodash path (potentially with bracket notation) to a JSON Pointer format.
* This handles paths like: channels['user.fifo'].publish.message
* And converts them to: channels/user.fifo/publish/message
*
* Special characters in segment values are escaped according to RFC 6901:
* - '~' → '~0'
* - '/' → '~1'
*/
const lodashPathToJsonPointer = (lodashPath: string): string => {
return lodashPathToSegments(lodashPath).map(escapeJsonPointerSegment).join('/')
}
export { compareComponents, isEqual, isInComponents, isInChannels, toJS, getComponentName, lodashPathToJsonPointer, toLodashPathSegment }