@easy-editor/renderer-core 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,971 @@
1
+ 'use strict';
2
+
3
+ var core = require('@easy-editor/core');
4
+
5
+ const classnames = (...args) => {
6
+ return args.filter(Boolean).join(' ');
7
+ };
8
+
9
+ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
10
+
11
+ var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
12
+ var root = freeGlobal || freeSelf || Function('return this')();
13
+
14
+ var Symbol = root.Symbol;
15
+
16
+ var objectProto$7 = Object.prototype;
17
+ var hasOwnProperty$5 = objectProto$7.hasOwnProperty;
18
+ var nativeObjectToString$1 = objectProto$7.toString;
19
+ var symToStringTag$1 = Symbol ? Symbol.toStringTag : undefined;
20
+ function getRawTag(value) {
21
+ var isOwn = hasOwnProperty$5.call(value, symToStringTag$1),
22
+ tag = value[symToStringTag$1];
23
+ try {
24
+ value[symToStringTag$1] = undefined;
25
+ var unmasked = true;
26
+ } catch (e) {}
27
+ var result = nativeObjectToString$1.call(value);
28
+ if (unmasked) {
29
+ if (isOwn) {
30
+ value[symToStringTag$1] = tag;
31
+ } else {
32
+ delete value[symToStringTag$1];
33
+ }
34
+ }
35
+ return result;
36
+ }
37
+
38
+ var objectProto$6 = Object.prototype;
39
+ var nativeObjectToString = objectProto$6.toString;
40
+ function objectToString(value) {
41
+ return nativeObjectToString.call(value);
42
+ }
43
+
44
+ var nullTag = '[object Null]',
45
+ undefinedTag = '[object Undefined]';
46
+ var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
47
+ function baseGetTag(value) {
48
+ if (value == null) {
49
+ return value === undefined ? undefinedTag : nullTag;
50
+ }
51
+ return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value);
52
+ }
53
+
54
+ function isObjectLike(value) {
55
+ return value != null && typeof value == 'object';
56
+ }
57
+
58
+ var isArray = Array.isArray;
59
+
60
+ function isObject(value) {
61
+ var type = typeof value;
62
+ return value != null && (type == 'object' || type == 'function');
63
+ }
64
+
65
+ function identity(value) {
66
+ return value;
67
+ }
68
+
69
+ var asyncTag = '[object AsyncFunction]',
70
+ funcTag$1 = '[object Function]',
71
+ genTag = '[object GeneratorFunction]',
72
+ proxyTag = '[object Proxy]';
73
+ function isFunction(value) {
74
+ if (!isObject(value)) {
75
+ return false;
76
+ }
77
+ var tag = baseGetTag(value);
78
+ return tag == funcTag$1 || tag == genTag || tag == asyncTag || tag == proxyTag;
79
+ }
80
+
81
+ var coreJsData = root['__core-js_shared__'];
82
+
83
+ var maskSrcKey = function () {
84
+ var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
85
+ return uid ? 'Symbol(src)_1.' + uid : '';
86
+ }();
87
+ function isMasked(func) {
88
+ return !!maskSrcKey && maskSrcKey in func;
89
+ }
90
+
91
+ var funcProto$1 = Function.prototype;
92
+ var funcToString$1 = funcProto$1.toString;
93
+ function toSource(func) {
94
+ if (func != null) {
95
+ try {
96
+ return funcToString$1.call(func);
97
+ } catch (e) {}
98
+ try {
99
+ return func + '';
100
+ } catch (e) {}
101
+ }
102
+ return '';
103
+ }
104
+
105
+ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
106
+ var reIsHostCtor = /^\[object .+?Constructor\]$/;
107
+ var funcProto = Function.prototype,
108
+ objectProto$5 = Object.prototype;
109
+ var funcToString = funcProto.toString;
110
+ var hasOwnProperty$4 = objectProto$5.hasOwnProperty;
111
+ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty$4).replace(reRegExpChar, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$');
112
+ function baseIsNative(value) {
113
+ if (!isObject(value) || isMasked(value)) {
114
+ return false;
115
+ }
116
+ var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
117
+ return pattern.test(toSource(value));
118
+ }
119
+
120
+ function getValue$1(object, key) {
121
+ return object == null ? undefined : object[key];
122
+ }
123
+
124
+ function getNative(object, key) {
125
+ var value = getValue$1(object, key);
126
+ return baseIsNative(value) ? value : undefined;
127
+ }
128
+
129
+ var WeakMap = getNative(root, 'WeakMap');
130
+
131
+ function arrayEach(array, iteratee) {
132
+ var index = -1,
133
+ length = array == null ? 0 : array.length;
134
+ while (++index < length) {
135
+ if (iteratee(array[index], index, array) === false) {
136
+ break;
137
+ }
138
+ }
139
+ return array;
140
+ }
141
+
142
+ var MAX_SAFE_INTEGER$1 = 9007199254740991;
143
+ var reIsUint = /^(?:0|[1-9]\d*)$/;
144
+ function isIndex(value, length) {
145
+ var type = typeof value;
146
+ length = length == null ? MAX_SAFE_INTEGER$1 : length;
147
+ return !!length && (type == 'number' || type != 'symbol' && reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
148
+ }
149
+
150
+ var MAX_SAFE_INTEGER = 9007199254740991;
151
+ function isLength(value) {
152
+ return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
153
+ }
154
+
155
+ function isArrayLike(value) {
156
+ return value != null && isLength(value.length) && !isFunction(value);
157
+ }
158
+
159
+ var objectProto$4 = Object.prototype;
160
+ function isPrototype(value) {
161
+ var Ctor = value && value.constructor,
162
+ proto = typeof Ctor == 'function' && Ctor.prototype || objectProto$4;
163
+ return value === proto;
164
+ }
165
+
166
+ function baseTimes(n, iteratee) {
167
+ var index = -1,
168
+ result = Array(n);
169
+ while (++index < n) {
170
+ result[index] = iteratee(index);
171
+ }
172
+ return result;
173
+ }
174
+
175
+ var argsTag$1 = '[object Arguments]';
176
+ function baseIsArguments(value) {
177
+ return isObjectLike(value) && baseGetTag(value) == argsTag$1;
178
+ }
179
+
180
+ var objectProto$3 = Object.prototype;
181
+ var hasOwnProperty$3 = objectProto$3.hasOwnProperty;
182
+ var propertyIsEnumerable = objectProto$3.propertyIsEnumerable;
183
+ var isArguments = baseIsArguments(function () {
184
+ return arguments;
185
+ }()) ? baseIsArguments : function (value) {
186
+ return isObjectLike(value) && hasOwnProperty$3.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee');
187
+ };
188
+
189
+ function stubFalse() {
190
+ return false;
191
+ }
192
+
193
+ var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports;
194
+ var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module;
195
+ var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1;
196
+ var Buffer = moduleExports$1 ? root.Buffer : undefined;
197
+ var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
198
+ var isBuffer = nativeIsBuffer || stubFalse;
199
+
200
+ var argsTag = '[object Arguments]',
201
+ arrayTag = '[object Array]',
202
+ boolTag = '[object Boolean]',
203
+ dateTag = '[object Date]',
204
+ errorTag = '[object Error]',
205
+ funcTag = '[object Function]',
206
+ mapTag$2 = '[object Map]',
207
+ numberTag = '[object Number]',
208
+ objectTag$1 = '[object Object]',
209
+ regexpTag = '[object RegExp]',
210
+ setTag$2 = '[object Set]',
211
+ stringTag = '[object String]',
212
+ weakMapTag$1 = '[object WeakMap]';
213
+ var arrayBufferTag = '[object ArrayBuffer]',
214
+ dataViewTag$1 = '[object DataView]',
215
+ float32Tag = '[object Float32Array]',
216
+ float64Tag = '[object Float64Array]',
217
+ int8Tag = '[object Int8Array]',
218
+ int16Tag = '[object Int16Array]',
219
+ int32Tag = '[object Int32Array]',
220
+ uint8Tag = '[object Uint8Array]',
221
+ uint8ClampedTag = '[object Uint8ClampedArray]',
222
+ uint16Tag = '[object Uint16Array]',
223
+ uint32Tag = '[object Uint32Array]';
224
+ var typedArrayTags = {};
225
+ typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
226
+ typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag$1] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag$2] = typedArrayTags[numberTag] = typedArrayTags[objectTag$1] = typedArrayTags[regexpTag] = typedArrayTags[setTag$2] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag$1] = false;
227
+ function baseIsTypedArray(value) {
228
+ return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
229
+ }
230
+
231
+ function baseUnary(func) {
232
+ return function (value) {
233
+ return func(value);
234
+ };
235
+ }
236
+
237
+ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
238
+ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
239
+ var moduleExports = freeModule && freeModule.exports === freeExports;
240
+ var freeProcess = moduleExports && freeGlobal.process;
241
+ var nodeUtil = function () {
242
+ try {
243
+ var types = freeModule && freeModule.require && freeModule.require('util').types;
244
+ if (types) {
245
+ return types;
246
+ }
247
+ return freeProcess && freeProcess.binding && freeProcess.binding('util');
248
+ } catch (e) {}
249
+ }();
250
+
251
+ var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
252
+ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
253
+
254
+ var objectProto$2 = Object.prototype;
255
+ var hasOwnProperty$2 = objectProto$2.hasOwnProperty;
256
+ function arrayLikeKeys(value, inherited) {
257
+ var isArr = isArray(value),
258
+ isArg = !isArr && isArguments(value),
259
+ isBuff = !isArr && !isArg && isBuffer(value),
260
+ isType = !isArr && !isArg && !isBuff && isTypedArray(value),
261
+ skipIndexes = isArr || isArg || isBuff || isType,
262
+ result = skipIndexes ? baseTimes(value.length, String) : [],
263
+ length = result.length;
264
+ for (var key in value) {
265
+ if ((hasOwnProperty$2.call(value, key)) && !(skipIndexes && (
266
+ key == 'length' ||
267
+ isBuff && (key == 'offset' || key == 'parent') ||
268
+ isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset') ||
269
+ isIndex(key, length)))) {
270
+ result.push(key);
271
+ }
272
+ }
273
+ return result;
274
+ }
275
+
276
+ function overArg(func, transform) {
277
+ return function (arg) {
278
+ return func(transform(arg));
279
+ };
280
+ }
281
+
282
+ var nativeKeys = overArg(Object.keys, Object);
283
+
284
+ var objectProto$1 = Object.prototype;
285
+ var hasOwnProperty$1 = objectProto$1.hasOwnProperty;
286
+ function baseKeys(object) {
287
+ if (!isPrototype(object)) {
288
+ return nativeKeys(object);
289
+ }
290
+ var result = [];
291
+ for (var key in Object(object)) {
292
+ if (hasOwnProperty$1.call(object, key) && key != 'constructor') {
293
+ result.push(key);
294
+ }
295
+ }
296
+ return result;
297
+ }
298
+
299
+ function keys(object) {
300
+ return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
301
+ }
302
+
303
+ var Map = getNative(root, 'Map');
304
+
305
+ var DataView = getNative(root, 'DataView');
306
+
307
+ var Promise$1 = getNative(root, 'Promise');
308
+
309
+ var Set = getNative(root, 'Set');
310
+
311
+ var mapTag$1 = '[object Map]',
312
+ objectTag = '[object Object]',
313
+ promiseTag = '[object Promise]',
314
+ setTag$1 = '[object Set]',
315
+ weakMapTag = '[object WeakMap]';
316
+ var dataViewTag = '[object DataView]';
317
+ var dataViewCtorString = toSource(DataView),
318
+ mapCtorString = toSource(Map),
319
+ promiseCtorString = toSource(Promise$1),
320
+ setCtorString = toSource(Set),
321
+ weakMapCtorString = toSource(WeakMap);
322
+ var getTag = baseGetTag;
323
+ if (DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag || Map && getTag(new Map()) != mapTag$1 || Promise$1 && getTag(Promise$1.resolve()) != promiseTag || Set && getTag(new Set()) != setTag$1 || WeakMap && getTag(new WeakMap()) != weakMapTag) {
324
+ getTag = function (value) {
325
+ var result = baseGetTag(value),
326
+ Ctor = result == objectTag ? value.constructor : undefined,
327
+ ctorString = Ctor ? toSource(Ctor) : '';
328
+ if (ctorString) {
329
+ switch (ctorString) {
330
+ case dataViewCtorString:
331
+ return dataViewTag;
332
+ case mapCtorString:
333
+ return mapTag$1;
334
+ case promiseCtorString:
335
+ return promiseTag;
336
+ case setCtorString:
337
+ return setTag$1;
338
+ case weakMapCtorString:
339
+ return weakMapTag;
340
+ }
341
+ }
342
+ return result;
343
+ };
344
+ }
345
+
346
+ function createBaseFor(fromRight) {
347
+ return function (object, iteratee, keysFunc) {
348
+ var index = -1,
349
+ iterable = Object(object),
350
+ props = keysFunc(object),
351
+ length = props.length;
352
+ while (length--) {
353
+ var key = props[++index];
354
+ if (iteratee(iterable[key], key, iterable) === false) {
355
+ break;
356
+ }
357
+ }
358
+ return object;
359
+ };
360
+ }
361
+
362
+ var baseFor = createBaseFor();
363
+
364
+ function baseForOwn(object, iteratee) {
365
+ return object && baseFor(object, iteratee, keys);
366
+ }
367
+
368
+ function createBaseEach(eachFunc, fromRight) {
369
+ return function (collection, iteratee) {
370
+ if (collection == null) {
371
+ return collection;
372
+ }
373
+ if (!isArrayLike(collection)) {
374
+ return eachFunc(collection, iteratee);
375
+ }
376
+ var length = collection.length,
377
+ index = -1,
378
+ iterable = Object(collection);
379
+ while (++index < length) {
380
+ if (iteratee(iterable[index], index, iterable) === false) {
381
+ break;
382
+ }
383
+ }
384
+ return collection;
385
+ };
386
+ }
387
+
388
+ var baseEach = createBaseEach(baseForOwn);
389
+
390
+ function castFunction(value) {
391
+ return typeof value == 'function' ? value : identity;
392
+ }
393
+
394
+ function forEach(collection, iteratee) {
395
+ var func = isArray(collection) ? arrayEach : baseEach;
396
+ return func(collection, castFunction(iteratee));
397
+ }
398
+
399
+ var mapTag = '[object Map]',
400
+ setTag = '[object Set]';
401
+ var objectProto = Object.prototype;
402
+ var hasOwnProperty = objectProto.hasOwnProperty;
403
+ function isEmpty(value) {
404
+ if (value == null) {
405
+ return true;
406
+ }
407
+ if (isArrayLike(value) && (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || isBuffer(value) || isTypedArray(value) || isArguments(value))) {
408
+ return !value.length;
409
+ }
410
+ var tag = getTag(value);
411
+ if (tag == mapTag || tag == setTag) {
412
+ return !value.size;
413
+ }
414
+ if (isPrototype(value)) {
415
+ return !baseKeys(value).length;
416
+ }
417
+ for (var key in value) {
418
+ if (hasOwnProperty.call(value, key)) {
419
+ return false;
420
+ }
421
+ }
422
+ return true;
423
+ }
424
+
425
+ const logger = core.createLogger('Renderer');
426
+
427
+ const PropTypes2 = true;
428
+ const inSameDomain = () => {
429
+ try {
430
+ return window.parent !== window && window.parent.location.host === window.location.host;
431
+ } catch (e) {
432
+ return false;
433
+ }
434
+ };
435
+ const getFileCssName = fileName => {
436
+ if (!fileName) {
437
+ return;
438
+ }
439
+ const name = fileName.replace(/([A-Z])/g, '-$1').toLowerCase();
440
+ return `lce-${name}`.split('-').filter(p => !!p).join('-');
441
+ };
442
+ const isSchema = schema => {
443
+ if (!schema) {
444
+ return false;
445
+ }
446
+ if (schema.componentName === 'Leaf' || schema.componentName === 'Slot') {
447
+ return true;
448
+ }
449
+ if (Array.isArray(schema)) {
450
+ return schema.every(item => isSchema(item));
451
+ }
452
+ const isValidProps = props => {
453
+ if (!props) {
454
+ return false;
455
+ }
456
+ return typeof schema.props === 'object' && !Array.isArray(props);
457
+ };
458
+ return !!(schema.componentName && isValidProps(schema.props));
459
+ };
460
+ const getValue = (obj, path, defaultValue = {}) => {
461
+ if (Array.isArray(obj)) {
462
+ return defaultValue;
463
+ }
464
+ if (!obj || typeof obj !== 'object') {
465
+ return defaultValue;
466
+ }
467
+ const res = path.split('.').reduce((pre, cur) => {
468
+ return pre && pre[cur];
469
+ }, obj);
470
+ if (res === undefined) {
471
+ return defaultValue;
472
+ }
473
+ return res;
474
+ };
475
+ const transformArrayToMap = (arr, key, overwrite = true) => {
476
+ if (!arr || !Array.isArray(arr)) {
477
+ return {};
478
+ }
479
+ const res = {};
480
+ arr.forEach(item => {
481
+ const curKey = item[key];
482
+ if (item[key] === undefined) {
483
+ return;
484
+ }
485
+ if (res[curKey] && !overwrite) {
486
+ return;
487
+ }
488
+ res[curKey] = item;
489
+ });
490
+ return res;
491
+ };
492
+ const parseData = (schema, self, options = {}) => {
493
+ if (core.isJSExpression(schema)) {
494
+ return parseExpression({
495
+ str: schema,
496
+ self,
497
+ thisRequired: true,
498
+ logScope: options.logScope
499
+ });
500
+ }
501
+ if (typeof schema === 'string') {
502
+ return schema.trim();
503
+ } else if (Array.isArray(schema)) {
504
+ return schema.map(item => parseData(item, self, options));
505
+ } else if (typeof schema === 'function') {
506
+ return schema.bind(self);
507
+ } else if (typeof schema === 'object') {
508
+ if (!schema) {
509
+ return schema;
510
+ }
511
+ const res = {};
512
+ Object.entries(schema).forEach(([key, val]) => {
513
+ if (key.startsWith('__')) {
514
+ return;
515
+ }
516
+ res[key] = parseData(val, self, options);
517
+ });
518
+ return res;
519
+ }
520
+ return schema;
521
+ };
522
+ const isUseLoop = (loop, isDesignMode) => {
523
+ if (!isDesignMode) {
524
+ return true;
525
+ }
526
+ if (!Array.isArray(loop)) {
527
+ return false;
528
+ }
529
+ return loop.length > 0;
530
+ };
531
+ const checkPropTypes = (value, name, rule, componentName) => {
532
+ let ruleFunction = rule;
533
+ if (typeof rule === 'string') {
534
+ ruleFunction = new Function(`"use strict"; const PropTypes = arguments[0]; return ${rule}`)(PropTypes2);
535
+ }
536
+ if (!ruleFunction || typeof ruleFunction !== 'function') {
537
+ logger.warn('checkPropTypes should have a function type rule argument');
538
+ return true;
539
+ }
540
+ const err = ruleFunction({
541
+ [name]: value
542
+ }, name, componentName, 'prop', null
543
+ );
544
+ if (err) {
545
+ logger.warn(err);
546
+ }
547
+ return !err;
548
+ };
549
+ const transformStringToFunction = str => {
550
+ if (typeof str !== 'string') {
551
+ return str;
552
+ }
553
+ if (inSameDomain() && window.parent.__newFunc) {
554
+ return window.parent.__newFunc(`"use strict"; return ${str}`)();
555
+ } else {
556
+ return new Function(`"use strict"; return ${str}`)();
557
+ }
558
+ };
559
+ function parseExpression(a, b, c = false) {
560
+ let str;
561
+ let self;
562
+ let thisRequired;
563
+ let logScope;
564
+ if (typeof a === 'object' && b === undefined) {
565
+ str = a.str;
566
+ self = a.self;
567
+ thisRequired = a.thisRequired;
568
+ logScope = a.logScope;
569
+ } else {
570
+ str = a;
571
+ self = b;
572
+ thisRequired = c;
573
+ }
574
+ try {
575
+ const contextArr = ['"use strict";', 'var __self = arguments[0];'];
576
+ contextArr.push('return ');
577
+ let tarStr;
578
+ tarStr = (str.value || '').trim();
579
+ tarStr = tarStr.replace(/this(\W|$)/g, (_a, b) => `__self${b}`);
580
+ tarStr = contextArr.join('\n') + tarStr;
581
+ if (inSameDomain() && window.parent.__newFunc) {
582
+ return window.parent.__newFunc(tarStr)(self);
583
+ }
584
+ const code = `with(${thisRequired ? '{}' : '$scope || {}'}) { ${tarStr} }`;
585
+ return new Function('$scope', code)(self);
586
+ } catch (err) {
587
+ logger.error(`${logScope || ''} parseExpression.error`, err, str, self?.__self ?? self);
588
+ return undefined;
589
+ }
590
+ }
591
+ const parseThisRequiredExpression = (str, self) => {
592
+ return parseExpression(str, self, true);
593
+ };
594
+ const isString = str => {
595
+ return {}.toString.call(str) === '[object String]';
596
+ };
597
+ const capitalizeFirstLetter = word => {
598
+ if (!word || !isString(word) || word.length === 0) {
599
+ return word;
600
+ }
601
+ return word[0].toUpperCase() + word.slice(1);
602
+ };
603
+ const serializeParams = obj => {
604
+ const result = [];
605
+ forEach(obj, (val, key) => {
606
+ if (val === null || val === undefined || val === '') {
607
+ return;
608
+ }
609
+ if (typeof val === 'object') {
610
+ result.push(`${key}=${encodeURIComponent(JSON.stringify(val))}`);
611
+ } else {
612
+ result.push(`${key}=${encodeURIComponent(val)}`);
613
+ }
614
+ });
615
+ return result.join('&');
616
+ };
617
+
618
+ const buildUrl = (dataAPI, params) => {
619
+ const paramStr = serializeParams(params);
620
+ if (paramStr) {
621
+ return dataAPI.indexOf('?') > 0 ? `${dataAPI}&${paramStr}` : `${dataAPI}?${paramStr}`;
622
+ }
623
+ return dataAPI;
624
+ };
625
+ const get = (dataAPI, params = {}, headers = {}, otherProps = {}) => {
626
+ const processedHeaders = {
627
+ Accept: 'application/json',
628
+ ...headers
629
+ };
630
+ const url = buildUrl(dataAPI, params);
631
+ return request(url, 'GET', null, processedHeaders, otherProps);
632
+ };
633
+ const post = (dataAPI, params = {}, headers = {}, otherProps = {}) => {
634
+ const processedHeaders = {
635
+ Accept: 'application/json',
636
+ 'Content-Type': 'application/x-www-form-urlencoded',
637
+ ...headers
638
+ };
639
+ const body = processedHeaders['Content-Type'].indexOf('application/json') > -1 || Array.isArray(params) ? JSON.stringify(params) : serializeParams(params);
640
+ return request(dataAPI, 'POST', body, processedHeaders, otherProps);
641
+ };
642
+ const request = (dataAPI, method = 'GET', data, headers = {}, otherProps = {}) => {
643
+ let processedHeaders = headers || {};
644
+ let payload = data;
645
+ if (method === 'PUT' || method === 'DELETE') {
646
+ processedHeaders = {
647
+ Accept: 'application/json',
648
+ 'Content-Type': 'application/json',
649
+ ...processedHeaders
650
+ };
651
+ payload = JSON.stringify(payload || {});
652
+ }
653
+ return new Promise((resolve, reject) => {
654
+ if (otherProps.timeout) {
655
+ setTimeout(() => {
656
+ reject(new Error('timeout'));
657
+ }, otherProps.timeout);
658
+ }
659
+ fetch(dataAPI, {
660
+ method,
661
+ credentials: 'include',
662
+ headers: processedHeaders,
663
+ body: payload,
664
+ ...otherProps
665
+ }).then(response => {
666
+ switch (response.status) {
667
+ case 200:
668
+ case 201:
669
+ case 202:
670
+ return response.json();
671
+ case 204:
672
+ if (method === 'DELETE') {
673
+ return {
674
+ success: true
675
+ };
676
+ } else {
677
+ return {
678
+ __success: false,
679
+ code: response.status
680
+ };
681
+ }
682
+ case 400:
683
+ case 401:
684
+ case 403:
685
+ case 404:
686
+ case 406:
687
+ case 410:
688
+ case 422:
689
+ case 500:
690
+ return response.json().then(res => {
691
+ return {
692
+ __success: false,
693
+ code: response.status,
694
+ data: res
695
+ };
696
+ }).catch(() => {
697
+ return {
698
+ __success: false,
699
+ code: response.status
700
+ };
701
+ });
702
+ }
703
+ return null;
704
+ }).then(json => {
705
+ if (!json) {
706
+ reject(json);
707
+ return;
708
+ }
709
+ if (json.__success !== false) {
710
+ resolve(json);
711
+ } else {
712
+ json.__success = undefined;
713
+ reject(json);
714
+ }
715
+ }).catch(err => {
716
+ reject(err);
717
+ });
718
+ });
719
+ };
720
+
721
+ const DS_STATUS = {
722
+ INIT: 'init',
723
+ LOADING: 'loading',
724
+ LOADED: 'loaded',
725
+ ERROR: 'error'
726
+ };
727
+ const doRequest = (type, options) => {
728
+ let {
729
+ uri,
730
+ url,
731
+ method = 'GET',
732
+ headers,
733
+ params,
734
+ ...otherProps
735
+ } = options;
736
+ otherProps = otherProps || {};
737
+ if (type === 'fetch') {
738
+ switch (method.toUpperCase()) {
739
+ case 'GET':
740
+ return get(uri, params, headers, otherProps);
741
+ case 'POST':
742
+ return post(uri, params, headers, otherProps);
743
+ default:
744
+ return request(uri, method, params, headers, otherProps);
745
+ }
746
+ }
747
+ logger.log(`Engine default dataSource does not support type:[${type}] dataSource request!`, options);
748
+ };
749
+ class DataHelper {
750
+ host;
751
+ config;
752
+ parser;
753
+ ajaxList;
754
+ dataHandler;
755
+ ajaxMap;
756
+ dataSourceMap;
757
+ appHelper;
758
+ constructor(comp, config, appHelper, parser) {
759
+ this.host = comp;
760
+ this.config = config || {};
761
+ this.parser = parser;
762
+ this.ajaxList = config?.list || [];
763
+ this.ajaxMap = transformArrayToMap(this.ajaxList, 'id');
764
+ this.dataSourceMap = this.generateDataSourceMap();
765
+ this.appHelper = appHelper;
766
+ this.dataHandler = config?.dataHandler ? parseExpression(config?.dataHandler, comp, true) : undefined;
767
+ }
768
+ updateConfig(config = {}) {
769
+ this.config = config;
770
+ this.ajaxList = config?.list || [];
771
+ const ajaxMap = transformArrayToMap(this.ajaxList, 'id');
772
+ Object.keys(this.ajaxMap).forEach(key => {
773
+ if (!ajaxMap[key]) {
774
+ delete this.dataSourceMap[key];
775
+ }
776
+ });
777
+ this.ajaxMap = ajaxMap;
778
+ this.ajaxList.forEach(item => {
779
+ if (!this.dataSourceMap[item.id]) {
780
+ this.dataSourceMap[item.id] = {
781
+ status: DS_STATUS.INIT,
782
+ load: (...args) => {
783
+ return this.getDataSource(item.id, ...args);
784
+ }
785
+ };
786
+ }
787
+ });
788
+ return this.dataSourceMap;
789
+ }
790
+ generateDataSourceMap() {
791
+ const res = {};
792
+ this.ajaxList.forEach(item => {
793
+ res[item.id] = {
794
+ status: DS_STATUS.INIT,
795
+ load: (...args) => {
796
+ return this.getDataSource(item.id, ...args);
797
+ }
798
+ };
799
+ });
800
+ return res;
801
+ }
802
+ updateDataSourceMap(id, data, error) {
803
+ this.dataSourceMap[id].error = error || undefined;
804
+ this.dataSourceMap[id].data = data;
805
+ this.dataSourceMap[id].status = error ? DS_STATUS.ERROR : DS_STATUS.LOADED;
806
+ }
807
+ getInitDataSourseConfigs() {
808
+ const initConfigs = this.parser(this.ajaxList).filter(item => {
809
+ if (item.isInit === true) {
810
+ this.dataSourceMap[item.id].status = DS_STATUS.LOADING;
811
+ return true;
812
+ }
813
+ return false;
814
+ });
815
+ return initConfigs;
816
+ }
817
+ getInitData() {
818
+ const initSyncData = this.getInitDataSourseConfigs();
819
+ return this.asyncDataHandler(initSyncData).then(res => {
820
+ const {
821
+ dataHandler
822
+ } = this.config;
823
+ return this.handleData(null, dataHandler, res, null);
824
+ });
825
+ }
826
+ async reloadDataSource() {
827
+ const dataSourceMap = await this.getInitData();
828
+ if (isEmpty(dataSourceMap)) {
829
+ return;
830
+ }
831
+ this.host.setState(dataSourceMap);
832
+ if (this.dataHandler) {
833
+ this.dataHandler(dataSourceMap);
834
+ }
835
+ }
836
+ getDataSource(id, params, otherOptions, callback) {
837
+ const req = this.parser(this.ajaxMap[id]);
838
+ const options = req.options || {};
839
+ let callbackFn = callback;
840
+ let otherOptionsObj = otherOptions;
841
+ if (typeof otherOptions === 'function') {
842
+ callbackFn = otherOptions;
843
+ otherOptionsObj = {};
844
+ }
845
+ const {
846
+ headers,
847
+ ...otherProps
848
+ } = otherOptionsObj || {};
849
+ if (!req) {
850
+ logger.warn(`getDataSource API named ${id} not exist`);
851
+ return;
852
+ }
853
+ return this.asyncDataHandler([{
854
+ ...req,
855
+ options: {
856
+ ...options,
857
+ params: Array.isArray(options.params) || Array.isArray(params) ? params || options.params : {
858
+ ...options.params,
859
+ ...params
860
+ },
861
+ headers: {
862
+ ...options.headers,
863
+ ...headers
864
+ },
865
+ ...otherProps
866
+ }
867
+ }]).then(res => {
868
+ try {
869
+ callbackFn && callbackFn(res && res[id]);
870
+ } catch (e) {
871
+ logger.error('load请求回调函数报错', e);
872
+ }
873
+ return res && res[id];
874
+ }).catch(err => {
875
+ try {
876
+ callbackFn && callbackFn(null, err);
877
+ } catch (e) {
878
+ logger.error('load请求回调函数报错', e);
879
+ }
880
+ return err;
881
+ });
882
+ }
883
+ asyncDataHandler(asyncDataList) {
884
+ return new Promise((resolve, reject) => {
885
+ const allReq = [];
886
+ asyncDataList.forEach(req => {
887
+ const {
888
+ id,
889
+ type
890
+ } = req;
891
+ if (!id || !type || type === 'legao') {
892
+ return;
893
+ }
894
+ allReq.push(req);
895
+ });
896
+ if (allReq.length === 0) {
897
+ resolve({});
898
+ }
899
+ const res = {};
900
+ Promise.all(allReq.map(item => {
901
+ return new Promise(innerResolve => {
902
+ const {
903
+ type,
904
+ id,
905
+ dataHandler,
906
+ options
907
+ } = item;
908
+ const fetchHandler = (data, error) => {
909
+ res[id] = this.handleData(id, dataHandler, data, error);
910
+ this.updateDataSourceMap(id, res[id], error);
911
+ innerResolve({});
912
+ };
913
+ const doFetch = (innerType, innerOptions) => {
914
+ doRequest(innerType, innerOptions)?.then(data => {
915
+ fetchHandler(data, undefined);
916
+ }).catch(err => {
917
+ fetchHandler(undefined, err);
918
+ });
919
+ };
920
+ this.dataSourceMap[id].status = DS_STATUS.LOADING;
921
+ doFetch(type, options);
922
+ });
923
+ })).then(() => {
924
+ resolve(res);
925
+ }).catch(e => {
926
+ reject(e);
927
+ });
928
+ });
929
+ }
930
+ handleData(id, dataHandler, data, error) {
931
+ let dataHandlerFun = dataHandler;
932
+ if (core.isJSFunction(dataHandler)) {
933
+ dataHandlerFun = transformStringToFunction(dataHandler.value);
934
+ }
935
+ if (!dataHandlerFun || typeof dataHandlerFun !== 'function') {
936
+ return data;
937
+ }
938
+ try {
939
+ return dataHandlerFun.call(this.host, data, error);
940
+ } catch (e) {
941
+ if (id) {
942
+ logger.error(`[${id}]单个请求数据处理函数运行出错`, e);
943
+ } else {
944
+ logger.error('请求数据处理函数运行出错', e);
945
+ }
946
+ }
947
+ }
948
+ }
949
+
950
+ exports.DataHelper = DataHelper;
951
+ exports.buildUrl = buildUrl;
952
+ exports.capitalizeFirstLetter = capitalizeFirstLetter;
953
+ exports.checkPropTypes = checkPropTypes;
954
+ exports.classnames = classnames;
955
+ exports.doRequest = doRequest;
956
+ exports.get = get;
957
+ exports.getFileCssName = getFileCssName;
958
+ exports.getValue = getValue;
959
+ exports.inSameDomain = inSameDomain;
960
+ exports.isSchema = isSchema;
961
+ exports.isString = isString;
962
+ exports.isUseLoop = isUseLoop;
963
+ exports.logger = logger;
964
+ exports.parseData = parseData;
965
+ exports.parseExpression = parseExpression;
966
+ exports.parseThisRequiredExpression = parseThisRequiredExpression;
967
+ exports.post = post;
968
+ exports.request = request;
969
+ exports.serializeParams = serializeParams;
970
+ exports.transformArrayToMap = transformArrayToMap;
971
+ exports.transformStringToFunction = transformStringToFunction;