mapping.ts
TypeScript · 210 рядків
1import { literalType } from './action.ts'
2
3const clone = value => value === undefined ? undefined : JSON.parse(JSON.stringify(value))
4
5function get(value, path) {
6 return path.reduce((current, key) => current?.[key], value)
7}
8
9function set(value, path, next) {
10 const keys = path.split('.')
11 const last = keys.pop()
12 const target = keys.reduce((current, key) => current[key] ??= {}, value)
13 target[last] = next
14}
15
16function parseSource(source, scope = 'data') {
17 if (typeof source !== 'string') return null
18 if (source === '$data') return { root: 'data', path: [] }
19 if (source.startsWith('$data.')) return { root: 'data', path: source.slice(6).split('.') }
20
21 for (const root of ['data', 'task', 'event', 'parent']) {
22 if (source === root) return { root, path: [] }
23 if (source.startsWith(`${root}.`)) return { root, path: source.slice(root.length + 1).split('.') }
24 }
25
26 if (scope === 'item') {
27 if (source === 'item') return { root: 'item', path: [] }
28 if (source.startsWith('item.')) return { root: 'item', path: source.slice(5).split('.') }
29 }
30 return null
31}
32
33function sourceRoot(root, data, item, scopes) {
34 if (root === 'data') return data
35 if (root === 'item') return item
36 return scopes?.[root]
37}
38
39function sourceValue(data, source, item, scope = 'data', scopes: any = {}) {
40 const parsed = parseSource(source, scope)
41 if (!parsed) return undefined
42 return parsed.path.length
43 ? get(sourceRoot(parsed.root, data, item, scopes), parsed.path)
44 : sourceRoot(parsed.root, data, item, scopes)
45}
46
47/** Літерал у мапінгу (P3, R-23 §11): { "$value": "SUPPLY_RECEIVED" } — константа замість шляху до даних. */
48function isLiteral(value) {
49 return value
50 && typeof value === 'object'
51 && !Array.isArray(value)
52 && Object.keys(value).length === 1
53 && '$value' in value
54}
55
56function isMap(value) {
57 return value
58 && typeof value === 'object'
59 && !Array.isArray(value)
60 && Object.keys(value).includes('$map')
61}
62
63export function resolveMappingValue(definition, data, item, scope = 'data', scopes: any = {}) {
64 if (typeof definition === 'string') {
65 return clone(sourceValue(data, definition, item, scope, scopes))
66 }
67 if (isLiteral(definition)) return clone(definition.$value)
68 if (isMap(definition)) {
69 const collection = sourceValue(data, definition.$map, item, scope, scopes)
70 if (!Array.isArray(collection)) return undefined
71 return collection.map(entry => resolveMappingValue(definition.value, data, entry, 'item', scopes))
72 }
73 if (scope === 'item' && definition && typeof definition === 'object' && !Array.isArray(definition)) {
74 return Object.fromEntries(
75 Object.entries(definition).map(([key, value]) => [
76 key,
77 resolveMappingValue(value, data, item, scope, scopes)
78 ])
79 )
80 }
81 return undefined
82}
83
84function deriveValueSchema(definition, inputSchema, itemSchema, scope = 'data', scopeSchemas: any = {}) {
85 if (typeof definition === 'string') {
86 return sourceValue(inputSchema, definition, itemSchema, scope, scopeSchemas) ?? 'unknown'
87 }
88 if (isLiteral(definition)) return literalType(definition.$value)
89 if (isMap(definition)) {
90 const collection = sourceValue(inputSchema, definition.$map, itemSchema, scope, scopeSchemas)
91 const entry = Array.isArray(collection) ? collection[0] : undefined
92 return [deriveValueSchema(definition.value, inputSchema, entry, 'item', scopeSchemas)]
93 }
94 if (scope === 'item' && definition && typeof definition === 'object' && !Array.isArray(definition)) {
95 return Object.fromEntries(
96 Object.entries(definition).map(([key, value]) => [
97 key,
98 deriveValueSchema(value, inputSchema, itemSchema, scope, scopeSchemas)
99 ])
100 )
101 }
102 return 'unknown'
103}
104
105function validateValue(
106 definition,
107 inputSchema,
108 errors,
109 label,
110 itemSchema,
111 scope = 'data',
112 scopeSchemas = {}
113) {
114 if (typeof definition === 'string') {
115 const parsed = parseSource(definition, scope)
116 if (!parsed) {
117 errors.push(`${label}: source must use $data, data.*, task.*, event.*${scope === 'item' ? ', item, or item.*' : ''}`)
118 return
119 }
120 const root = sourceRoot(parsed.root, inputSchema, itemSchema, scopeSchemas)
121 if (parsed.path.length && get(root, parsed.path) === undefined) {
122 errors.push(`${label}: unknown source "${definition}"`)
123 }
124 return
125 }
126
127 if (isLiteral(definition)) return
128
129 if (isMap(definition)) {
130 const parsed = parseSource(definition.$map, scope)
131 if (!parsed) {
132 errors.push(`${label}.$map: source must reference an array`)
133 return
134 }
135 const root = sourceRoot(parsed.root, inputSchema, itemSchema, scopeSchemas)
136 const collection = parsed.path.length ? get(root, parsed.path) : root
137 if (collection === undefined) {
138 errors.push(`${label}.$map: unknown source "${definition.$map}"`)
139 } else if (!Array.isArray(collection)) {
140 errors.push(`${label}.$map: source must be an array`)
141 }
142 if (!('value' in definition)) {
143 errors.push(`${label}.$map: value is required`)
144 } else {
145 validateValue(
146 definition.value,
147 inputSchema,
148 errors,
149 `${label}.value`,
150 Array.isArray(collection) ? collection[0] : undefined,
151 'item',
152 scopeSchemas
153 )
154 }
155 for (const key of Object.keys(definition)) {
156 if (!['$map', 'value'].includes(key)) {
157 errors.push(`${label}: unsupported $map property "${key}"`)
158 }
159 }
160 return
161 }
162
163 if (scope === 'item' && definition && typeof definition === 'object' && !Array.isArray(definition)) {
164 for (const [key, value] of Object.entries(definition)) {
165 validateValue(value, inputSchema, errors, `${label}.${key}`, itemSchema, scope, scopeSchemas)
166 }
167 return
168 }
169
170 errors.push(
171 scope === 'data'
172 ? `${label}: source must be $data, $data.*, a legacy data.* path, or { "$value": constant }`
173 : `${label}: mapping value must use item.*, data.*, task.*, event.*, an object, or $map`
174 )
175}
176
177export function buildMappedData(mapping, data, scopes: any = {}) {
178 const result = mapping?.$copy === 'data' ? clone(data) : {}
179 for (const [target, definition] of Object.entries(mapping || {})) {
180 if (target === '$copy') continue
181 set(result, target, resolveMappingValue(definition, data, undefined, 'data', scopes))
182 }
183 return result
184}
185
186export function deriveMappingSchema(mapping, inputSchema, scopeSchemas: any = {}) {
187 const result = mapping?.$copy === 'data' ? clone(inputSchema) : {}
188 for (const [target, definition] of Object.entries(mapping || {})) {
189 if (target === '$copy') continue
190 set(result, target, deriveValueSchema(definition, inputSchema, undefined, 'data', scopeSchemas))
191 }
192 return result
193}
194
195export function validateMapping(mapping, inputSchema, scopeSchemas: any = {}) {
196 const errors = []
197 if (!mapping || typeof mapping !== 'object' || Array.isArray(mapping)) {
198 return { valid: false, errors: ['Mapping must be a JSON object'] }
199 }
200 if ('$copy' in mapping && mapping.$copy !== 'data') {
201 errors.push('$copy must equal "data"')
202 }
203 for (const [target, definition] of Object.entries(mapping)) {
204 if (target === '$copy') continue
205 if (!target.trim()) errors.push('Target path cannot be empty')
206 validateValue(definition, inputSchema, errors, target, undefined, 'data', scopeSchemas)
207 }
208 return { valid: errors.length === 0, errors }
209}
210