pompelmi 0.17.0-dev.36 → 0.17.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.
@@ -1,3279 +0,0 @@
1
- 'use strict';
2
-
3
- const SIG_CEN = 0x02014b50;
4
- const DEFAULTS = {
5
- maxEntries: 1000,
6
- maxTotalUncompressedBytes: 500 * 1024 * 1024,
7
- maxEntryNameLength: 255,
8
- maxCompressionRatio: 1000,
9
- eocdSearchWindow: 70000,
10
- };
11
- function r16(buf, off) {
12
- return buf.readUInt16LE(off);
13
- }
14
- function r32(buf, off) {
15
- return buf.readUInt32LE(off);
16
- }
17
- function isZipLike$1(buf) {
18
- // local file header at start is common
19
- return buf.length >= 4 && buf[0] === 0x50 && buf[1] === 0x4b && buf[2] === 0x03 && buf[3] === 0x04;
20
- }
21
- function lastIndexOfEOCD(buf, window) {
22
- const sig = Buffer.from([0x50, 0x4b, 0x05, 0x06]);
23
- const start = Math.max(0, buf.length - window);
24
- const idx = buf.lastIndexOf(sig, Math.min(buf.length - sig.length, buf.length - 1));
25
- return idx >= start ? idx : -1;
26
- }
27
- function hasTraversal(name) {
28
- return name.includes('../') || name.includes('..\\') || name.startsWith('/') || /^[A-Za-z]:/.test(name);
29
- }
30
- function createZipBombGuard(opts = {}) {
31
- const cfg = { ...DEFAULTS, ...opts };
32
- return {
33
- async scan(input) {
34
- const buf = Buffer.from(input);
35
- const matches = [];
36
- if (!isZipLike$1(buf))
37
- return matches;
38
- // Find EOCD near the end
39
- const eocdPos = lastIndexOfEOCD(buf, cfg.eocdSearchWindow);
40
- if (eocdPos < 0 || eocdPos + 22 > buf.length) {
41
- // ZIP but no EOCD — malformed or polyglot → suspicious
42
- matches.push({ rule: 'zip_eocd_not_found', severity: 'medium' });
43
- return matches;
44
- }
45
- const totalEntries = r16(buf, eocdPos + 10);
46
- const cdSize = r32(buf, eocdPos + 12);
47
- const cdOffset = r32(buf, eocdPos + 16);
48
- // Bounds check
49
- if (cdOffset + cdSize > buf.length) {
50
- matches.push({ rule: 'zip_cd_out_of_bounds', severity: 'medium' });
51
- return matches;
52
- }
53
- // Iterate central directory entries
54
- let ptr = cdOffset;
55
- let seen = 0;
56
- let sumComp = 0;
57
- let sumUnc = 0;
58
- while (ptr + 46 <= cdOffset + cdSize && seen < totalEntries) {
59
- const sig = r32(buf, ptr);
60
- if (sig !== SIG_CEN)
61
- break; // stop if structure breaks
62
- const compSize = r32(buf, ptr + 20);
63
- const uncSize = r32(buf, ptr + 24);
64
- const fnLen = r16(buf, ptr + 28);
65
- const exLen = r16(buf, ptr + 30);
66
- const cmLen = r16(buf, ptr + 32);
67
- const nameStart = ptr + 46;
68
- const nameEnd = nameStart + fnLen;
69
- if (nameEnd > buf.length)
70
- break;
71
- const name = buf.toString('utf8', nameStart, nameEnd);
72
- sumComp += compSize;
73
- sumUnc += uncSize;
74
- seen++;
75
- if (name.length > cfg.maxEntryNameLength) {
76
- matches.push({ rule: 'zip_entry_name_too_long', severity: 'medium', meta: { name, length: name.length } });
77
- }
78
- if (hasTraversal(name)) {
79
- matches.push({ rule: 'zip_path_traversal_entry', severity: 'medium', meta: { name } });
80
- }
81
- // move to next entry
82
- ptr = nameEnd + exLen + cmLen;
83
- }
84
- if (seen !== totalEntries) {
85
- // central dir truncated/odd, still report what we found
86
- matches.push({ rule: 'zip_cd_truncated', severity: 'medium', meta: { seen, totalEntries } });
87
- }
88
- // Heuristics thresholds
89
- if (seen > cfg.maxEntries) {
90
- matches.push({ rule: 'zip_too_many_entries', severity: 'medium', meta: { seen, limit: cfg.maxEntries } });
91
- }
92
- if (sumUnc > cfg.maxTotalUncompressedBytes) {
93
- matches.push({
94
- rule: 'zip_total_uncompressed_too_large',
95
- severity: 'medium',
96
- meta: { totalUncompressed: sumUnc, limit: cfg.maxTotalUncompressedBytes }
97
- });
98
- }
99
- if (sumComp === 0 && sumUnc > 0) {
100
- matches.push({ rule: 'zip_suspicious_ratio', severity: 'medium', meta: { ratio: Infinity } });
101
- }
102
- else if (sumComp > 0) {
103
- const ratio = sumUnc / Math.max(1, sumComp);
104
- if (ratio >= cfg.maxCompressionRatio) {
105
- matches.push({ rule: 'zip_suspicious_ratio', severity: 'medium', meta: { ratio, limit: cfg.maxCompressionRatio } });
106
- }
107
- }
108
- return matches;
109
- }
110
- };
111
- }
112
-
113
- /** Risolve uno Scanner (fn o oggetto con .scan) in una funzione */
114
- function asScanFn(s) {
115
- return typeof s === 'function' ? s : s.scan;
116
- }
117
- /** Composizione sequenziale: concatena tutti i match degli scanner */
118
- function composeScanners(scanners) {
119
- return async (input, ctx) => {
120
- const out = [];
121
- for (const s of scanners) {
122
- const res = await Promise.resolve(asScanFn(s)(input, ctx));
123
- if (Array.isArray(res) && res.length)
124
- out.push(...res);
125
- }
126
- return out;
127
- };
128
- }
129
- /** Ritorna uno ScanFn pronto all'uso, oggi con zip-bomb guard */
130
- function createPresetScanner(_name = 'zip-basic', _opts = {}) {
131
- // Al momento un solo preset "zip-basic"
132
- const scanners = [
133
- createZipBombGuard(), // usa i default interni
134
- ];
135
- return composeScanners(scanners);
136
- }
137
-
138
- /** Mappa veloce estensione -> mime (basic) */
139
- function guessMimeByExt(name) {
140
- if (!name)
141
- return;
142
- const ext = name.toLowerCase().split('.').pop();
143
- switch (ext) {
144
- case 'zip': return 'application/zip';
145
- case 'png': return 'image/png';
146
- case 'jpg':
147
- case 'jpeg': return 'image/jpeg';
148
- case 'pdf': return 'application/pdf';
149
- case 'txt': return 'text/plain';
150
- default: return;
151
- }
152
- }
153
- /** Heuristica semplice per verdetto */
154
- function computeVerdict(matches) {
155
- if (!matches.length)
156
- return 'clean';
157
- // se la regola contiene 'zip_' lo marchiamo "suspicious"
158
- const anyHigh = matches.some(m => (m.tags ?? []).includes('critical') || (m.tags ?? []).includes('high'));
159
- return anyHigh ? 'malicious' : 'suspicious';
160
- }
161
- /** Converte i Match (heuristics) in YaraMatch-like per uniformare l'output */
162
- function toYaraMatches(ms) {
163
- return ms.map(m => ({
164
- rule: m.rule,
165
- namespace: 'heuristics',
166
- tags: ['heuristics'].concat(m.severity ? [m.severity] : []),
167
- meta: m.meta,
168
- }));
169
- }
170
- /** Scan di bytes (browser/node) usando preset (default: zip-basic) */
171
- async function scanBytes(input, opts = {}) {
172
- const t0 = Date.now();
173
- const preset = opts.preset ?? 'zip-basic';
174
- const ctx = {
175
- ...opts.ctx,
176
- mimeType: opts.ctx?.mimeType ?? guessMimeByExt(opts.ctx?.filename),
177
- size: opts.ctx?.size ?? input.byteLength,
178
- };
179
- const scanFn = createPresetScanner(preset);
180
- const matchesH = await scanFn(input, ctx);
181
- const matches = toYaraMatches(matchesH);
182
- const verdict = computeVerdict(matches);
183
- const durationMs = Date.now() - t0;
184
- return {
185
- ok: verdict === 'clean',
186
- verdict,
187
- matches,
188
- reasons: matches.map(m => m.rule),
189
- file: { name: ctx.filename, mimeType: ctx.mimeType, size: ctx.size },
190
- durationMs,
191
- engine: 'heuristics',
192
- truncated: false,
193
- timedOut: false,
194
- };
195
- }
196
- /** Scan di un file su disco (Node). Import dinamico per non vincolare il bundle browser. */
197
- async function scanFile(filePath, opts = {}) {
198
- const [{ readFile, stat }, path] = await Promise.all([
199
- import('fs/promises'),
200
- import('path'),
201
- ]);
202
- const [buf, st] = await Promise.all([readFile(filePath), stat(filePath)]);
203
- const ctx = {
204
- filename: path.basename(filePath),
205
- mimeType: guessMimeByExt(filePath),
206
- size: st.size,
207
- };
208
- return scanBytes(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength), { ...opts, ctx });
209
- }
210
- /** Scan multipli File (browser) usando scanBytes + preset di default */
211
- async function scanFiles(files, opts = {}) {
212
- const list = Array.from(files);
213
- const out = [];
214
- for (const f of list) {
215
- const buf = new Uint8Array(await f.arrayBuffer());
216
- const rep = await scanBytes(buf, {
217
- ...opts,
218
- ctx: { filename: f.name, mimeType: f.type || guessMimeByExt(f.name), size: f.size },
219
- });
220
- out.push(rep);
221
- }
222
- return out;
223
- }
224
-
225
- /**
226
- * Validates a File by MIME type and size (max 5 MB).
227
- */
228
- function validateFile(file) {
229
- const maxSize = 5 * 1024 * 1024;
230
- const allowedTypes = ['text/plain', 'application/json', 'text/csv'];
231
- if (!allowedTypes.includes(file.type)) {
232
- return { valid: false, error: 'Unsupported file type' };
233
- }
234
- if (file.size > maxSize) {
235
- return { valid: false, error: 'File too large (max 5 MB)' };
236
- }
237
- return { valid: true };
238
- }
239
-
240
- var react = {exports: {}};
241
-
242
- var react_production_min = {};
243
-
244
- /**
245
- * @license React
246
- * react.production.min.js
247
- *
248
- * Copyright (c) Facebook, Inc. and its affiliates.
249
- *
250
- * This source code is licensed under the MIT license found in the
251
- * LICENSE file in the root directory of this source tree.
252
- */
253
-
254
- var hasRequiredReact_production_min;
255
-
256
- function requireReact_production_min () {
257
- if (hasRequiredReact_production_min) return react_production_min;
258
- hasRequiredReact_production_min = 1;
259
- var l=Symbol.for("react.element"),n=Symbol.for("react.portal"),p=Symbol.for("react.fragment"),q=Symbol.for("react.strict_mode"),r=Symbol.for("react.profiler"),t=Symbol.for("react.provider"),u=Symbol.for("react.context"),v=Symbol.for("react.forward_ref"),w=Symbol.for("react.suspense"),x=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),z=Symbol.iterator;function A(a){if(null===a||"object"!==typeof a)return null;a=z&&a[z]||a["@@iterator"];return "function"===typeof a?a:null}
260
- var B={isMounted:function(){return false},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C=Object.assign,D={};function E(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B;}E.prototype.isReactComponent={};
261
- E.prototype.setState=function(a,b){if("object"!==typeof a&&"function"!==typeof a&&null!=a)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,a,b,"setState");};E.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,"forceUpdate");};function F(){}F.prototype=E.prototype;function G(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B;}var H=G.prototype=new F;
262
- H.constructor=G;C(H,E.prototype);H.isPureReactComponent=true;var I=Array.isArray,J=Object.prototype.hasOwnProperty,K={current:null},L={key:true,ref:true,__self:true,__source:true};
263
- function M(a,b,e){var d,c={},k=null,h=null;if(null!=b)for(d in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(k=""+b.key),b)J.call(b,d)&&!L.hasOwnProperty(d)&&(c[d]=b[d]);var g=arguments.length-2;if(1===g)c.children=e;else if(1<g){for(var f=Array(g),m=0;m<g;m++)f[m]=arguments[m+2];c.children=f;}if(a&&a.defaultProps)for(d in g=a.defaultProps,g) void 0===c[d]&&(c[d]=g[d]);return {$$typeof:l,type:a,key:k,ref:h,props:c,_owner:K.current}}
264
- function N(a,b){return {$$typeof:l,type:a.type,key:b,ref:a.ref,props:a.props,_owner:a._owner}}function O(a){return "object"===typeof a&&null!==a&&a.$$typeof===l}function escape(a){var b={"=":"=0",":":"=2"};return "$"+a.replace(/[=:]/g,function(a){return b[a]})}var P=/\/+/g;function Q(a,b){return "object"===typeof a&&null!==a&&null!=a.key?escape(""+a.key):b.toString(36)}
265
- function R(a,b,e,d,c){var k=typeof a;if("undefined"===k||"boolean"===k)a=null;var h=false;if(null===a)h=true;else switch(k){case "string":case "number":h=true;break;case "object":switch(a.$$typeof){case l:case n:h=true;}}if(h)return h=a,c=c(h),a=""===d?"."+Q(h,0):d,I(c)?(e="",null!=a&&(e=a.replace(P,"$&/")+"/"),R(c,b,e,"",function(a){return a})):null!=c&&(O(c)&&(c=N(c,e+(!c.key||h&&h.key===c.key?"":(""+c.key).replace(P,"$&/")+"/")+a)),b.push(c)),1;h=0;d=""===d?".":d+":";if(I(a))for(var g=0;g<a.length;g++){k=
266
- a[g];var f=d+Q(k,g);h+=R(k,b,e,f,c);}else if(f=A(a),"function"===typeof f)for(a=f.call(a),g=0;!(k=a.next()).done;)k=k.value,f=d+Q(k,g++),h+=R(k,b,e,f,c);else if("object"===k)throw b=String(a),Error("Objects are not valid as a React child (found: "+("[object Object]"===b?"object with keys {"+Object.keys(a).join(", ")+"}":b)+"). If you meant to render a collection of children, use an array instead.");return h}
267
- function S(a,b,e){if(null==a)return a;var d=[],c=0;R(a,d,"","",function(a){return b.call(e,a,c++)});return d}function T(a){if(-1===a._status){var b=a._result;b=b();b.then(function(b){if(0===a._status||-1===a._status)a._status=1,a._result=b;},function(b){if(0===a._status||-1===a._status)a._status=2,a._result=b;});-1===a._status&&(a._status=0,a._result=b);}if(1===a._status)return a._result.default;throw a._result;}
268
- var U={current:null},V={transition:null},W={ReactCurrentDispatcher:U,ReactCurrentBatchConfig:V,ReactCurrentOwner:K};function X(){throw Error("act(...) is not supported in production builds of React.");}
269
- react_production_min.Children={map:S,forEach:function(a,b,e){S(a,function(){b.apply(this,arguments);},e);},count:function(a){var b=0;S(a,function(){b++;});return b},toArray:function(a){return S(a,function(a){return a})||[]},only:function(a){if(!O(a))throw Error("React.Children.only expected to receive a single React element child.");return a}};react_production_min.Component=E;react_production_min.Fragment=p;react_production_min.Profiler=r;react_production_min.PureComponent=G;react_production_min.StrictMode=q;react_production_min.Suspense=w;
270
- react_production_min.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=W;react_production_min.act=X;
271
- react_production_min.cloneElement=function(a,b,e){if(null===a||void 0===a)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+a+".");var d=C({},a.props),c=a.key,k=a.ref,h=a._owner;if(null!=b){ void 0!==b.ref&&(k=b.ref,h=K.current);void 0!==b.key&&(c=""+b.key);if(a.type&&a.type.defaultProps)var g=a.type.defaultProps;for(f in b)J.call(b,f)&&!L.hasOwnProperty(f)&&(d[f]=void 0===b[f]&&void 0!==g?g[f]:b[f]);}var f=arguments.length-2;if(1===f)d.children=e;else if(1<f){g=Array(f);
272
- for(var m=0;m<f;m++)g[m]=arguments[m+2];d.children=g;}return {$$typeof:l,type:a.type,key:c,ref:k,props:d,_owner:h}};react_production_min.createContext=function(a){a={$$typeof:u,_currentValue:a,_currentValue2:a,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null};a.Provider={$$typeof:t,_context:a};return a.Consumer=a};react_production_min.createElement=M;react_production_min.createFactory=function(a){var b=M.bind(null,a);b.type=a;return b};react_production_min.createRef=function(){return {current:null}};
273
- react_production_min.forwardRef=function(a){return {$$typeof:v,render:a}};react_production_min.isValidElement=O;react_production_min.lazy=function(a){return {$$typeof:y,_payload:{_status:-1,_result:a},_init:T}};react_production_min.memo=function(a,b){return {$$typeof:x,type:a,compare:void 0===b?null:b}};react_production_min.startTransition=function(a){var b=V.transition;V.transition={};try{a();}finally{V.transition=b;}};react_production_min.unstable_act=X;react_production_min.useCallback=function(a,b){return U.current.useCallback(a,b)};react_production_min.useContext=function(a){return U.current.useContext(a)};
274
- react_production_min.useDebugValue=function(){};react_production_min.useDeferredValue=function(a){return U.current.useDeferredValue(a)};react_production_min.useEffect=function(a,b){return U.current.useEffect(a,b)};react_production_min.useId=function(){return U.current.useId()};react_production_min.useImperativeHandle=function(a,b,e){return U.current.useImperativeHandle(a,b,e)};react_production_min.useInsertionEffect=function(a,b){return U.current.useInsertionEffect(a,b)};react_production_min.useLayoutEffect=function(a,b){return U.current.useLayoutEffect(a,b)};
275
- react_production_min.useMemo=function(a,b){return U.current.useMemo(a,b)};react_production_min.useReducer=function(a,b,e){return U.current.useReducer(a,b,e)};react_production_min.useRef=function(a){return U.current.useRef(a)};react_production_min.useState=function(a){return U.current.useState(a)};react_production_min.useSyncExternalStore=function(a,b,e){return U.current.useSyncExternalStore(a,b,e)};react_production_min.useTransition=function(){return U.current.useTransition()};react_production_min.version="18.3.1";
276
- return react_production_min;
277
- }
278
-
279
- var react_development = {exports: {}};
280
-
281
- /**
282
- * @license React
283
- * react.development.js
284
- *
285
- * Copyright (c) Facebook, Inc. and its affiliates.
286
- *
287
- * This source code is licensed under the MIT license found in the
288
- * LICENSE file in the root directory of this source tree.
289
- */
290
- react_development.exports;
291
-
292
- var hasRequiredReact_development;
293
-
294
- function requireReact_development () {
295
- if (hasRequiredReact_development) return react_development.exports;
296
- hasRequiredReact_development = 1;
297
- (function (module, exports) {
298
-
299
- if (process.env.NODE_ENV !== "production") {
300
- (function() {
301
-
302
- /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
303
- if (
304
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
305
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===
306
- 'function'
307
- ) {
308
- __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
309
- }
310
- var ReactVersion = '18.3.1';
311
-
312
- // ATTENTION
313
- // When adding new symbols to this file,
314
- // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
315
- // The Symbol used to tag the ReactElement-like types.
316
- var REACT_ELEMENT_TYPE = Symbol.for('react.element');
317
- var REACT_PORTAL_TYPE = Symbol.for('react.portal');
318
- var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
319
- var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');
320
- var REACT_PROFILER_TYPE = Symbol.for('react.profiler');
321
- var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
322
- var REACT_CONTEXT_TYPE = Symbol.for('react.context');
323
- var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
324
- var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
325
- var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
326
- var REACT_MEMO_TYPE = Symbol.for('react.memo');
327
- var REACT_LAZY_TYPE = Symbol.for('react.lazy');
328
- var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen');
329
- var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
330
- var FAUX_ITERATOR_SYMBOL = '@@iterator';
331
- function getIteratorFn(maybeIterable) {
332
- if (maybeIterable === null || typeof maybeIterable !== 'object') {
333
- return null;
334
- }
335
-
336
- var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
337
-
338
- if (typeof maybeIterator === 'function') {
339
- return maybeIterator;
340
- }
341
-
342
- return null;
343
- }
344
-
345
- /**
346
- * Keeps track of the current dispatcher.
347
- */
348
- var ReactCurrentDispatcher = {
349
- /**
350
- * @internal
351
- * @type {ReactComponent}
352
- */
353
- current: null
354
- };
355
-
356
- /**
357
- * Keeps track of the current batch's configuration such as how long an update
358
- * should suspend for if it needs to.
359
- */
360
- var ReactCurrentBatchConfig = {
361
- transition: null
362
- };
363
-
364
- var ReactCurrentActQueue = {
365
- current: null,
366
- // Used to reproduce behavior of `batchedUpdates` in legacy mode.
367
- isBatchingLegacy: false,
368
- didScheduleLegacyUpdate: false
369
- };
370
-
371
- /**
372
- * Keeps track of the current owner.
373
- *
374
- * The current owner is the component who should own any components that are
375
- * currently being constructed.
376
- */
377
- var ReactCurrentOwner = {
378
- /**
379
- * @internal
380
- * @type {ReactComponent}
381
- */
382
- current: null
383
- };
384
-
385
- var ReactDebugCurrentFrame = {};
386
- var currentExtraStackFrame = null;
387
- function setExtraStackFrame(stack) {
388
- {
389
- currentExtraStackFrame = stack;
390
- }
391
- }
392
-
393
- {
394
- ReactDebugCurrentFrame.setExtraStackFrame = function (stack) {
395
- {
396
- currentExtraStackFrame = stack;
397
- }
398
- }; // Stack implementation injected by the current renderer.
399
-
400
-
401
- ReactDebugCurrentFrame.getCurrentStack = null;
402
-
403
- ReactDebugCurrentFrame.getStackAddendum = function () {
404
- var stack = ''; // Add an extra top frame while an element is being validated
405
-
406
- if (currentExtraStackFrame) {
407
- stack += currentExtraStackFrame;
408
- } // Delegate to the injected renderer-specific implementation
409
-
410
-
411
- var impl = ReactDebugCurrentFrame.getCurrentStack;
412
-
413
- if (impl) {
414
- stack += impl() || '';
415
- }
416
-
417
- return stack;
418
- };
419
- }
420
-
421
- // -----------------------------------------------------------------------------
422
-
423
- var enableScopeAPI = false; // Experimental Create Event Handle API.
424
- var enableCacheElement = false;
425
- var enableTransitionTracing = false; // No known bugs, but needs performance testing
426
-
427
- var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber
428
- // stuff. Intended to enable React core members to more easily debug scheduling
429
- // issues in DEV builds.
430
-
431
- var enableDebugTracing = false; // Track which Fiber(s) schedule render work.
432
-
433
- var ReactSharedInternals = {
434
- ReactCurrentDispatcher: ReactCurrentDispatcher,
435
- ReactCurrentBatchConfig: ReactCurrentBatchConfig,
436
- ReactCurrentOwner: ReactCurrentOwner
437
- };
438
-
439
- {
440
- ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame;
441
- ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue;
442
- }
443
-
444
- // by calls to these methods by a Babel plugin.
445
- //
446
- // In PROD (or in packages without access to React internals),
447
- // they are left as they are instead.
448
-
449
- function warn(format) {
450
- {
451
- {
452
- for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
453
- args[_key - 1] = arguments[_key];
454
- }
455
-
456
- printWarning('warn', format, args);
457
- }
458
- }
459
- }
460
- function error(format) {
461
- {
462
- {
463
- for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
464
- args[_key2 - 1] = arguments[_key2];
465
- }
466
-
467
- printWarning('error', format, args);
468
- }
469
- }
470
- }
471
-
472
- function printWarning(level, format, args) {
473
- // When changing this logic, you might want to also
474
- // update consoleWithStackDev.www.js as well.
475
- {
476
- var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
477
- var stack = ReactDebugCurrentFrame.getStackAddendum();
478
-
479
- if (stack !== '') {
480
- format += '%s';
481
- args = args.concat([stack]);
482
- } // eslint-disable-next-line react-internal/safe-string-coercion
483
-
484
-
485
- var argsWithFormat = args.map(function (item) {
486
- return String(item);
487
- }); // Careful: RN currently depends on this prefix
488
-
489
- argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
490
- // breaks IE9: https://github.com/facebook/react/issues/13610
491
- // eslint-disable-next-line react-internal/no-production-logging
492
-
493
- Function.prototype.apply.call(console[level], console, argsWithFormat);
494
- }
495
- }
496
-
497
- var didWarnStateUpdateForUnmountedComponent = {};
498
-
499
- function warnNoop(publicInstance, callerName) {
500
- {
501
- var _constructor = publicInstance.constructor;
502
- var componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass';
503
- var warningKey = componentName + "." + callerName;
504
-
505
- if (didWarnStateUpdateForUnmountedComponent[warningKey]) {
506
- return;
507
- }
508
-
509
- error("Can't call %s on a component that is not yet mounted. " + 'This is a no-op, but it might indicate a bug in your application. ' + 'Instead, assign to `this.state` directly or define a `state = {};` ' + 'class property with the desired state in the %s component.', callerName, componentName);
510
-
511
- didWarnStateUpdateForUnmountedComponent[warningKey] = true;
512
- }
513
- }
514
- /**
515
- * This is the abstract API for an update queue.
516
- */
517
-
518
-
519
- var ReactNoopUpdateQueue = {
520
- /**
521
- * Checks whether or not this composite component is mounted.
522
- * @param {ReactClass} publicInstance The instance we want to test.
523
- * @return {boolean} True if mounted, false otherwise.
524
- * @protected
525
- * @final
526
- */
527
- isMounted: function (publicInstance) {
528
- return false;
529
- },
530
-
531
- /**
532
- * Forces an update. This should only be invoked when it is known with
533
- * certainty that we are **not** in a DOM transaction.
534
- *
535
- * You may want to call this when you know that some deeper aspect of the
536
- * component's state has changed but `setState` was not called.
537
- *
538
- * This will not invoke `shouldComponentUpdate`, but it will invoke
539
- * `componentWillUpdate` and `componentDidUpdate`.
540
- *
541
- * @param {ReactClass} publicInstance The instance that should rerender.
542
- * @param {?function} callback Called after component is updated.
543
- * @param {?string} callerName name of the calling function in the public API.
544
- * @internal
545
- */
546
- enqueueForceUpdate: function (publicInstance, callback, callerName) {
547
- warnNoop(publicInstance, 'forceUpdate');
548
- },
549
-
550
- /**
551
- * Replaces all of the state. Always use this or `setState` to mutate state.
552
- * You should treat `this.state` as immutable.
553
- *
554
- * There is no guarantee that `this.state` will be immediately updated, so
555
- * accessing `this.state` after calling this method may return the old value.
556
- *
557
- * @param {ReactClass} publicInstance The instance that should rerender.
558
- * @param {object} completeState Next state.
559
- * @param {?function} callback Called after component is updated.
560
- * @param {?string} callerName name of the calling function in the public API.
561
- * @internal
562
- */
563
- enqueueReplaceState: function (publicInstance, completeState, callback, callerName) {
564
- warnNoop(publicInstance, 'replaceState');
565
- },
566
-
567
- /**
568
- * Sets a subset of the state. This only exists because _pendingState is
569
- * internal. This provides a merging strategy that is not available to deep
570
- * properties which is confusing. TODO: Expose pendingState or don't use it
571
- * during the merge.
572
- *
573
- * @param {ReactClass} publicInstance The instance that should rerender.
574
- * @param {object} partialState Next partial state to be merged with state.
575
- * @param {?function} callback Called after component is updated.
576
- * @param {?string} Name of the calling function in the public API.
577
- * @internal
578
- */
579
- enqueueSetState: function (publicInstance, partialState, callback, callerName) {
580
- warnNoop(publicInstance, 'setState');
581
- }
582
- };
583
-
584
- var assign = Object.assign;
585
-
586
- var emptyObject = {};
587
-
588
- {
589
- Object.freeze(emptyObject);
590
- }
591
- /**
592
- * Base class helpers for the updating state of a component.
593
- */
594
-
595
-
596
- function Component(props, context, updater) {
597
- this.props = props;
598
- this.context = context; // If a component has string refs, we will assign a different object later.
599
-
600
- this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the
601
- // renderer.
602
-
603
- this.updater = updater || ReactNoopUpdateQueue;
604
- }
605
-
606
- Component.prototype.isReactComponent = {};
607
- /**
608
- * Sets a subset of the state. Always use this to mutate
609
- * state. You should treat `this.state` as immutable.
610
- *
611
- * There is no guarantee that `this.state` will be immediately updated, so
612
- * accessing `this.state` after calling this method may return the old value.
613
- *
614
- * There is no guarantee that calls to `setState` will run synchronously,
615
- * as they may eventually be batched together. You can provide an optional
616
- * callback that will be executed when the call to setState is actually
617
- * completed.
618
- *
619
- * When a function is provided to setState, it will be called at some point in
620
- * the future (not synchronously). It will be called with the up to date
621
- * component arguments (state, props, context). These values can be different
622
- * from this.* because your function may be called after receiveProps but before
623
- * shouldComponentUpdate, and this new state, props, and context will not yet be
624
- * assigned to this.
625
- *
626
- * @param {object|function} partialState Next partial state or function to
627
- * produce next partial state to be merged with current state.
628
- * @param {?function} callback Called after state is updated.
629
- * @final
630
- * @protected
631
- */
632
-
633
- Component.prototype.setState = function (partialState, callback) {
634
- if (typeof partialState !== 'object' && typeof partialState !== 'function' && partialState != null) {
635
- throw new Error('setState(...): takes an object of state variables to update or a ' + 'function which returns an object of state variables.');
636
- }
637
-
638
- this.updater.enqueueSetState(this, partialState, callback, 'setState');
639
- };
640
- /**
641
- * Forces an update. This should only be invoked when it is known with
642
- * certainty that we are **not** in a DOM transaction.
643
- *
644
- * You may want to call this when you know that some deeper aspect of the
645
- * component's state has changed but `setState` was not called.
646
- *
647
- * This will not invoke `shouldComponentUpdate`, but it will invoke
648
- * `componentWillUpdate` and `componentDidUpdate`.
649
- *
650
- * @param {?function} callback Called after update is complete.
651
- * @final
652
- * @protected
653
- */
654
-
655
-
656
- Component.prototype.forceUpdate = function (callback) {
657
- this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
658
- };
659
- /**
660
- * Deprecated APIs. These APIs used to exist on classic React classes but since
661
- * we would like to deprecate them, we're not going to move them over to this
662
- * modern base class. Instead, we define a getter that warns if it's accessed.
663
- */
664
-
665
-
666
- {
667
- var deprecatedAPIs = {
668
- isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'],
669
- replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).']
670
- };
671
-
672
- var defineDeprecationWarning = function (methodName, info) {
673
- Object.defineProperty(Component.prototype, methodName, {
674
- get: function () {
675
- warn('%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]);
676
-
677
- return undefined;
678
- }
679
- });
680
- };
681
-
682
- for (var fnName in deprecatedAPIs) {
683
- if (deprecatedAPIs.hasOwnProperty(fnName)) {
684
- defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
685
- }
686
- }
687
- }
688
-
689
- function ComponentDummy() {}
690
-
691
- ComponentDummy.prototype = Component.prototype;
692
- /**
693
- * Convenience component with default shallow equality check for sCU.
694
- */
695
-
696
- function PureComponent(props, context, updater) {
697
- this.props = props;
698
- this.context = context; // If a component has string refs, we will assign a different object later.
699
-
700
- this.refs = emptyObject;
701
- this.updater = updater || ReactNoopUpdateQueue;
702
- }
703
-
704
- var pureComponentPrototype = PureComponent.prototype = new ComponentDummy();
705
- pureComponentPrototype.constructor = PureComponent; // Avoid an extra prototype jump for these methods.
706
-
707
- assign(pureComponentPrototype, Component.prototype);
708
- pureComponentPrototype.isPureReactComponent = true;
709
-
710
- // an immutable object with a single mutable value
711
- function createRef() {
712
- var refObject = {
713
- current: null
714
- };
715
-
716
- {
717
- Object.seal(refObject);
718
- }
719
-
720
- return refObject;
721
- }
722
-
723
- var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare
724
-
725
- function isArray(a) {
726
- return isArrayImpl(a);
727
- }
728
-
729
- /*
730
- * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol
731
- * and Temporal.* types. See https://github.com/facebook/react/pull/22064.
732
- *
733
- * The functions in this module will throw an easier-to-understand,
734
- * easier-to-debug exception with a clear errors message message explaining the
735
- * problem. (Instead of a confusing exception thrown inside the implementation
736
- * of the `value` object).
737
- */
738
- // $FlowFixMe only called in DEV, so void return is not possible.
739
- function typeName(value) {
740
- {
741
- // toStringTag is needed for namespaced types like Temporal.Instant
742
- var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;
743
- var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';
744
- return type;
745
- }
746
- } // $FlowFixMe only called in DEV, so void return is not possible.
747
-
748
-
749
- function willCoercionThrow(value) {
750
- {
751
- try {
752
- testStringCoercion(value);
753
- return false;
754
- } catch (e) {
755
- return true;
756
- }
757
- }
758
- }
759
-
760
- function testStringCoercion(value) {
761
- // If you ended up here by following an exception call stack, here's what's
762
- // happened: you supplied an object or symbol value to React (as a prop, key,
763
- // DOM attribute, CSS property, string ref, etc.) and when React tried to
764
- // coerce it to a string using `'' + value`, an exception was thrown.
765
- //
766
- // The most common types that will cause this exception are `Symbol` instances
767
- // and Temporal objects like `Temporal.Instant`. But any object that has a
768
- // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
769
- // exception. (Library authors do this to prevent users from using built-in
770
- // numeric operators like `+` or comparison operators like `>=` because custom
771
- // methods are needed to perform accurate arithmetic or comparison.)
772
- //
773
- // To fix the problem, coerce this object or symbol value to a string before
774
- // passing it to React. The most reliable way is usually `String(value)`.
775
- //
776
- // To find which value is throwing, check the browser or debugger console.
777
- // Before this exception was thrown, there should be `console.error` output
778
- // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
779
- // problem and how that type was used: key, atrribute, input value prop, etc.
780
- // In most cases, this console output also shows the component and its
781
- // ancestor components where the exception happened.
782
- //
783
- // eslint-disable-next-line react-internal/safe-string-coercion
784
- return '' + value;
785
- }
786
- function checkKeyStringCoercion(value) {
787
- {
788
- if (willCoercionThrow(value)) {
789
- error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));
790
-
791
- return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
792
- }
793
- }
794
- }
795
-
796
- function getWrappedName(outerType, innerType, wrapperName) {
797
- var displayName = outerType.displayName;
798
-
799
- if (displayName) {
800
- return displayName;
801
- }
802
-
803
- var functionName = innerType.displayName || innerType.name || '';
804
- return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
805
- } // Keep in sync with react-reconciler/getComponentNameFromFiber
806
-
807
-
808
- function getContextName(type) {
809
- return type.displayName || 'Context';
810
- } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.
811
-
812
-
813
- function getComponentNameFromType(type) {
814
- if (type == null) {
815
- // Host root, text node or just invalid type.
816
- return null;
817
- }
818
-
819
- {
820
- if (typeof type.tag === 'number') {
821
- error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
822
- }
823
- }
824
-
825
- if (typeof type === 'function') {
826
- return type.displayName || type.name || null;
827
- }
828
-
829
- if (typeof type === 'string') {
830
- return type;
831
- }
832
-
833
- switch (type) {
834
- case REACT_FRAGMENT_TYPE:
835
- return 'Fragment';
836
-
837
- case REACT_PORTAL_TYPE:
838
- return 'Portal';
839
-
840
- case REACT_PROFILER_TYPE:
841
- return 'Profiler';
842
-
843
- case REACT_STRICT_MODE_TYPE:
844
- return 'StrictMode';
845
-
846
- case REACT_SUSPENSE_TYPE:
847
- return 'Suspense';
848
-
849
- case REACT_SUSPENSE_LIST_TYPE:
850
- return 'SuspenseList';
851
-
852
- }
853
-
854
- if (typeof type === 'object') {
855
- switch (type.$$typeof) {
856
- case REACT_CONTEXT_TYPE:
857
- var context = type;
858
- return getContextName(context) + '.Consumer';
859
-
860
- case REACT_PROVIDER_TYPE:
861
- var provider = type;
862
- return getContextName(provider._context) + '.Provider';
863
-
864
- case REACT_FORWARD_REF_TYPE:
865
- return getWrappedName(type, type.render, 'ForwardRef');
866
-
867
- case REACT_MEMO_TYPE:
868
- var outerName = type.displayName || null;
869
-
870
- if (outerName !== null) {
871
- return outerName;
872
- }
873
-
874
- return getComponentNameFromType(type.type) || 'Memo';
875
-
876
- case REACT_LAZY_TYPE:
877
- {
878
- var lazyComponent = type;
879
- var payload = lazyComponent._payload;
880
- var init = lazyComponent._init;
881
-
882
- try {
883
- return getComponentNameFromType(init(payload));
884
- } catch (x) {
885
- return null;
886
- }
887
- }
888
-
889
- // eslint-disable-next-line no-fallthrough
890
- }
891
- }
892
-
893
- return null;
894
- }
895
-
896
- var hasOwnProperty = Object.prototype.hasOwnProperty;
897
-
898
- var RESERVED_PROPS = {
899
- key: true,
900
- ref: true,
901
- __self: true,
902
- __source: true
903
- };
904
- var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs;
905
-
906
- {
907
- didWarnAboutStringRefs = {};
908
- }
909
-
910
- function hasValidRef(config) {
911
- {
912
- if (hasOwnProperty.call(config, 'ref')) {
913
- var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;
914
-
915
- if (getter && getter.isReactWarning) {
916
- return false;
917
- }
918
- }
919
- }
920
-
921
- return config.ref !== undefined;
922
- }
923
-
924
- function hasValidKey(config) {
925
- {
926
- if (hasOwnProperty.call(config, 'key')) {
927
- var getter = Object.getOwnPropertyDescriptor(config, 'key').get;
928
-
929
- if (getter && getter.isReactWarning) {
930
- return false;
931
- }
932
- }
933
- }
934
-
935
- return config.key !== undefined;
936
- }
937
-
938
- function defineKeyPropWarningGetter(props, displayName) {
939
- var warnAboutAccessingKey = function () {
940
- {
941
- if (!specialPropKeyWarningShown) {
942
- specialPropKeyWarningShown = true;
943
-
944
- error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
945
- }
946
- }
947
- };
948
-
949
- warnAboutAccessingKey.isReactWarning = true;
950
- Object.defineProperty(props, 'key', {
951
- get: warnAboutAccessingKey,
952
- configurable: true
953
- });
954
- }
955
-
956
- function defineRefPropWarningGetter(props, displayName) {
957
- var warnAboutAccessingRef = function () {
958
- {
959
- if (!specialPropRefWarningShown) {
960
- specialPropRefWarningShown = true;
961
-
962
- error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
963
- }
964
- }
965
- };
966
-
967
- warnAboutAccessingRef.isReactWarning = true;
968
- Object.defineProperty(props, 'ref', {
969
- get: warnAboutAccessingRef,
970
- configurable: true
971
- });
972
- }
973
-
974
- function warnIfStringRefCannotBeAutoConverted(config) {
975
- {
976
- if (typeof config.ref === 'string' && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) {
977
- var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);
978
-
979
- if (!didWarnAboutStringRefs[componentName]) {
980
- error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref);
981
-
982
- didWarnAboutStringRefs[componentName] = true;
983
- }
984
- }
985
- }
986
- }
987
- /**
988
- * Factory method to create a new React element. This no longer adheres to
989
- * the class pattern, so do not use new to call it. Also, instanceof check
990
- * will not work. Instead test $$typeof field against Symbol.for('react.element') to check
991
- * if something is a React Element.
992
- *
993
- * @param {*} type
994
- * @param {*} props
995
- * @param {*} key
996
- * @param {string|object} ref
997
- * @param {*} owner
998
- * @param {*} self A *temporary* helper to detect places where `this` is
999
- * different from the `owner` when React.createElement is called, so that we
1000
- * can warn. We want to get rid of owner and replace string `ref`s with arrow
1001
- * functions, and as long as `this` and owner are the same, there will be no
1002
- * change in behavior.
1003
- * @param {*} source An annotation object (added by a transpiler or otherwise)
1004
- * indicating filename, line number, and/or other information.
1005
- * @internal
1006
- */
1007
-
1008
-
1009
- var ReactElement = function (type, key, ref, self, source, owner, props) {
1010
- var element = {
1011
- // This tag allows us to uniquely identify this as a React Element
1012
- $$typeof: REACT_ELEMENT_TYPE,
1013
- // Built-in properties that belong on the element
1014
- type: type,
1015
- key: key,
1016
- ref: ref,
1017
- props: props,
1018
- // Record the component responsible for creating this element.
1019
- _owner: owner
1020
- };
1021
-
1022
- {
1023
- // The validation flag is currently mutative. We put it on
1024
- // an external backing store so that we can freeze the whole object.
1025
- // This can be replaced with a WeakMap once they are implemented in
1026
- // commonly used development environments.
1027
- element._store = {}; // To make comparing ReactElements easier for testing purposes, we make
1028
- // the validation flag non-enumerable (where possible, which should
1029
- // include every environment we run tests in), so the test framework
1030
- // ignores it.
1031
-
1032
- Object.defineProperty(element._store, 'validated', {
1033
- configurable: false,
1034
- enumerable: false,
1035
- writable: true,
1036
- value: false
1037
- }); // self and source are DEV only properties.
1038
-
1039
- Object.defineProperty(element, '_self', {
1040
- configurable: false,
1041
- enumerable: false,
1042
- writable: false,
1043
- value: self
1044
- }); // Two elements created in two different places should be considered
1045
- // equal for testing purposes and therefore we hide it from enumeration.
1046
-
1047
- Object.defineProperty(element, '_source', {
1048
- configurable: false,
1049
- enumerable: false,
1050
- writable: false,
1051
- value: source
1052
- });
1053
-
1054
- if (Object.freeze) {
1055
- Object.freeze(element.props);
1056
- Object.freeze(element);
1057
- }
1058
- }
1059
-
1060
- return element;
1061
- };
1062
- /**
1063
- * Create and return a new ReactElement of the given type.
1064
- * See https://reactjs.org/docs/react-api.html#createelement
1065
- */
1066
-
1067
- function createElement(type, config, children) {
1068
- var propName; // Reserved names are extracted
1069
-
1070
- var props = {};
1071
- var key = null;
1072
- var ref = null;
1073
- var self = null;
1074
- var source = null;
1075
-
1076
- if (config != null) {
1077
- if (hasValidRef(config)) {
1078
- ref = config.ref;
1079
-
1080
- {
1081
- warnIfStringRefCannotBeAutoConverted(config);
1082
- }
1083
- }
1084
-
1085
- if (hasValidKey(config)) {
1086
- {
1087
- checkKeyStringCoercion(config.key);
1088
- }
1089
-
1090
- key = '' + config.key;
1091
- }
1092
-
1093
- self = config.__self === undefined ? null : config.__self;
1094
- source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object
1095
-
1096
- for (propName in config) {
1097
- if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
1098
- props[propName] = config[propName];
1099
- }
1100
- }
1101
- } // Children can be more than one argument, and those are transferred onto
1102
- // the newly allocated props object.
1103
-
1104
-
1105
- var childrenLength = arguments.length - 2;
1106
-
1107
- if (childrenLength === 1) {
1108
- props.children = children;
1109
- } else if (childrenLength > 1) {
1110
- var childArray = Array(childrenLength);
1111
-
1112
- for (var i = 0; i < childrenLength; i++) {
1113
- childArray[i] = arguments[i + 2];
1114
- }
1115
-
1116
- {
1117
- if (Object.freeze) {
1118
- Object.freeze(childArray);
1119
- }
1120
- }
1121
-
1122
- props.children = childArray;
1123
- } // Resolve default props
1124
-
1125
-
1126
- if (type && type.defaultProps) {
1127
- var defaultProps = type.defaultProps;
1128
-
1129
- for (propName in defaultProps) {
1130
- if (props[propName] === undefined) {
1131
- props[propName] = defaultProps[propName];
1132
- }
1133
- }
1134
- }
1135
-
1136
- {
1137
- if (key || ref) {
1138
- var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;
1139
-
1140
- if (key) {
1141
- defineKeyPropWarningGetter(props, displayName);
1142
- }
1143
-
1144
- if (ref) {
1145
- defineRefPropWarningGetter(props, displayName);
1146
- }
1147
- }
1148
- }
1149
-
1150
- return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
1151
- }
1152
- function cloneAndReplaceKey(oldElement, newKey) {
1153
- var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);
1154
- return newElement;
1155
- }
1156
- /**
1157
- * Clone and return a new ReactElement using element as the starting point.
1158
- * See https://reactjs.org/docs/react-api.html#cloneelement
1159
- */
1160
-
1161
- function cloneElement(element, config, children) {
1162
- if (element === null || element === undefined) {
1163
- throw new Error("React.cloneElement(...): The argument must be a React element, but you passed " + element + ".");
1164
- }
1165
-
1166
- var propName; // Original props are copied
1167
-
1168
- var props = assign({}, element.props); // Reserved names are extracted
1169
-
1170
- var key = element.key;
1171
- var ref = element.ref; // Self is preserved since the owner is preserved.
1172
-
1173
- var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a
1174
- // transpiler, and the original source is probably a better indicator of the
1175
- // true owner.
1176
-
1177
- var source = element._source; // Owner will be preserved, unless ref is overridden
1178
-
1179
- var owner = element._owner;
1180
-
1181
- if (config != null) {
1182
- if (hasValidRef(config)) {
1183
- // Silently steal the ref from the parent.
1184
- ref = config.ref;
1185
- owner = ReactCurrentOwner.current;
1186
- }
1187
-
1188
- if (hasValidKey(config)) {
1189
- {
1190
- checkKeyStringCoercion(config.key);
1191
- }
1192
-
1193
- key = '' + config.key;
1194
- } // Remaining properties override existing props
1195
-
1196
-
1197
- var defaultProps;
1198
-
1199
- if (element.type && element.type.defaultProps) {
1200
- defaultProps = element.type.defaultProps;
1201
- }
1202
-
1203
- for (propName in config) {
1204
- if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
1205
- if (config[propName] === undefined && defaultProps !== undefined) {
1206
- // Resolve default props
1207
- props[propName] = defaultProps[propName];
1208
- } else {
1209
- props[propName] = config[propName];
1210
- }
1211
- }
1212
- }
1213
- } // Children can be more than one argument, and those are transferred onto
1214
- // the newly allocated props object.
1215
-
1216
-
1217
- var childrenLength = arguments.length - 2;
1218
-
1219
- if (childrenLength === 1) {
1220
- props.children = children;
1221
- } else if (childrenLength > 1) {
1222
- var childArray = Array(childrenLength);
1223
-
1224
- for (var i = 0; i < childrenLength; i++) {
1225
- childArray[i] = arguments[i + 2];
1226
- }
1227
-
1228
- props.children = childArray;
1229
- }
1230
-
1231
- return ReactElement(element.type, key, ref, self, source, owner, props);
1232
- }
1233
- /**
1234
- * Verifies the object is a ReactElement.
1235
- * See https://reactjs.org/docs/react-api.html#isvalidelement
1236
- * @param {?object} object
1237
- * @return {boolean} True if `object` is a ReactElement.
1238
- * @final
1239
- */
1240
-
1241
- function isValidElement(object) {
1242
- return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
1243
- }
1244
-
1245
- var SEPARATOR = '.';
1246
- var SUBSEPARATOR = ':';
1247
- /**
1248
- * Escape and wrap key so it is safe to use as a reactid
1249
- *
1250
- * @param {string} key to be escaped.
1251
- * @return {string} the escaped key.
1252
- */
1253
-
1254
- function escape(key) {
1255
- var escapeRegex = /[=:]/g;
1256
- var escaperLookup = {
1257
- '=': '=0',
1258
- ':': '=2'
1259
- };
1260
- var escapedString = key.replace(escapeRegex, function (match) {
1261
- return escaperLookup[match];
1262
- });
1263
- return '$' + escapedString;
1264
- }
1265
- /**
1266
- * TODO: Test that a single child and an array with one item have the same key
1267
- * pattern.
1268
- */
1269
-
1270
-
1271
- var didWarnAboutMaps = false;
1272
- var userProvidedKeyEscapeRegex = /\/+/g;
1273
-
1274
- function escapeUserProvidedKey(text) {
1275
- return text.replace(userProvidedKeyEscapeRegex, '$&/');
1276
- }
1277
- /**
1278
- * Generate a key string that identifies a element within a set.
1279
- *
1280
- * @param {*} element A element that could contain a manual key.
1281
- * @param {number} index Index that is used if a manual key is not provided.
1282
- * @return {string}
1283
- */
1284
-
1285
-
1286
- function getElementKey(element, index) {
1287
- // Do some typechecking here since we call this blindly. We want to ensure
1288
- // that we don't block potential future ES APIs.
1289
- if (typeof element === 'object' && element !== null && element.key != null) {
1290
- // Explicit key
1291
- {
1292
- checkKeyStringCoercion(element.key);
1293
- }
1294
-
1295
- return escape('' + element.key);
1296
- } // Implicit key determined by the index in the set
1297
-
1298
-
1299
- return index.toString(36);
1300
- }
1301
-
1302
- function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
1303
- var type = typeof children;
1304
-
1305
- if (type === 'undefined' || type === 'boolean') {
1306
- // All of the above are perceived as null.
1307
- children = null;
1308
- }
1309
-
1310
- var invokeCallback = false;
1311
-
1312
- if (children === null) {
1313
- invokeCallback = true;
1314
- } else {
1315
- switch (type) {
1316
- case 'string':
1317
- case 'number':
1318
- invokeCallback = true;
1319
- break;
1320
-
1321
- case 'object':
1322
- switch (children.$$typeof) {
1323
- case REACT_ELEMENT_TYPE:
1324
- case REACT_PORTAL_TYPE:
1325
- invokeCallback = true;
1326
- }
1327
-
1328
- }
1329
- }
1330
-
1331
- if (invokeCallback) {
1332
- var _child = children;
1333
- var mappedChild = callback(_child); // If it's the only child, treat the name as if it was wrapped in an array
1334
- // so that it's consistent if the number of children grows:
1335
-
1336
- var childKey = nameSoFar === '' ? SEPARATOR + getElementKey(_child, 0) : nameSoFar;
1337
-
1338
- if (isArray(mappedChild)) {
1339
- var escapedChildKey = '';
1340
-
1341
- if (childKey != null) {
1342
- escapedChildKey = escapeUserProvidedKey(childKey) + '/';
1343
- }
1344
-
1345
- mapIntoArray(mappedChild, array, escapedChildKey, '', function (c) {
1346
- return c;
1347
- });
1348
- } else if (mappedChild != null) {
1349
- if (isValidElement(mappedChild)) {
1350
- {
1351
- // The `if` statement here prevents auto-disabling of the safe
1352
- // coercion ESLint rule, so we must manually disable it below.
1353
- // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key
1354
- if (mappedChild.key && (!_child || _child.key !== mappedChild.key)) {
1355
- checkKeyStringCoercion(mappedChild.key);
1356
- }
1357
- }
1358
-
1359
- mappedChild = cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as
1360
- // traverseAllChildren used to do for objects as children
1361
- escapedPrefix + ( // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key
1362
- mappedChild.key && (!_child || _child.key !== mappedChild.key) ? // $FlowFixMe Flow incorrectly thinks existing element's key can be a number
1363
- // eslint-disable-next-line react-internal/safe-string-coercion
1364
- escapeUserProvidedKey('' + mappedChild.key) + '/' : '') + childKey);
1365
- }
1366
-
1367
- array.push(mappedChild);
1368
- }
1369
-
1370
- return 1;
1371
- }
1372
-
1373
- var child;
1374
- var nextName;
1375
- var subtreeCount = 0; // Count of children found in the current subtree.
1376
-
1377
- var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;
1378
-
1379
- if (isArray(children)) {
1380
- for (var i = 0; i < children.length; i++) {
1381
- child = children[i];
1382
- nextName = nextNamePrefix + getElementKey(child, i);
1383
- subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
1384
- }
1385
- } else {
1386
- var iteratorFn = getIteratorFn(children);
1387
-
1388
- if (typeof iteratorFn === 'function') {
1389
- var iterableChildren = children;
1390
-
1391
- {
1392
- // Warn about using Maps as children
1393
- if (iteratorFn === iterableChildren.entries) {
1394
- if (!didWarnAboutMaps) {
1395
- warn('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.');
1396
- }
1397
-
1398
- didWarnAboutMaps = true;
1399
- }
1400
- }
1401
-
1402
- var iterator = iteratorFn.call(iterableChildren);
1403
- var step;
1404
- var ii = 0;
1405
-
1406
- while (!(step = iterator.next()).done) {
1407
- child = step.value;
1408
- nextName = nextNamePrefix + getElementKey(child, ii++);
1409
- subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
1410
- }
1411
- } else if (type === 'object') {
1412
- // eslint-disable-next-line react-internal/safe-string-coercion
1413
- var childrenString = String(children);
1414
- throw new Error("Objects are not valid as a React child (found: " + (childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.');
1415
- }
1416
- }
1417
-
1418
- return subtreeCount;
1419
- }
1420
-
1421
- /**
1422
- * Maps children that are typically specified as `props.children`.
1423
- *
1424
- * See https://reactjs.org/docs/react-api.html#reactchildrenmap
1425
- *
1426
- * The provided mapFunction(child, index) will be called for each
1427
- * leaf child.
1428
- *
1429
- * @param {?*} children Children tree container.
1430
- * @param {function(*, int)} func The map function.
1431
- * @param {*} context Context for mapFunction.
1432
- * @return {object} Object containing the ordered map of results.
1433
- */
1434
- function mapChildren(children, func, context) {
1435
- if (children == null) {
1436
- return children;
1437
- }
1438
-
1439
- var result = [];
1440
- var count = 0;
1441
- mapIntoArray(children, result, '', '', function (child) {
1442
- return func.call(context, child, count++);
1443
- });
1444
- return result;
1445
- }
1446
- /**
1447
- * Count the number of children that are typically specified as
1448
- * `props.children`.
1449
- *
1450
- * See https://reactjs.org/docs/react-api.html#reactchildrencount
1451
- *
1452
- * @param {?*} children Children tree container.
1453
- * @return {number} The number of children.
1454
- */
1455
-
1456
-
1457
- function countChildren(children) {
1458
- var n = 0;
1459
- mapChildren(children, function () {
1460
- n++; // Don't return anything
1461
- });
1462
- return n;
1463
- }
1464
-
1465
- /**
1466
- * Iterates through children that are typically specified as `props.children`.
1467
- *
1468
- * See https://reactjs.org/docs/react-api.html#reactchildrenforeach
1469
- *
1470
- * The provided forEachFunc(child, index) will be called for each
1471
- * leaf child.
1472
- *
1473
- * @param {?*} children Children tree container.
1474
- * @param {function(*, int)} forEachFunc
1475
- * @param {*} forEachContext Context for forEachContext.
1476
- */
1477
- function forEachChildren(children, forEachFunc, forEachContext) {
1478
- mapChildren(children, function () {
1479
- forEachFunc.apply(this, arguments); // Don't return anything.
1480
- }, forEachContext);
1481
- }
1482
- /**
1483
- * Flatten a children object (typically specified as `props.children`) and
1484
- * return an array with appropriately re-keyed children.
1485
- *
1486
- * See https://reactjs.org/docs/react-api.html#reactchildrentoarray
1487
- */
1488
-
1489
-
1490
- function toArray(children) {
1491
- return mapChildren(children, function (child) {
1492
- return child;
1493
- }) || [];
1494
- }
1495
- /**
1496
- * Returns the first child in a collection of children and verifies that there
1497
- * is only one child in the collection.
1498
- *
1499
- * See https://reactjs.org/docs/react-api.html#reactchildrenonly
1500
- *
1501
- * The current implementation of this function assumes that a single child gets
1502
- * passed without a wrapper, but the purpose of this helper function is to
1503
- * abstract away the particular structure of children.
1504
- *
1505
- * @param {?object} children Child collection structure.
1506
- * @return {ReactElement} The first and only `ReactElement` contained in the
1507
- * structure.
1508
- */
1509
-
1510
-
1511
- function onlyChild(children) {
1512
- if (!isValidElement(children)) {
1513
- throw new Error('React.Children.only expected to receive a single React element child.');
1514
- }
1515
-
1516
- return children;
1517
- }
1518
-
1519
- function createContext(defaultValue) {
1520
- // TODO: Second argument used to be an optional `calculateChangedBits`
1521
- // function. Warn to reserve for future use?
1522
- var context = {
1523
- $$typeof: REACT_CONTEXT_TYPE,
1524
- // As a workaround to support multiple concurrent renderers, we categorize
1525
- // some renderers as primary and others as secondary. We only expect
1526
- // there to be two concurrent renderers at most: React Native (primary) and
1527
- // Fabric (secondary); React DOM (primary) and React ART (secondary).
1528
- // Secondary renderers store their context values on separate fields.
1529
- _currentValue: defaultValue,
1530
- _currentValue2: defaultValue,
1531
- // Used to track how many concurrent renderers this context currently
1532
- // supports within in a single renderer. Such as parallel server rendering.
1533
- _threadCount: 0,
1534
- // These are circular
1535
- Provider: null,
1536
- Consumer: null,
1537
- // Add these to use same hidden class in VM as ServerContext
1538
- _defaultValue: null,
1539
- _globalName: null
1540
- };
1541
- context.Provider = {
1542
- $$typeof: REACT_PROVIDER_TYPE,
1543
- _context: context
1544
- };
1545
- var hasWarnedAboutUsingNestedContextConsumers = false;
1546
- var hasWarnedAboutUsingConsumerProvider = false;
1547
- var hasWarnedAboutDisplayNameOnConsumer = false;
1548
-
1549
- {
1550
- // A separate object, but proxies back to the original context object for
1551
- // backwards compatibility. It has a different $$typeof, so we can properly
1552
- // warn for the incorrect usage of Context as a Consumer.
1553
- var Consumer = {
1554
- $$typeof: REACT_CONTEXT_TYPE,
1555
- _context: context
1556
- }; // $FlowFixMe: Flow complains about not setting a value, which is intentional here
1557
-
1558
- Object.defineProperties(Consumer, {
1559
- Provider: {
1560
- get: function () {
1561
- if (!hasWarnedAboutUsingConsumerProvider) {
1562
- hasWarnedAboutUsingConsumerProvider = true;
1563
-
1564
- error('Rendering <Context.Consumer.Provider> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Provider> instead?');
1565
- }
1566
-
1567
- return context.Provider;
1568
- },
1569
- set: function (_Provider) {
1570
- context.Provider = _Provider;
1571
- }
1572
- },
1573
- _currentValue: {
1574
- get: function () {
1575
- return context._currentValue;
1576
- },
1577
- set: function (_currentValue) {
1578
- context._currentValue = _currentValue;
1579
- }
1580
- },
1581
- _currentValue2: {
1582
- get: function () {
1583
- return context._currentValue2;
1584
- },
1585
- set: function (_currentValue2) {
1586
- context._currentValue2 = _currentValue2;
1587
- }
1588
- },
1589
- _threadCount: {
1590
- get: function () {
1591
- return context._threadCount;
1592
- },
1593
- set: function (_threadCount) {
1594
- context._threadCount = _threadCount;
1595
- }
1596
- },
1597
- Consumer: {
1598
- get: function () {
1599
- if (!hasWarnedAboutUsingNestedContextConsumers) {
1600
- hasWarnedAboutUsingNestedContextConsumers = true;
1601
-
1602
- error('Rendering <Context.Consumer.Consumer> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
1603
- }
1604
-
1605
- return context.Consumer;
1606
- }
1607
- },
1608
- displayName: {
1609
- get: function () {
1610
- return context.displayName;
1611
- },
1612
- set: function (displayName) {
1613
- if (!hasWarnedAboutDisplayNameOnConsumer) {
1614
- warn('Setting `displayName` on Context.Consumer has no effect. ' + "You should set it directly on the context with Context.displayName = '%s'.", displayName);
1615
-
1616
- hasWarnedAboutDisplayNameOnConsumer = true;
1617
- }
1618
- }
1619
- }
1620
- }); // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty
1621
-
1622
- context.Consumer = Consumer;
1623
- }
1624
-
1625
- {
1626
- context._currentRenderer = null;
1627
- context._currentRenderer2 = null;
1628
- }
1629
-
1630
- return context;
1631
- }
1632
-
1633
- var Uninitialized = -1;
1634
- var Pending = 0;
1635
- var Resolved = 1;
1636
- var Rejected = 2;
1637
-
1638
- function lazyInitializer(payload) {
1639
- if (payload._status === Uninitialized) {
1640
- var ctor = payload._result;
1641
- var thenable = ctor(); // Transition to the next state.
1642
- // This might throw either because it's missing or throws. If so, we treat it
1643
- // as still uninitialized and try again next time. Which is the same as what
1644
- // happens if the ctor or any wrappers processing the ctor throws. This might
1645
- // end up fixing it if the resolution was a concurrency bug.
1646
-
1647
- thenable.then(function (moduleObject) {
1648
- if (payload._status === Pending || payload._status === Uninitialized) {
1649
- // Transition to the next state.
1650
- var resolved = payload;
1651
- resolved._status = Resolved;
1652
- resolved._result = moduleObject;
1653
- }
1654
- }, function (error) {
1655
- if (payload._status === Pending || payload._status === Uninitialized) {
1656
- // Transition to the next state.
1657
- var rejected = payload;
1658
- rejected._status = Rejected;
1659
- rejected._result = error;
1660
- }
1661
- });
1662
-
1663
- if (payload._status === Uninitialized) {
1664
- // In case, we're still uninitialized, then we're waiting for the thenable
1665
- // to resolve. Set it as pending in the meantime.
1666
- var pending = payload;
1667
- pending._status = Pending;
1668
- pending._result = thenable;
1669
- }
1670
- }
1671
-
1672
- if (payload._status === Resolved) {
1673
- var moduleObject = payload._result;
1674
-
1675
- {
1676
- if (moduleObject === undefined) {
1677
- error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + // Break up imports to avoid accidentally parsing them as dependencies.
1678
- 'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))\n\n" + 'Did you accidentally put curly braces around the import?', moduleObject);
1679
- }
1680
- }
1681
-
1682
- {
1683
- if (!('default' in moduleObject)) {
1684
- error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + // Break up imports to avoid accidentally parsing them as dependencies.
1685
- 'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))", moduleObject);
1686
- }
1687
- }
1688
-
1689
- return moduleObject.default;
1690
- } else {
1691
- throw payload._result;
1692
- }
1693
- }
1694
-
1695
- function lazy(ctor) {
1696
- var payload = {
1697
- // We use these fields to store the result.
1698
- _status: Uninitialized,
1699
- _result: ctor
1700
- };
1701
- var lazyType = {
1702
- $$typeof: REACT_LAZY_TYPE,
1703
- _payload: payload,
1704
- _init: lazyInitializer
1705
- };
1706
-
1707
- {
1708
- // In production, this would just set it on the object.
1709
- var defaultProps;
1710
- var propTypes; // $FlowFixMe
1711
-
1712
- Object.defineProperties(lazyType, {
1713
- defaultProps: {
1714
- configurable: true,
1715
- get: function () {
1716
- return defaultProps;
1717
- },
1718
- set: function (newDefaultProps) {
1719
- error('React.lazy(...): It is not supported to assign `defaultProps` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');
1720
-
1721
- defaultProps = newDefaultProps; // Match production behavior more closely:
1722
- // $FlowFixMe
1723
-
1724
- Object.defineProperty(lazyType, 'defaultProps', {
1725
- enumerable: true
1726
- });
1727
- }
1728
- },
1729
- propTypes: {
1730
- configurable: true,
1731
- get: function () {
1732
- return propTypes;
1733
- },
1734
- set: function (newPropTypes) {
1735
- error('React.lazy(...): It is not supported to assign `propTypes` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');
1736
-
1737
- propTypes = newPropTypes; // Match production behavior more closely:
1738
- // $FlowFixMe
1739
-
1740
- Object.defineProperty(lazyType, 'propTypes', {
1741
- enumerable: true
1742
- });
1743
- }
1744
- }
1745
- });
1746
- }
1747
-
1748
- return lazyType;
1749
- }
1750
-
1751
- function forwardRef(render) {
1752
- {
1753
- if (render != null && render.$$typeof === REACT_MEMO_TYPE) {
1754
- error('forwardRef requires a render function but received a `memo` ' + 'component. Instead of forwardRef(memo(...)), use ' + 'memo(forwardRef(...)).');
1755
- } else if (typeof render !== 'function') {
1756
- error('forwardRef requires a render function but was given %s.', render === null ? 'null' : typeof render);
1757
- } else {
1758
- if (render.length !== 0 && render.length !== 2) {
1759
- error('forwardRef render functions accept exactly two parameters: props and ref. %s', render.length === 1 ? 'Did you forget to use the ref parameter?' : 'Any additional parameter will be undefined.');
1760
- }
1761
- }
1762
-
1763
- if (render != null) {
1764
- if (render.defaultProps != null || render.propTypes != null) {
1765
- error('forwardRef render functions do not support propTypes or defaultProps. ' + 'Did you accidentally pass a React component?');
1766
- }
1767
- }
1768
- }
1769
-
1770
- var elementType = {
1771
- $$typeof: REACT_FORWARD_REF_TYPE,
1772
- render: render
1773
- };
1774
-
1775
- {
1776
- var ownName;
1777
- Object.defineProperty(elementType, 'displayName', {
1778
- enumerable: false,
1779
- configurable: true,
1780
- get: function () {
1781
- return ownName;
1782
- },
1783
- set: function (name) {
1784
- ownName = name; // The inner component shouldn't inherit this display name in most cases,
1785
- // because the component may be used elsewhere.
1786
- // But it's nice for anonymous functions to inherit the name,
1787
- // so that our component-stack generation logic will display their frames.
1788
- // An anonymous function generally suggests a pattern like:
1789
- // React.forwardRef((props, ref) => {...});
1790
- // This kind of inner function is not used elsewhere so the side effect is okay.
1791
-
1792
- if (!render.name && !render.displayName) {
1793
- render.displayName = name;
1794
- }
1795
- }
1796
- });
1797
- }
1798
-
1799
- return elementType;
1800
- }
1801
-
1802
- var REACT_MODULE_REFERENCE;
1803
-
1804
- {
1805
- REACT_MODULE_REFERENCE = Symbol.for('react.module.reference');
1806
- }
1807
-
1808
- function isValidElementType(type) {
1809
- if (typeof type === 'string' || typeof type === 'function') {
1810
- return true;
1811
- } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).
1812
-
1813
-
1814
- if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing ) {
1815
- return true;
1816
- }
1817
-
1818
- if (typeof type === 'object' && type !== null) {
1819
- if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object
1820
- // types supported by any Flight configuration anywhere since
1821
- // we don't know which Flight build this will end up being used
1822
- // with.
1823
- type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) {
1824
- return true;
1825
- }
1826
- }
1827
-
1828
- return false;
1829
- }
1830
-
1831
- function memo(type, compare) {
1832
- {
1833
- if (!isValidElementType(type)) {
1834
- error('memo: The first argument must be a component. Instead ' + 'received: %s', type === null ? 'null' : typeof type);
1835
- }
1836
- }
1837
-
1838
- var elementType = {
1839
- $$typeof: REACT_MEMO_TYPE,
1840
- type: type,
1841
- compare: compare === undefined ? null : compare
1842
- };
1843
-
1844
- {
1845
- var ownName;
1846
- Object.defineProperty(elementType, 'displayName', {
1847
- enumerable: false,
1848
- configurable: true,
1849
- get: function () {
1850
- return ownName;
1851
- },
1852
- set: function (name) {
1853
- ownName = name; // The inner component shouldn't inherit this display name in most cases,
1854
- // because the component may be used elsewhere.
1855
- // But it's nice for anonymous functions to inherit the name,
1856
- // so that our component-stack generation logic will display their frames.
1857
- // An anonymous function generally suggests a pattern like:
1858
- // React.memo((props) => {...});
1859
- // This kind of inner function is not used elsewhere so the side effect is okay.
1860
-
1861
- if (!type.name && !type.displayName) {
1862
- type.displayName = name;
1863
- }
1864
- }
1865
- });
1866
- }
1867
-
1868
- return elementType;
1869
- }
1870
-
1871
- function resolveDispatcher() {
1872
- var dispatcher = ReactCurrentDispatcher.current;
1873
-
1874
- {
1875
- if (dispatcher === null) {
1876
- error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.');
1877
- }
1878
- } // Will result in a null access error if accessed outside render phase. We
1879
- // intentionally don't throw our own error because this is in a hot path.
1880
- // Also helps ensure this is inlined.
1881
-
1882
-
1883
- return dispatcher;
1884
- }
1885
- function useContext(Context) {
1886
- var dispatcher = resolveDispatcher();
1887
-
1888
- {
1889
- // TODO: add a more generic warning for invalid values.
1890
- if (Context._context !== undefined) {
1891
- var realContext = Context._context; // Don't deduplicate because this legitimately causes bugs
1892
- // and nobody should be using this in existing code.
1893
-
1894
- if (realContext.Consumer === Context) {
1895
- error('Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be ' + 'removed in a future major release. Did you mean to call useContext(Context) instead?');
1896
- } else if (realContext.Provider === Context) {
1897
- error('Calling useContext(Context.Provider) is not supported. ' + 'Did you mean to call useContext(Context) instead?');
1898
- }
1899
- }
1900
- }
1901
-
1902
- return dispatcher.useContext(Context);
1903
- }
1904
- function useState(initialState) {
1905
- var dispatcher = resolveDispatcher();
1906
- return dispatcher.useState(initialState);
1907
- }
1908
- function useReducer(reducer, initialArg, init) {
1909
- var dispatcher = resolveDispatcher();
1910
- return dispatcher.useReducer(reducer, initialArg, init);
1911
- }
1912
- function useRef(initialValue) {
1913
- var dispatcher = resolveDispatcher();
1914
- return dispatcher.useRef(initialValue);
1915
- }
1916
- function useEffect(create, deps) {
1917
- var dispatcher = resolveDispatcher();
1918
- return dispatcher.useEffect(create, deps);
1919
- }
1920
- function useInsertionEffect(create, deps) {
1921
- var dispatcher = resolveDispatcher();
1922
- return dispatcher.useInsertionEffect(create, deps);
1923
- }
1924
- function useLayoutEffect(create, deps) {
1925
- var dispatcher = resolveDispatcher();
1926
- return dispatcher.useLayoutEffect(create, deps);
1927
- }
1928
- function useCallback(callback, deps) {
1929
- var dispatcher = resolveDispatcher();
1930
- return dispatcher.useCallback(callback, deps);
1931
- }
1932
- function useMemo(create, deps) {
1933
- var dispatcher = resolveDispatcher();
1934
- return dispatcher.useMemo(create, deps);
1935
- }
1936
- function useImperativeHandle(ref, create, deps) {
1937
- var dispatcher = resolveDispatcher();
1938
- return dispatcher.useImperativeHandle(ref, create, deps);
1939
- }
1940
- function useDebugValue(value, formatterFn) {
1941
- {
1942
- var dispatcher = resolveDispatcher();
1943
- return dispatcher.useDebugValue(value, formatterFn);
1944
- }
1945
- }
1946
- function useTransition() {
1947
- var dispatcher = resolveDispatcher();
1948
- return dispatcher.useTransition();
1949
- }
1950
- function useDeferredValue(value) {
1951
- var dispatcher = resolveDispatcher();
1952
- return dispatcher.useDeferredValue(value);
1953
- }
1954
- function useId() {
1955
- var dispatcher = resolveDispatcher();
1956
- return dispatcher.useId();
1957
- }
1958
- function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
1959
- var dispatcher = resolveDispatcher();
1960
- return dispatcher.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
1961
- }
1962
-
1963
- // Helpers to patch console.logs to avoid logging during side-effect free
1964
- // replaying on render function. This currently only patches the object
1965
- // lazily which won't cover if the log function was extracted eagerly.
1966
- // We could also eagerly patch the method.
1967
- var disabledDepth = 0;
1968
- var prevLog;
1969
- var prevInfo;
1970
- var prevWarn;
1971
- var prevError;
1972
- var prevGroup;
1973
- var prevGroupCollapsed;
1974
- var prevGroupEnd;
1975
-
1976
- function disabledLog() {}
1977
-
1978
- disabledLog.__reactDisabledLog = true;
1979
- function disableLogs() {
1980
- {
1981
- if (disabledDepth === 0) {
1982
- /* eslint-disable react-internal/no-production-logging */
1983
- prevLog = console.log;
1984
- prevInfo = console.info;
1985
- prevWarn = console.warn;
1986
- prevError = console.error;
1987
- prevGroup = console.group;
1988
- prevGroupCollapsed = console.groupCollapsed;
1989
- prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099
1990
-
1991
- var props = {
1992
- configurable: true,
1993
- enumerable: true,
1994
- value: disabledLog,
1995
- writable: true
1996
- }; // $FlowFixMe Flow thinks console is immutable.
1997
-
1998
- Object.defineProperties(console, {
1999
- info: props,
2000
- log: props,
2001
- warn: props,
2002
- error: props,
2003
- group: props,
2004
- groupCollapsed: props,
2005
- groupEnd: props
2006
- });
2007
- /* eslint-enable react-internal/no-production-logging */
2008
- }
2009
-
2010
- disabledDepth++;
2011
- }
2012
- }
2013
- function reenableLogs() {
2014
- {
2015
- disabledDepth--;
2016
-
2017
- if (disabledDepth === 0) {
2018
- /* eslint-disable react-internal/no-production-logging */
2019
- var props = {
2020
- configurable: true,
2021
- enumerable: true,
2022
- writable: true
2023
- }; // $FlowFixMe Flow thinks console is immutable.
2024
-
2025
- Object.defineProperties(console, {
2026
- log: assign({}, props, {
2027
- value: prevLog
2028
- }),
2029
- info: assign({}, props, {
2030
- value: prevInfo
2031
- }),
2032
- warn: assign({}, props, {
2033
- value: prevWarn
2034
- }),
2035
- error: assign({}, props, {
2036
- value: prevError
2037
- }),
2038
- group: assign({}, props, {
2039
- value: prevGroup
2040
- }),
2041
- groupCollapsed: assign({}, props, {
2042
- value: prevGroupCollapsed
2043
- }),
2044
- groupEnd: assign({}, props, {
2045
- value: prevGroupEnd
2046
- })
2047
- });
2048
- /* eslint-enable react-internal/no-production-logging */
2049
- }
2050
-
2051
- if (disabledDepth < 0) {
2052
- error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
2053
- }
2054
- }
2055
- }
2056
-
2057
- var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
2058
- var prefix;
2059
- function describeBuiltInComponentFrame(name, source, ownerFn) {
2060
- {
2061
- if (prefix === undefined) {
2062
- // Extract the VM specific prefix used by each line.
2063
- try {
2064
- throw Error();
2065
- } catch (x) {
2066
- var match = x.stack.trim().match(/\n( *(at )?)/);
2067
- prefix = match && match[1] || '';
2068
- }
2069
- } // We use the prefix to ensure our stacks line up with native stack frames.
2070
-
2071
-
2072
- return '\n' + prefix + name;
2073
- }
2074
- }
2075
- var reentry = false;
2076
- var componentFrameCache;
2077
-
2078
- {
2079
- var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
2080
- componentFrameCache = new PossiblyWeakMap();
2081
- }
2082
-
2083
- function describeNativeComponentFrame(fn, construct) {
2084
- // If something asked for a stack inside a fake render, it should get ignored.
2085
- if ( !fn || reentry) {
2086
- return '';
2087
- }
2088
-
2089
- {
2090
- var frame = componentFrameCache.get(fn);
2091
-
2092
- if (frame !== undefined) {
2093
- return frame;
2094
- }
2095
- }
2096
-
2097
- var control;
2098
- reentry = true;
2099
- var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.
2100
-
2101
- Error.prepareStackTrace = undefined;
2102
- var previousDispatcher;
2103
-
2104
- {
2105
- previousDispatcher = ReactCurrentDispatcher$1.current; // Set the dispatcher in DEV because this might be call in the render function
2106
- // for warnings.
2107
-
2108
- ReactCurrentDispatcher$1.current = null;
2109
- disableLogs();
2110
- }
2111
-
2112
- try {
2113
- // This should throw.
2114
- if (construct) {
2115
- // Something should be setting the props in the constructor.
2116
- var Fake = function () {
2117
- throw Error();
2118
- }; // $FlowFixMe
2119
-
2120
-
2121
- Object.defineProperty(Fake.prototype, 'props', {
2122
- set: function () {
2123
- // We use a throwing setter instead of frozen or non-writable props
2124
- // because that won't throw in a non-strict mode function.
2125
- throw Error();
2126
- }
2127
- });
2128
-
2129
- if (typeof Reflect === 'object' && Reflect.construct) {
2130
- // We construct a different control for this case to include any extra
2131
- // frames added by the construct call.
2132
- try {
2133
- Reflect.construct(Fake, []);
2134
- } catch (x) {
2135
- control = x;
2136
- }
2137
-
2138
- Reflect.construct(fn, [], Fake);
2139
- } else {
2140
- try {
2141
- Fake.call();
2142
- } catch (x) {
2143
- control = x;
2144
- }
2145
-
2146
- fn.call(Fake.prototype);
2147
- }
2148
- } else {
2149
- try {
2150
- throw Error();
2151
- } catch (x) {
2152
- control = x;
2153
- }
2154
-
2155
- fn();
2156
- }
2157
- } catch (sample) {
2158
- // This is inlined manually because closure doesn't do it for us.
2159
- if (sample && control && typeof sample.stack === 'string') {
2160
- // This extracts the first frame from the sample that isn't also in the control.
2161
- // Skipping one frame that we assume is the frame that calls the two.
2162
- var sampleLines = sample.stack.split('\n');
2163
- var controlLines = control.stack.split('\n');
2164
- var s = sampleLines.length - 1;
2165
- var c = controlLines.length - 1;
2166
-
2167
- while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
2168
- // We expect at least one stack frame to be shared.
2169
- // Typically this will be the root most one. However, stack frames may be
2170
- // cut off due to maximum stack limits. In this case, one maybe cut off
2171
- // earlier than the other. We assume that the sample is longer or the same
2172
- // and there for cut off earlier. So we should find the root most frame in
2173
- // the sample somewhere in the control.
2174
- c--;
2175
- }
2176
-
2177
- for (; s >= 1 && c >= 0; s--, c--) {
2178
- // Next we find the first one that isn't the same which should be the
2179
- // frame that called our sample function and the control.
2180
- if (sampleLines[s] !== controlLines[c]) {
2181
- // In V8, the first line is describing the message but other VMs don't.
2182
- // If we're about to return the first line, and the control is also on the same
2183
- // line, that's a pretty good indicator that our sample threw at same line as
2184
- // the control. I.e. before we entered the sample frame. So we ignore this result.
2185
- // This can happen if you passed a class to function component, or non-function.
2186
- if (s !== 1 || c !== 1) {
2187
- do {
2188
- s--;
2189
- c--; // We may still have similar intermediate frames from the construct call.
2190
- // The next one that isn't the same should be our match though.
2191
-
2192
- if (c < 0 || sampleLines[s] !== controlLines[c]) {
2193
- // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
2194
- var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>"
2195
- // but we have a user-provided "displayName"
2196
- // splice it in to make the stack more readable.
2197
-
2198
-
2199
- if (fn.displayName && _frame.includes('<anonymous>')) {
2200
- _frame = _frame.replace('<anonymous>', fn.displayName);
2201
- }
2202
-
2203
- {
2204
- if (typeof fn === 'function') {
2205
- componentFrameCache.set(fn, _frame);
2206
- }
2207
- } // Return the line we found.
2208
-
2209
-
2210
- return _frame;
2211
- }
2212
- } while (s >= 1 && c >= 0);
2213
- }
2214
-
2215
- break;
2216
- }
2217
- }
2218
- }
2219
- } finally {
2220
- reentry = false;
2221
-
2222
- {
2223
- ReactCurrentDispatcher$1.current = previousDispatcher;
2224
- reenableLogs();
2225
- }
2226
-
2227
- Error.prepareStackTrace = previousPrepareStackTrace;
2228
- } // Fallback to just using the name if we couldn't make it throw.
2229
-
2230
-
2231
- var name = fn ? fn.displayName || fn.name : '';
2232
- var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';
2233
-
2234
- {
2235
- if (typeof fn === 'function') {
2236
- componentFrameCache.set(fn, syntheticFrame);
2237
- }
2238
- }
2239
-
2240
- return syntheticFrame;
2241
- }
2242
- function describeFunctionComponentFrame(fn, source, ownerFn) {
2243
- {
2244
- return describeNativeComponentFrame(fn, false);
2245
- }
2246
- }
2247
-
2248
- function shouldConstruct(Component) {
2249
- var prototype = Component.prototype;
2250
- return !!(prototype && prototype.isReactComponent);
2251
- }
2252
-
2253
- function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
2254
-
2255
- if (type == null) {
2256
- return '';
2257
- }
2258
-
2259
- if (typeof type === 'function') {
2260
- {
2261
- return describeNativeComponentFrame(type, shouldConstruct(type));
2262
- }
2263
- }
2264
-
2265
- if (typeof type === 'string') {
2266
- return describeBuiltInComponentFrame(type);
2267
- }
2268
-
2269
- switch (type) {
2270
- case REACT_SUSPENSE_TYPE:
2271
- return describeBuiltInComponentFrame('Suspense');
2272
-
2273
- case REACT_SUSPENSE_LIST_TYPE:
2274
- return describeBuiltInComponentFrame('SuspenseList');
2275
- }
2276
-
2277
- if (typeof type === 'object') {
2278
- switch (type.$$typeof) {
2279
- case REACT_FORWARD_REF_TYPE:
2280
- return describeFunctionComponentFrame(type.render);
2281
-
2282
- case REACT_MEMO_TYPE:
2283
- // Memo may contain any component type so we recursively resolve it.
2284
- return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
2285
-
2286
- case REACT_LAZY_TYPE:
2287
- {
2288
- var lazyComponent = type;
2289
- var payload = lazyComponent._payload;
2290
- var init = lazyComponent._init;
2291
-
2292
- try {
2293
- // Lazy may contain any component type so we recursively resolve it.
2294
- return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
2295
- } catch (x) {}
2296
- }
2297
- }
2298
- }
2299
-
2300
- return '';
2301
- }
2302
-
2303
- var loggedTypeFailures = {};
2304
- var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
2305
-
2306
- function setCurrentlyValidatingElement(element) {
2307
- {
2308
- if (element) {
2309
- var owner = element._owner;
2310
- var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
2311
- ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
2312
- } else {
2313
- ReactDebugCurrentFrame$1.setExtraStackFrame(null);
2314
- }
2315
- }
2316
- }
2317
-
2318
- function checkPropTypes(typeSpecs, values, location, componentName, element) {
2319
- {
2320
- // $FlowFixMe This is okay but Flow doesn't know it.
2321
- var has = Function.call.bind(hasOwnProperty);
2322
-
2323
- for (var typeSpecName in typeSpecs) {
2324
- if (has(typeSpecs, typeSpecName)) {
2325
- var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
2326
- // fail the render phase where it didn't fail before. So we log it.
2327
- // After these have been cleaned up, we'll let them throw.
2328
-
2329
- try {
2330
- // This is intentionally an invariant that gets caught. It's the same
2331
- // behavior as without this statement except with a better message.
2332
- if (typeof typeSpecs[typeSpecName] !== 'function') {
2333
- // eslint-disable-next-line react-internal/prod-error-codes
2334
- var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
2335
- err.name = 'Invariant Violation';
2336
- throw err;
2337
- }
2338
-
2339
- error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
2340
- } catch (ex) {
2341
- error$1 = ex;
2342
- }
2343
-
2344
- if (error$1 && !(error$1 instanceof Error)) {
2345
- setCurrentlyValidatingElement(element);
2346
-
2347
- error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);
2348
-
2349
- setCurrentlyValidatingElement(null);
2350
- }
2351
-
2352
- if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
2353
- // Only monitor this failure once because there tends to be a lot of the
2354
- // same error.
2355
- loggedTypeFailures[error$1.message] = true;
2356
- setCurrentlyValidatingElement(element);
2357
-
2358
- error('Failed %s type: %s', location, error$1.message);
2359
-
2360
- setCurrentlyValidatingElement(null);
2361
- }
2362
- }
2363
- }
2364
- }
2365
- }
2366
-
2367
- function setCurrentlyValidatingElement$1(element) {
2368
- {
2369
- if (element) {
2370
- var owner = element._owner;
2371
- var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
2372
- setExtraStackFrame(stack);
2373
- } else {
2374
- setExtraStackFrame(null);
2375
- }
2376
- }
2377
- }
2378
-
2379
- var propTypesMisspellWarningShown;
2380
-
2381
- {
2382
- propTypesMisspellWarningShown = false;
2383
- }
2384
-
2385
- function getDeclarationErrorAddendum() {
2386
- if (ReactCurrentOwner.current) {
2387
- var name = getComponentNameFromType(ReactCurrentOwner.current.type);
2388
-
2389
- if (name) {
2390
- return '\n\nCheck the render method of `' + name + '`.';
2391
- }
2392
- }
2393
-
2394
- return '';
2395
- }
2396
-
2397
- function getSourceInfoErrorAddendum(source) {
2398
- if (source !== undefined) {
2399
- var fileName = source.fileName.replace(/^.*[\\\/]/, '');
2400
- var lineNumber = source.lineNumber;
2401
- return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.';
2402
- }
2403
-
2404
- return '';
2405
- }
2406
-
2407
- function getSourceInfoErrorAddendumForProps(elementProps) {
2408
- if (elementProps !== null && elementProps !== undefined) {
2409
- return getSourceInfoErrorAddendum(elementProps.__source);
2410
- }
2411
-
2412
- return '';
2413
- }
2414
- /**
2415
- * Warn if there's no key explicitly set on dynamic arrays of children or
2416
- * object keys are not valid. This allows us to keep track of children between
2417
- * updates.
2418
- */
2419
-
2420
-
2421
- var ownerHasKeyUseWarning = {};
2422
-
2423
- function getCurrentComponentErrorInfo(parentType) {
2424
- var info = getDeclarationErrorAddendum();
2425
-
2426
- if (!info) {
2427
- var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
2428
-
2429
- if (parentName) {
2430
- info = "\n\nCheck the top-level render call using <" + parentName + ">.";
2431
- }
2432
- }
2433
-
2434
- return info;
2435
- }
2436
- /**
2437
- * Warn if the element doesn't have an explicit key assigned to it.
2438
- * This element is in an array. The array could grow and shrink or be
2439
- * reordered. All children that haven't already been validated are required to
2440
- * have a "key" property assigned to it. Error statuses are cached so a warning
2441
- * will only be shown once.
2442
- *
2443
- * @internal
2444
- * @param {ReactElement} element Element that requires a key.
2445
- * @param {*} parentType element's parent's type.
2446
- */
2447
-
2448
-
2449
- function validateExplicitKey(element, parentType) {
2450
- if (!element._store || element._store.validated || element.key != null) {
2451
- return;
2452
- }
2453
-
2454
- element._store.validated = true;
2455
- var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
2456
-
2457
- if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
2458
- return;
2459
- }
2460
-
2461
- ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a
2462
- // property, it may be the creator of the child that's responsible for
2463
- // assigning it a key.
2464
-
2465
- var childOwner = '';
2466
-
2467
- if (element && element._owner && element._owner !== ReactCurrentOwner.current) {
2468
- // Give the component that originally created this child.
2469
- childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + ".";
2470
- }
2471
-
2472
- {
2473
- setCurrentlyValidatingElement$1(element);
2474
-
2475
- error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);
2476
-
2477
- setCurrentlyValidatingElement$1(null);
2478
- }
2479
- }
2480
- /**
2481
- * Ensure that every element either is passed in a static location, in an
2482
- * array with an explicit keys property defined, or in an object literal
2483
- * with valid key property.
2484
- *
2485
- * @internal
2486
- * @param {ReactNode} node Statically passed child of any type.
2487
- * @param {*} parentType node's parent's type.
2488
- */
2489
-
2490
-
2491
- function validateChildKeys(node, parentType) {
2492
- if (typeof node !== 'object') {
2493
- return;
2494
- }
2495
-
2496
- if (isArray(node)) {
2497
- for (var i = 0; i < node.length; i++) {
2498
- var child = node[i];
2499
-
2500
- if (isValidElement(child)) {
2501
- validateExplicitKey(child, parentType);
2502
- }
2503
- }
2504
- } else if (isValidElement(node)) {
2505
- // This element was passed in a valid location.
2506
- if (node._store) {
2507
- node._store.validated = true;
2508
- }
2509
- } else if (node) {
2510
- var iteratorFn = getIteratorFn(node);
2511
-
2512
- if (typeof iteratorFn === 'function') {
2513
- // Entry iterators used to provide implicit keys,
2514
- // but now we print a separate warning for them later.
2515
- if (iteratorFn !== node.entries) {
2516
- var iterator = iteratorFn.call(node);
2517
- var step;
2518
-
2519
- while (!(step = iterator.next()).done) {
2520
- if (isValidElement(step.value)) {
2521
- validateExplicitKey(step.value, parentType);
2522
- }
2523
- }
2524
- }
2525
- }
2526
- }
2527
- }
2528
- /**
2529
- * Given an element, validate that its props follow the propTypes definition,
2530
- * provided by the type.
2531
- *
2532
- * @param {ReactElement} element
2533
- */
2534
-
2535
-
2536
- function validatePropTypes(element) {
2537
- {
2538
- var type = element.type;
2539
-
2540
- if (type === null || type === undefined || typeof type === 'string') {
2541
- return;
2542
- }
2543
-
2544
- var propTypes;
2545
-
2546
- if (typeof type === 'function') {
2547
- propTypes = type.propTypes;
2548
- } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
2549
- // Inner props are checked in the reconciler.
2550
- type.$$typeof === REACT_MEMO_TYPE)) {
2551
- propTypes = type.propTypes;
2552
- } else {
2553
- return;
2554
- }
2555
-
2556
- if (propTypes) {
2557
- // Intentionally inside to avoid triggering lazy initializers:
2558
- var name = getComponentNameFromType(type);
2559
- checkPropTypes(propTypes, element.props, 'prop', name, element);
2560
- } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
2561
- propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:
2562
-
2563
- var _name = getComponentNameFromType(type);
2564
-
2565
- error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');
2566
- }
2567
-
2568
- if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {
2569
- error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');
2570
- }
2571
- }
2572
- }
2573
- /**
2574
- * Given a fragment, validate that it can only be provided with fragment props
2575
- * @param {ReactElement} fragment
2576
- */
2577
-
2578
-
2579
- function validateFragmentProps(fragment) {
2580
- {
2581
- var keys = Object.keys(fragment.props);
2582
-
2583
- for (var i = 0; i < keys.length; i++) {
2584
- var key = keys[i];
2585
-
2586
- if (key !== 'children' && key !== 'key') {
2587
- setCurrentlyValidatingElement$1(fragment);
2588
-
2589
- error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);
2590
-
2591
- setCurrentlyValidatingElement$1(null);
2592
- break;
2593
- }
2594
- }
2595
-
2596
- if (fragment.ref !== null) {
2597
- setCurrentlyValidatingElement$1(fragment);
2598
-
2599
- error('Invalid attribute `ref` supplied to `React.Fragment`.');
2600
-
2601
- setCurrentlyValidatingElement$1(null);
2602
- }
2603
- }
2604
- }
2605
- function createElementWithValidation(type, props, children) {
2606
- var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to
2607
- // succeed and there will likely be errors in render.
2608
-
2609
- if (!validType) {
2610
- var info = '';
2611
-
2612
- if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
2613
- info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports.";
2614
- }
2615
-
2616
- var sourceInfo = getSourceInfoErrorAddendumForProps(props);
2617
-
2618
- if (sourceInfo) {
2619
- info += sourceInfo;
2620
- } else {
2621
- info += getDeclarationErrorAddendum();
2622
- }
2623
-
2624
- var typeString;
2625
-
2626
- if (type === null) {
2627
- typeString = 'null';
2628
- } else if (isArray(type)) {
2629
- typeString = 'array';
2630
- } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
2631
- typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />";
2632
- info = ' Did you accidentally export a JSX literal instead of a component?';
2633
- } else {
2634
- typeString = typeof type;
2635
- }
2636
-
2637
- {
2638
- error('React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);
2639
- }
2640
- }
2641
-
2642
- var element = createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used.
2643
- // TODO: Drop this when these are no longer allowed as the type argument.
2644
-
2645
- if (element == null) {
2646
- return element;
2647
- } // Skip key warning if the type isn't valid since our key validation logic
2648
- // doesn't expect a non-string/function type and can throw confusing errors.
2649
- // We don't want exception behavior to differ between dev and prod.
2650
- // (Rendering will throw with a helpful message and as soon as the type is
2651
- // fixed, the key warnings will appear.)
2652
-
2653
-
2654
- if (validType) {
2655
- for (var i = 2; i < arguments.length; i++) {
2656
- validateChildKeys(arguments[i], type);
2657
- }
2658
- }
2659
-
2660
- if (type === REACT_FRAGMENT_TYPE) {
2661
- validateFragmentProps(element);
2662
- } else {
2663
- validatePropTypes(element);
2664
- }
2665
-
2666
- return element;
2667
- }
2668
- var didWarnAboutDeprecatedCreateFactory = false;
2669
- function createFactoryWithValidation(type) {
2670
- var validatedFactory = createElementWithValidation.bind(null, type);
2671
- validatedFactory.type = type;
2672
-
2673
- {
2674
- if (!didWarnAboutDeprecatedCreateFactory) {
2675
- didWarnAboutDeprecatedCreateFactory = true;
2676
-
2677
- warn('React.createFactory() is deprecated and will be removed in ' + 'a future major release. Consider using JSX ' + 'or use React.createElement() directly instead.');
2678
- } // Legacy hook: remove it
2679
-
2680
-
2681
- Object.defineProperty(validatedFactory, 'type', {
2682
- enumerable: false,
2683
- get: function () {
2684
- warn('Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.');
2685
-
2686
- Object.defineProperty(this, 'type', {
2687
- value: type
2688
- });
2689
- return type;
2690
- }
2691
- });
2692
- }
2693
-
2694
- return validatedFactory;
2695
- }
2696
- function cloneElementWithValidation(element, props, children) {
2697
- var newElement = cloneElement.apply(this, arguments);
2698
-
2699
- for (var i = 2; i < arguments.length; i++) {
2700
- validateChildKeys(arguments[i], newElement.type);
2701
- }
2702
-
2703
- validatePropTypes(newElement);
2704
- return newElement;
2705
- }
2706
-
2707
- function startTransition(scope, options) {
2708
- var prevTransition = ReactCurrentBatchConfig.transition;
2709
- ReactCurrentBatchConfig.transition = {};
2710
- var currentTransition = ReactCurrentBatchConfig.transition;
2711
-
2712
- {
2713
- ReactCurrentBatchConfig.transition._updatedFibers = new Set();
2714
- }
2715
-
2716
- try {
2717
- scope();
2718
- } finally {
2719
- ReactCurrentBatchConfig.transition = prevTransition;
2720
-
2721
- {
2722
- if (prevTransition === null && currentTransition._updatedFibers) {
2723
- var updatedFibersCount = currentTransition._updatedFibers.size;
2724
-
2725
- if (updatedFibersCount > 10) {
2726
- warn('Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.');
2727
- }
2728
-
2729
- currentTransition._updatedFibers.clear();
2730
- }
2731
- }
2732
- }
2733
- }
2734
-
2735
- var didWarnAboutMessageChannel = false;
2736
- var enqueueTaskImpl = null;
2737
- function enqueueTask(task) {
2738
- if (enqueueTaskImpl === null) {
2739
- try {
2740
- // read require off the module object to get around the bundlers.
2741
- // we don't want them to detect a require and bundle a Node polyfill.
2742
- var requireString = ('require' + Math.random()).slice(0, 7);
2743
- var nodeRequire = module && module[requireString]; // assuming we're in node, let's try to get node's
2744
- // version of setImmediate, bypassing fake timers if any.
2745
-
2746
- enqueueTaskImpl = nodeRequire.call(module, 'timers').setImmediate;
2747
- } catch (_err) {
2748
- // we're in a browser
2749
- // we can't use regular timers because they may still be faked
2750
- // so we try MessageChannel+postMessage instead
2751
- enqueueTaskImpl = function (callback) {
2752
- {
2753
- if (didWarnAboutMessageChannel === false) {
2754
- didWarnAboutMessageChannel = true;
2755
-
2756
- if (typeof MessageChannel === 'undefined') {
2757
- error('This browser does not have a MessageChannel implementation, ' + 'so enqueuing tasks via await act(async () => ...) will fail. ' + 'Please file an issue at https://github.com/facebook/react/issues ' + 'if you encounter this warning.');
2758
- }
2759
- }
2760
- }
2761
-
2762
- var channel = new MessageChannel();
2763
- channel.port1.onmessage = callback;
2764
- channel.port2.postMessage(undefined);
2765
- };
2766
- }
2767
- }
2768
-
2769
- return enqueueTaskImpl(task);
2770
- }
2771
-
2772
- var actScopeDepth = 0;
2773
- var didWarnNoAwaitAct = false;
2774
- function act(callback) {
2775
- {
2776
- // `act` calls can be nested, so we track the depth. This represents the
2777
- // number of `act` scopes on the stack.
2778
- var prevActScopeDepth = actScopeDepth;
2779
- actScopeDepth++;
2780
-
2781
- if (ReactCurrentActQueue.current === null) {
2782
- // This is the outermost `act` scope. Initialize the queue. The reconciler
2783
- // will detect the queue and use it instead of Scheduler.
2784
- ReactCurrentActQueue.current = [];
2785
- }
2786
-
2787
- var prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy;
2788
- var result;
2789
-
2790
- try {
2791
- // Used to reproduce behavior of `batchedUpdates` in legacy mode. Only
2792
- // set to `true` while the given callback is executed, not for updates
2793
- // triggered during an async event, because this is how the legacy
2794
- // implementation of `act` behaved.
2795
- ReactCurrentActQueue.isBatchingLegacy = true;
2796
- result = callback(); // Replicate behavior of original `act` implementation in legacy mode,
2797
- // which flushed updates immediately after the scope function exits, even
2798
- // if it's an async function.
2799
-
2800
- if (!prevIsBatchingLegacy && ReactCurrentActQueue.didScheduleLegacyUpdate) {
2801
- var queue = ReactCurrentActQueue.current;
2802
-
2803
- if (queue !== null) {
2804
- ReactCurrentActQueue.didScheduleLegacyUpdate = false;
2805
- flushActQueue(queue);
2806
- }
2807
- }
2808
- } catch (error) {
2809
- popActScope(prevActScopeDepth);
2810
- throw error;
2811
- } finally {
2812
- ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy;
2813
- }
2814
-
2815
- if (result !== null && typeof result === 'object' && typeof result.then === 'function') {
2816
- var thenableResult = result; // The callback is an async function (i.e. returned a promise). Wait
2817
- // for it to resolve before exiting the current scope.
2818
-
2819
- var wasAwaited = false;
2820
- var thenable = {
2821
- then: function (resolve, reject) {
2822
- wasAwaited = true;
2823
- thenableResult.then(function (returnValue) {
2824
- popActScope(prevActScopeDepth);
2825
-
2826
- if (actScopeDepth === 0) {
2827
- // We've exited the outermost act scope. Recursively flush the
2828
- // queue until there's no remaining work.
2829
- recursivelyFlushAsyncActWork(returnValue, resolve, reject);
2830
- } else {
2831
- resolve(returnValue);
2832
- }
2833
- }, function (error) {
2834
- // The callback threw an error.
2835
- popActScope(prevActScopeDepth);
2836
- reject(error);
2837
- });
2838
- }
2839
- };
2840
-
2841
- {
2842
- if (!didWarnNoAwaitAct && typeof Promise !== 'undefined') {
2843
- // eslint-disable-next-line no-undef
2844
- Promise.resolve().then(function () {}).then(function () {
2845
- if (!wasAwaited) {
2846
- didWarnNoAwaitAct = true;
2847
-
2848
- error('You called act(async () => ...) without await. ' + 'This could lead to unexpected testing behaviour, ' + 'interleaving multiple act calls and mixing their ' + 'scopes. ' + 'You should - await act(async () => ...);');
2849
- }
2850
- });
2851
- }
2852
- }
2853
-
2854
- return thenable;
2855
- } else {
2856
- var returnValue = result; // The callback is not an async function. Exit the current scope
2857
- // immediately, without awaiting.
2858
-
2859
- popActScope(prevActScopeDepth);
2860
-
2861
- if (actScopeDepth === 0) {
2862
- // Exiting the outermost act scope. Flush the queue.
2863
- var _queue = ReactCurrentActQueue.current;
2864
-
2865
- if (_queue !== null) {
2866
- flushActQueue(_queue);
2867
- ReactCurrentActQueue.current = null;
2868
- } // Return a thenable. If the user awaits it, we'll flush again in
2869
- // case additional work was scheduled by a microtask.
2870
-
2871
-
2872
- var _thenable = {
2873
- then: function (resolve, reject) {
2874
- // Confirm we haven't re-entered another `act` scope, in case
2875
- // the user does something weird like await the thenable
2876
- // multiple times.
2877
- if (ReactCurrentActQueue.current === null) {
2878
- // Recursively flush the queue until there's no remaining work.
2879
- ReactCurrentActQueue.current = [];
2880
- recursivelyFlushAsyncActWork(returnValue, resolve, reject);
2881
- } else {
2882
- resolve(returnValue);
2883
- }
2884
- }
2885
- };
2886
- return _thenable;
2887
- } else {
2888
- // Since we're inside a nested `act` scope, the returned thenable
2889
- // immediately resolves. The outer scope will flush the queue.
2890
- var _thenable2 = {
2891
- then: function (resolve, reject) {
2892
- resolve(returnValue);
2893
- }
2894
- };
2895
- return _thenable2;
2896
- }
2897
- }
2898
- }
2899
- }
2900
-
2901
- function popActScope(prevActScopeDepth) {
2902
- {
2903
- if (prevActScopeDepth !== actScopeDepth - 1) {
2904
- error('You seem to have overlapping act() calls, this is not supported. ' + 'Be sure to await previous act() calls before making a new one. ');
2905
- }
2906
-
2907
- actScopeDepth = prevActScopeDepth;
2908
- }
2909
- }
2910
-
2911
- function recursivelyFlushAsyncActWork(returnValue, resolve, reject) {
2912
- {
2913
- var queue = ReactCurrentActQueue.current;
2914
-
2915
- if (queue !== null) {
2916
- try {
2917
- flushActQueue(queue);
2918
- enqueueTask(function () {
2919
- if (queue.length === 0) {
2920
- // No additional work was scheduled. Finish.
2921
- ReactCurrentActQueue.current = null;
2922
- resolve(returnValue);
2923
- } else {
2924
- // Keep flushing work until there's none left.
2925
- recursivelyFlushAsyncActWork(returnValue, resolve, reject);
2926
- }
2927
- });
2928
- } catch (error) {
2929
- reject(error);
2930
- }
2931
- } else {
2932
- resolve(returnValue);
2933
- }
2934
- }
2935
- }
2936
-
2937
- var isFlushing = false;
2938
-
2939
- function flushActQueue(queue) {
2940
- {
2941
- if (!isFlushing) {
2942
- // Prevent re-entrance.
2943
- isFlushing = true;
2944
- var i = 0;
2945
-
2946
- try {
2947
- for (; i < queue.length; i++) {
2948
- var callback = queue[i];
2949
-
2950
- do {
2951
- callback = callback(true);
2952
- } while (callback !== null);
2953
- }
2954
-
2955
- queue.length = 0;
2956
- } catch (error) {
2957
- // If something throws, leave the remaining callbacks on the queue.
2958
- queue = queue.slice(i + 1);
2959
- throw error;
2960
- } finally {
2961
- isFlushing = false;
2962
- }
2963
- }
2964
- }
2965
- }
2966
-
2967
- var createElement$1 = createElementWithValidation ;
2968
- var cloneElement$1 = cloneElementWithValidation ;
2969
- var createFactory = createFactoryWithValidation ;
2970
- var Children = {
2971
- map: mapChildren,
2972
- forEach: forEachChildren,
2973
- count: countChildren,
2974
- toArray: toArray,
2975
- only: onlyChild
2976
- };
2977
-
2978
- exports.Children = Children;
2979
- exports.Component = Component;
2980
- exports.Fragment = REACT_FRAGMENT_TYPE;
2981
- exports.Profiler = REACT_PROFILER_TYPE;
2982
- exports.PureComponent = PureComponent;
2983
- exports.StrictMode = REACT_STRICT_MODE_TYPE;
2984
- exports.Suspense = REACT_SUSPENSE_TYPE;
2985
- exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals;
2986
- exports.act = act;
2987
- exports.cloneElement = cloneElement$1;
2988
- exports.createContext = createContext;
2989
- exports.createElement = createElement$1;
2990
- exports.createFactory = createFactory;
2991
- exports.createRef = createRef;
2992
- exports.forwardRef = forwardRef;
2993
- exports.isValidElement = isValidElement;
2994
- exports.lazy = lazy;
2995
- exports.memo = memo;
2996
- exports.startTransition = startTransition;
2997
- exports.unstable_act = act;
2998
- exports.useCallback = useCallback;
2999
- exports.useContext = useContext;
3000
- exports.useDebugValue = useDebugValue;
3001
- exports.useDeferredValue = useDeferredValue;
3002
- exports.useEffect = useEffect;
3003
- exports.useId = useId;
3004
- exports.useImperativeHandle = useImperativeHandle;
3005
- exports.useInsertionEffect = useInsertionEffect;
3006
- exports.useLayoutEffect = useLayoutEffect;
3007
- exports.useMemo = useMemo;
3008
- exports.useReducer = useReducer;
3009
- exports.useRef = useRef;
3010
- exports.useState = useState;
3011
- exports.useSyncExternalStore = useSyncExternalStore;
3012
- exports.useTransition = useTransition;
3013
- exports.version = ReactVersion;
3014
- /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
3015
- if (
3016
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
3017
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===
3018
- 'function'
3019
- ) {
3020
- __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
3021
- }
3022
-
3023
- })();
3024
- }
3025
- } (react_development, react_development.exports));
3026
- return react_development.exports;
3027
- }
3028
-
3029
- var hasRequiredReact;
3030
-
3031
- function requireReact () {
3032
- if (hasRequiredReact) return react.exports;
3033
- hasRequiredReact = 1;
3034
-
3035
- if (process.env.NODE_ENV === 'production') {
3036
- react.exports = requireReact_production_min();
3037
- } else {
3038
- react.exports = requireReact_development();
3039
- }
3040
- return react.exports;
3041
- }
3042
-
3043
- var reactExports = requireReact();
3044
-
3045
- /**
3046
- * React Hook: handles <input type="file" onChange> with validation + scanning.
3047
- */
3048
- function useFileScanner() {
3049
- const [results, setResults] = reactExports.useState([]);
3050
- const [errors, setErrors] = reactExports.useState([]);
3051
- const onChange = reactExports.useCallback(async (e) => {
3052
- const fileList = Array.from(e.target.files || []);
3053
- const good = [];
3054
- const bad = [];
3055
- for (const file of fileList) {
3056
- const { valid, error } = validateFile(file);
3057
- if (valid)
3058
- good.push(file);
3059
- else
3060
- bad.push({ file, error: error });
3061
- }
3062
- setErrors(bad);
3063
- if (good.length) {
3064
- const scanned = await scanFiles(good);
3065
- setResults(scanned.map((r, i) => ({ file: good[i], report: r })));
3066
- }
3067
- else {
3068
- setResults([]);
3069
- }
3070
- }, []);
3071
- return { results, errors, onChange };
3072
- }
3073
-
3074
- async function createRemoteEngine(opts) {
3075
- const { endpoint, headers = {}, rulesField = 'rules', fileField = 'file', mode = 'multipart', rulesAsBase64 = false, } = opts;
3076
- const engine = {
3077
- async compile(rulesSource) {
3078
- return {
3079
- async scan(data) {
3080
- const fetchFn = globalThis.fetch;
3081
- if (!fetchFn)
3082
- throw new Error('[remote-yara] fetch non disponibile in questo ambiente');
3083
- let res;
3084
- if (mode === 'multipart') {
3085
- const FormDataCtor = globalThis.FormData;
3086
- const BlobCtor = globalThis.Blob;
3087
- if (!FormDataCtor || !BlobCtor) {
3088
- throw new Error('[remote-yara] FormData/Blob non disponibili (usa json-base64 oppure esegui in browser)');
3089
- }
3090
- const form = new FormDataCtor();
3091
- form.set(rulesField, new BlobCtor([rulesSource], { type: 'text/plain' }), 'rules.yar');
3092
- form.set(fileField, new BlobCtor([data], { type: 'application/octet-stream' }), 'sample.bin');
3093
- res = await fetchFn(endpoint, { method: 'POST', body: form, headers });
3094
- }
3095
- else {
3096
- const b64 = base64FromBytes(data);
3097
- const payload = { [fileField]: b64 };
3098
- if (rulesAsBase64) {
3099
- payload['rulesB64'] = base64FromString(rulesSource);
3100
- }
3101
- else {
3102
- payload[rulesField] = rulesSource;
3103
- }
3104
- res = await fetchFn(endpoint, {
3105
- method: 'POST',
3106
- headers: { 'Content-Type': 'application/json', ...headers },
3107
- body: JSON.stringify(payload),
3108
- });
3109
- }
3110
- if (!res.ok) {
3111
- throw new Error(`[remote-yara] HTTP ${res.status} ${res.statusText}`);
3112
- }
3113
- const json = await res.json().catch(() => null);
3114
- const arr = Array.isArray(json) ? json : (json?.matches ?? []);
3115
- return (arr ?? []).map((m) => ({
3116
- rule: m.rule ?? m.ruleIdentifier ?? 'unknown',
3117
- tags: m.tags ?? [],
3118
- }));
3119
- },
3120
- };
3121
- },
3122
- };
3123
- return engine;
3124
- }
3125
- // Helpers
3126
- function base64FromBytes(bytes) {
3127
- // usa btoa se disponibile (browser); altrimenti fallback manuale
3128
- const btoaFn = globalThis.btoa;
3129
- let bin = '';
3130
- for (let i = 0; i < bytes.byteLength; i++)
3131
- bin += String.fromCharCode(bytes[i]);
3132
- return btoaFn ? btoaFn(bin) : Buffer.from(bin, 'binary').toString('base64');
3133
- }
3134
- function base64FromString(s) {
3135
- const btoaFn = globalThis.btoa;
3136
- return btoaFn ? btoaFn(s) : Buffer.from(s, 'utf8').toString('base64');
3137
- }
3138
-
3139
- // src/scan/remote.ts
3140
- /**
3141
- * Scansiona una lista di File nel browser usando il motore remoto via HTTP.
3142
- * Non richiede WASM né dipendenze native sul client.
3143
- */
3144
- async function scanFilesWithRemoteYara(files, rulesSource, remote) {
3145
- const engine = await createRemoteEngine(remote);
3146
- const compiled = await engine.compile(rulesSource);
3147
- const results = [];
3148
- for (const file of files) {
3149
- try {
3150
- const bytes = new Uint8Array(await file.arrayBuffer());
3151
- const matches = await compiled.scan(bytes);
3152
- results.push({ file, matches });
3153
- }
3154
- catch (err) {
3155
- console.warn('[remote-yara] scan error for', file.name, err);
3156
- results.push({ file, matches: [], error: String(err?.message ?? err) });
3157
- }
3158
- }
3159
- return results;
3160
- }
3161
-
3162
- function mapMatchesToVerdict(matches = []) {
3163
- if (!matches.length)
3164
- return 'clean';
3165
- const malHints = ['trojan', 'ransom', 'worm', 'spy', 'rootkit', 'keylog', 'botnet'];
3166
- const tagSet = new Set(matches.flatMap(m => (m.tags ?? []).map(t => t.toLowerCase())));
3167
- const nameHit = (r) => malHints.some(h => r.toLowerCase().includes(h));
3168
- const isMal = matches.some(m => nameHit(m.rule)) || tagSet.has('malware') || tagSet.has('critical');
3169
- return isMal ? 'malicious' : 'suspicious';
3170
- }
3171
-
3172
- function hasAsciiToken(buf, token) {
3173
- // Use latin1 so we can safely search binary
3174
- return buf.indexOf(token, 0, 'latin1') !== -1;
3175
- }
3176
- function startsWith(buf, bytes) {
3177
- if (buf.length < bytes.length)
3178
- return false;
3179
- for (let i = 0; i < bytes.length; i++)
3180
- if (buf[i] !== bytes[i])
3181
- return false;
3182
- return true;
3183
- }
3184
- function isPDF(buf) {
3185
- // %PDF-
3186
- return startsWith(buf, [0x25, 0x50, 0x44, 0x46, 0x2d]);
3187
- }
3188
- function isOleCfb(buf) {
3189
- // D0 CF 11 E0 A1 B1 1A E1
3190
- const sig = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];
3191
- return startsWith(buf, sig);
3192
- }
3193
- function isZipLike(buf) {
3194
- // PK\x03\x04
3195
- return startsWith(buf, [0x50, 0x4b, 0x03, 0x04]);
3196
- }
3197
- function isPeExecutable(buf) {
3198
- // "MZ"
3199
- return startsWith(buf, [0x4d, 0x5a]);
3200
- }
3201
- /** OOXML macro hint via filename token in ZIP container */
3202
- function hasOoxmlMacros(buf) {
3203
- if (!isZipLike(buf))
3204
- return false;
3205
- return hasAsciiToken(buf, 'vbaProject.bin');
3206
- }
3207
- /** PDF risky features (/JavaScript, /OpenAction, /AA, /Launch) */
3208
- function pdfRiskTokens(buf) {
3209
- const tokens = ['/JavaScript', '/OpenAction', '/AA', '/Launch'];
3210
- return tokens.filter(t => hasAsciiToken(buf, t));
3211
- }
3212
- const CommonHeuristicsScanner = {
3213
- async scan(input) {
3214
- const buf = Buffer.from(input);
3215
- const matches = [];
3216
- // Office macros (OLE / OOXML)
3217
- if (isOleCfb(buf)) {
3218
- matches.push({ rule: 'office_ole_container', severity: 'suspicious' });
3219
- }
3220
- if (hasOoxmlMacros(buf)) {
3221
- matches.push({ rule: 'office_ooxml_macros', severity: 'suspicious' });
3222
- }
3223
- // PDF risky tokens
3224
- if (isPDF(buf)) {
3225
- const toks = pdfRiskTokens(buf);
3226
- if (toks.length) {
3227
- matches.push({
3228
- rule: 'pdf_risky_actions',
3229
- severity: 'suspicious',
3230
- meta: { tokens: toks }
3231
- });
3232
- }
3233
- }
3234
- // Executable header
3235
- if (isPeExecutable(buf)) {
3236
- matches.push({ rule: 'pe_executable_signature', severity: 'suspicious' });
3237
- }
3238
- return matches;
3239
- }
3240
- };
3241
-
3242
- const MB = 1024 * 1024;
3243
- const DEFAULT_POLICY = {
3244
- includeExtensions: ['zip', 'png', 'jpg', 'jpeg', 'pdf'],
3245
- allowedMimeTypes: ['application/zip', 'image/png', 'image/jpeg', 'application/pdf', 'text/plain'],
3246
- maxFileSizeBytes: 20 * MB,
3247
- timeoutMs: 5000,
3248
- concurrency: 4,
3249
- failClosed: true
3250
- };
3251
- function definePolicy(input = {}) {
3252
- const p = { ...DEFAULT_POLICY, ...input };
3253
- if (!Array.isArray(p.includeExtensions))
3254
- throw new TypeError('includeExtensions must be string[]');
3255
- if (!Array.isArray(p.allowedMimeTypes))
3256
- throw new TypeError('allowedMimeTypes must be string[]');
3257
- if (!(Number.isFinite(p.maxFileSizeBytes) && p.maxFileSizeBytes > 0))
3258
- throw new TypeError('maxFileSizeBytes must be > 0');
3259
- if (!(Number.isFinite(p.timeoutMs) && p.timeoutMs > 0))
3260
- throw new TypeError('timeoutMs must be > 0');
3261
- if (!(Number.isInteger(p.concurrency) && p.concurrency > 0))
3262
- throw new TypeError('concurrency must be > 0');
3263
- return p;
3264
- }
3265
-
3266
- exports.CommonHeuristicsScanner = CommonHeuristicsScanner;
3267
- exports.DEFAULT_POLICY = DEFAULT_POLICY;
3268
- exports.composeScanners = composeScanners;
3269
- exports.createPresetScanner = createPresetScanner;
3270
- exports.createZipBombGuard = createZipBombGuard;
3271
- exports.definePolicy = definePolicy;
3272
- exports.mapMatchesToVerdict = mapMatchesToVerdict;
3273
- exports.scanBytes = scanBytes;
3274
- exports.scanFile = scanFile;
3275
- exports.scanFiles = scanFiles;
3276
- exports.scanFilesWithRemoteYara = scanFilesWithRemoteYara;
3277
- exports.useFileScanner = useFileScanner;
3278
- exports.validateFile = validateFile;
3279
- //# sourceMappingURL=pompelmi.cjs.js.map