-
Notifications
You must be signed in to change notification settings - Fork 760
Expand file tree
/
Copy pathindex.js
More file actions
402 lines (343 loc) · 11.1 KB
/
index.js
File metadata and controls
402 lines (343 loc) · 11.1 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
import lib from './lib';
import refs from './lib/refs';
import externalValue from './lib/external-value';
import allOf from './lib/all-of';
import parameters from './lib/parameters';
import properties from './lib/properties';
import ContextTree from './lib/context-tree';
const HARD_LIMIT = 100;
const noop = () => {};
class SpecMap {
static getPluginName(plugin) {
return plugin.pluginName;
}
static getPatchesOfType(patches, fn) {
return patches.filter(fn);
}
constructor(opts) {
Object.assign(
this,
{
spec: '',
debugLevel: 'info',
plugins: [],
pluginHistory: {},
errors: [],
mutations: [],
promisedPatches: [],
state: {},
patches: [],
context: {},
contextTree: new ContextTree(),
showDebug: false,
allPatches: [], // only populated if showDebug is true
pluginProp: 'specMap',
libMethods: Object.assign(Object.create(this), lib, {
getInstance: () => this,
}),
allowMetaPatches: false,
},
opts
);
// Lib methods bound
this.get = this._get.bind(this); // eslint-disable-line no-underscore-dangle
this.getContext = this._getContext.bind(this); // eslint-disable-line no-underscore-dangle
this.hasRun = this._hasRun.bind(this); // eslint-disable-line no-underscore-dangle
this.wrappedPlugins = this.plugins.map(this.wrapPlugin.bind(this)).filter(lib.isFunction);
// Initial patch(s)
this.patches.push(lib.add([], this.spec));
this.patches.push(lib.context([], this.context));
this.updatePatches(this.patches);
}
debug(level, ...args) {
if (this.debugLevel === level) {
console.log(...args); // eslint-disable-line no-console
}
}
verbose(header, ...args) {
if (this.debugLevel === 'verbose') {
console.log(`[${header}] `, ...args); // eslint-disable-line no-console
}
}
wrapPlugin(plugin, name) {
const { pathDiscriminator } = this;
let ctx = null;
let fn;
if (plugin[this.pluginProp]) {
ctx = plugin;
fn = plugin[this.pluginProp];
} else if (lib.isFunction(plugin)) {
fn = plugin;
} else if (lib.isObject(plugin)) {
fn = createKeyBasedPlugin(plugin);
}
return Object.assign(fn.bind(ctx), {
pluginName: plugin.name || name,
isGenerator: lib.isGenerator(fn),
});
// Expected plugin interface: {key: string, plugin: fn*}
// This traverses depth-first and immediately applies yielded patches.
// This strategy should work well for most plugins (including the built-ins).
// We might consider making this (traversing & application) configurable later.
function createKeyBasedPlugin(pluginObj) {
const isSubPath = (path, tested) => {
if (!Array.isArray(path)) {
return true;
}
return path.every((val, i) => val === tested[i]);
};
return function* generator(patches, specmap) {
const refCache = {};
// eslint-disable-next-line no-restricted-syntax
for (const patch of patches.filter(lib.isAdditiveMutation)) {
yield* traverse(patch.value, patch.path, patch);
}
function* traverse(obj, path, patch) {
if (!lib.isObject(obj)) {
if (pluginObj.key === path[path.length - 1]) {
yield pluginObj.plugin(obj, pluginObj.key, path, specmap);
}
} else {
const parentIndex = path.length - 1;
const parent = path[parentIndex];
const indexOfFirstProperties = path.indexOf('properties');
const isRootProperties =
parent === 'properties' && parentIndex === indexOfFirstProperties;
const traversed = specmap.allowMetaPatches && refCache[obj.$$ref];
// eslint-disable-next-line no-restricted-syntax
for (const key of Object.keys(obj)) {
const val = obj[key];
const updatedPath = path.concat(key);
const isObj = lib.isObject(val);
const objRef = obj.$$ref;
if (!traversed) {
if (isObj) {
// Only store the ref if it exists
if (specmap.allowMetaPatches && objRef) {
refCache[objRef] = true;
}
yield* traverse(val, updatedPath, patch);
}
}
if (!isRootProperties && key === pluginObj.key) {
const isWithinPathDiscriminator = isSubPath(pathDiscriminator, path);
if (!pathDiscriminator || isWithinPathDiscriminator) {
yield pluginObj.plugin(val, key, updatedPath, specmap, patch);
}
}
}
}
}
};
}
}
nextPlugin() {
return this.wrappedPlugins.find((plugin) => {
const mutations = this.getMutationsForPlugin(plugin);
return mutations.length > 0;
});
}
nextPromisedPatch() {
if (this.promisedPatches.length > 0) {
return Promise.race(this.promisedPatches.map((patch) => patch.value));
}
return undefined;
}
getPluginHistory(plugin) {
const name = this.constructor.getPluginName(plugin);
return this.pluginHistory[name] || [];
}
getPluginRunCount(plugin) {
return this.getPluginHistory(plugin).length;
}
getPluginHistoryTip(plugin) {
const history = this.getPluginHistory(plugin);
const val = history && history[history.length - 1];
return val || {};
}
getPluginMutationIndex(plugin) {
const mi = this.getPluginHistoryTip(plugin).mutationIndex;
return typeof mi !== 'number' ? -1 : mi;
}
updatePluginHistory(plugin, val) {
const name = this.constructor.getPluginName(plugin);
this.pluginHistory[name] = this.pluginHistory[name] || [];
this.pluginHistory[name].push(val);
}
updatePatches(patches) {
lib.normalizeArray(patches).forEach((patch) => {
if (patch instanceof Error) {
this.errors.push(patch);
return;
}
try {
if (!lib.isObject(patch)) {
this.debug('updatePatches', 'Got a non-object patch', patch);
return;
}
if (this.showDebug) {
this.allPatches.push(patch);
}
if (lib.isPromise(patch.value)) {
this.promisedPatches.push(patch);
this.promisedPatchThen(patch);
return;
}
if (lib.isContextPatch(patch)) {
this.setContext(patch.path, patch.value);
return;
}
if (lib.isMutation(patch)) {
this.updateMutations(patch);
return;
}
} catch (e) {
console.error(e); // eslint-disable-line no-console
this.errors.push(e);
}
});
}
updateMutations(patch) {
if (typeof patch.value === 'object' && !Array.isArray(patch.value) && this.allowMetaPatches) {
patch.value = { ...patch.value };
}
const result = lib.applyPatch(this.state, patch, { allowMetaPatches: this.allowMetaPatches });
if (result) {
this.mutations.push(patch);
this.state = result;
}
}
removePromisedPatch(patch) {
const index = this.promisedPatches.indexOf(patch);
if (index < 0) {
this.debug("Tried to remove a promisedPatch that isn't there!");
return;
}
this.promisedPatches.splice(index, 1);
}
promisedPatchThen(patch) {
patch.value = patch.value
.then((val) => {
const promisedPatch = { ...patch, value: val };
this.removePromisedPatch(patch);
this.updatePatches(promisedPatch);
})
.catch((e) => {
this.removePromisedPatch(patch);
this.updatePatches(e);
});
return patch.value;
}
getMutations(from, to) {
from = from || 0;
if (typeof to !== 'number') {
to = this.mutations.length;
}
return this.mutations.slice(from, to);
}
getCurrentMutations() {
return this.getMutationsForPlugin(this.getCurrentPlugin());
}
getMutationsForPlugin(plugin) {
const tip = this.getPluginMutationIndex(plugin);
return this.getMutations(tip + 1);
}
getCurrentPlugin() {
return this.currentPlugin;
}
getLib() {
return this.libMethods;
}
// eslint-disable-next-line no-underscore-dangle
_get(path) {
return lib.getIn(this.state, path);
}
// eslint-disable-next-line no-underscore-dangle
_getContext(path) {
return this.contextTree.get(path);
}
setContext(path, value) {
return this.contextTree.set(path, value);
}
// eslint-disable-next-line no-underscore-dangle
_hasRun(count) {
const times = this.getPluginRunCount(this.getCurrentPlugin());
return times > (count || 0);
}
dispatch() {
const that = this;
const plugin = this.nextPlugin();
if (!plugin) {
const nextPromise = this.nextPromisedPatch();
if (nextPromise) {
return nextPromise.then(() => this.dispatch()).catch(() => this.dispatch());
}
// We're done!
const result = { spec: this.state, errors: this.errors };
if (this.showDebug) {
result.patches = this.allPatches;
}
return Promise.resolve(result);
}
// Makes sure plugin isn't running an endless loop
that.pluginCount = that.pluginCount || {};
that.pluginCount[plugin] = (that.pluginCount[plugin] || 0) + 1;
if (that.pluginCount[plugin] > HARD_LIMIT) {
return Promise.resolve({
spec: that.state,
errors: that.errors.concat(
new Error(`We've reached a hard limit of ${HARD_LIMIT} plugin runs`)
),
});
}
// A different plugin runs, wait for all promises to resolve, then retry
if (plugin !== this.currentPlugin && this.promisedPatches.length) {
const promises = this.promisedPatches.map((p) => p.value);
// Waits for all to settle instead of Promise.all which stops on rejection
return Promise.all(promises.map((promise) => promise.then(noop, noop))).then(() =>
this.dispatch()
);
}
// Ok, run the plugin
return executePlugin();
function executePlugin() {
that.currentPlugin = plugin;
const mutations = that.getCurrentMutations();
const lastMutationIndex = that.mutations.length - 1;
try {
if (plugin.isGenerator) {
// eslint-disable-next-line no-restricted-syntax
for (const yieldedPatches of plugin(mutations, that.getLib())) {
updatePatches(yieldedPatches);
}
} else {
const newPatches = plugin(mutations, that.getLib());
updatePatches(newPatches);
}
} catch (e) {
console.error(e); // eslint-disable-line no-console
updatePatches([Object.assign(Object.create(e), { plugin })]);
} finally {
that.updatePluginHistory(plugin, { mutationIndex: lastMutationIndex });
}
return that.dispatch();
}
function updatePatches(patches) {
if (patches) {
patches = lib.fullyNormalizeArray(patches);
that.updatePatches(patches, plugin);
}
}
}
}
export default function mapSpec(opts) {
return new SpecMap(opts).dispatch();
}
const plugins = {
refs,
externalValue,
allOf,
parameters,
properties,
};
export { SpecMap, plugins };