-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse.mjs
More file actions
168 lines (130 loc) · 4.17 KB
/
parse.mjs
File metadata and controls
168 lines (130 loc) · 4.17 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
import Debug from './debug.mjs'
import { SendScriptReferenceError } from './error.mjs'
function flattenSchema (schema) {
const obj = {}
for (const item of schema) {
if (typeof item === 'string') {
// leaf function
obj[item] = true
} else if (Array.isArray(item)) {
const [name, children] = item
if (!Array.isArray(children)) {
throw new Error(`Expected children array for namespace "${name}"`)
}
obj[name] = flattenSchema(children)
} else {
throw new Error('Schema items must be strings or [name, children] arrays')
}
}
return obj
}
const debug = Debug.extend('parse')
const undefinedSentinel = Symbol('sendscript-undefined')
const isPlainObject = (value) => {
if (!value || typeof value !== 'object') return false
const proto = Object.getPrototypeOf(value)
return proto === Object.prototype || proto === null
}
// Recursively resolve awaited values in a parsed tree
const evaluate = (value, awaits = []) => {
if (value === undefinedSentinel) return undefined
if (Array.isArray(value)) {
const [operator, ...rest] = value
if (operator === 'await') {
const [index] = rest
// No need to check index. It is closely tied to the program.
// if (typeof index !== 'number' || index < 0 || index >= awaitsResolved.length) {
// throw new Error(`Invalid await index: ${index}`);
// }
return awaits[index]
}
if (operator === 'call') {
// Step 1: evaluate the function itself
let [fn, args] = rest
fn = evaluate(fn, awaits)
// Step 2: evaluate each argument AFTER fn is ready
for (let i = 0; i < args.length; i++) {
args[i] = evaluate(args[i], awaits)
}
// Step 3: call the function
return fn(...args)
}
if (operator === 'quote') {
const [quoted] = rest
return quoted // return as-is without evaluating
}
// fallback: evaluate each element
// re-uses the array again.
for (let index = 0; index < value.length; index++) {
const item = value[index]
value[index] = evaluate(item, awaits)
}
return value
}
if (isPlainObject(value)) {
// We muatate the object itself. No need to make a new one.
for (const key of Object.keys(value)) {
value[key] = evaluate(value[key], awaits)
}
return value
}
return value
}
const spy = (fn) => (...args) => {
const value = fn(...args)
debug(args, ' => ', value)
return value
}
const defaultLeafDeserializer = (text) => JSON.parse(text)
export default (schemaArg, env, deserialize = defaultLeafDeserializer) => {
const schema = flattenSchema(schemaArg)
return function parse (program) {
debug('program', program)
const awaits = []
// Creates the list of awaits that will resolve in order
// and also deserializes the leaves.
const reviver = spy((key, value) => {
if (value === null) return value
if (!Array.isArray(value)) {
return value
}
const [operator, ...rest] = value
if (operator === 'leaf') {
const leafValue = deserialize(rest[0])
return leafValue === undefined ? undefinedSentinel : leafValue
}
if (operator === 'await') {
const [program] = rest
return ['await', awaits.push(program) - 1]
}
if (operator === 'ref') {
const path = rest
let current = env
let schemaCurrent = schema
for (const segment of path) {
if (schemaCurrent && Object.hasOwn(schemaCurrent, segment)) {
current = current[segment]
schemaCurrent = schemaCurrent[segment]
} else {
throw new SendScriptReferenceError({ key, value })
}
}
return current
}
return value
})
const parsed = JSON.parse(program, reviver)
debug('parsed', parsed)
if (awaits.length) {
debug('awaits', awaits)
return (async function () {
for (let index = 0; index < awaits.length; index++) {
awaits[index] = await evaluate(awaits[index], awaits)
}
debug('awaits(awaited)', awaits)
return evaluate(parsed, awaits)
})()
}
return evaluate(parsed)
}
}