-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcore.cjs
10042 lines (9974 loc) · 369 KB
/
core.cjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* @builder.io/qwik 1.13.0-dev+4571b3c
* Copyright Builder.io, Inc. All Rights Reserved.
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://github.com/QwikDev/qwik/blob/main/LICENSE
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@builder.io/qwik/build'), require('@builder.io/qwik/preloader')) :
typeof define === 'function' && define.amd ? define(['exports', '@builder.io/qwik/build', '@builder.io/qwik/preloader'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.qwikCore = {}, global.qwikBuild, global.qwikPreloader));
})(this, (function (exports, build, preloader) { 'use strict';
// <docs markdown="../readme.md#implicit$FirstArg">
// !!DO NOT EDIT THIS COMMENT DIRECTLY!!!
// (edit ../readme.md#implicit$FirstArg instead)
/**
* Create a `____$(...)` convenience method from `___(...)`.
*
* It is very common for functions to take a lazy-loadable resource as a first argument. For this
* reason, the Qwik Optimizer automatically extracts the first argument from any function which ends
* in `$`.
*
* This means that `foo$(arg0)` and `foo($(arg0))` are equivalent with respect to Qwik Optimizer.
* The former is just a shorthand for the latter.
*
* For example, these function calls are equivalent:
*
* - `component$(() => {...})` is same as `component($(() => {...}))`
*
* ```tsx
* export function myApi(callback: QRL<() => void>): void {
* // ...
* }
*
* export const myApi$ = implicit$FirstArg(myApi);
* // type of myApi$: (callback: () => void): void
*
* // can be used as:
* myApi$(() => console.log('callback'));
*
* // will be transpiled to:
* // FILE: <current file>
* myApi(qrl('./chunk-abc.js', 'callback'));
*
* // FILE: chunk-abc.js
* export const callback = () => console.log('callback');
* ```
*
* @param fn - A function that should have its first argument automatically `$`.
* @public
*/
// </docs>
const implicit$FirstArg = (fn) => {
return function (first, ...rest) {
return fn.call(null, $(first), ...rest);
};
};
const qDev = globalThis.qDev !== false;
const qInspector = globalThis.qInspector === true;
const qSerialize = globalThis.qSerialize !== false;
const qDynamicPlatform = globalThis.qDynamicPlatform !== false;
const qTest = globalThis.qTest === true;
const qRuntimeQrl = globalThis.qRuntimeQrl === true;
const seal = (obj) => {
if (qDev) {
Object.seal(obj);
}
};
const isNode$1 = (value) => {
return value && typeof value.nodeType === 'number';
};
const isDocument = (value) => {
return value.nodeType === 9;
};
const isElement$1 = (value) => {
return value.nodeType === 1;
};
const isQwikElement = (value) => {
const nodeType = value.nodeType;
return nodeType === 1 || nodeType === 111;
};
const isNodeElement = (value) => {
const nodeType = value.nodeType;
return nodeType === 1 || nodeType === 111 || nodeType === 3;
};
const isVirtualElement = (value) => {
return value.nodeType === 111;
};
const isText = (value) => {
return value.nodeType === 3;
};
const isComment = (value) => {
return value.nodeType === 8;
};
const STYLE = qDev
? `background: #564CE0; color: white; padding: 2px 3px; border-radius: 2px; font-size: 0.8em;`
: '';
const logError = (message, ...optionalParams) => {
return createAndLogError(false, message, ...optionalParams);
};
const throwErrorAndStop = (message, ...optionalParams) => {
const error = createAndLogError(false, message, ...optionalParams);
// eslint-disable-next-line no-debugger
debugger;
throw error;
};
const logErrorAndStop = (message, ...optionalParams) => {
const err = createAndLogError(qDev, message, ...optionalParams);
// eslint-disable-next-line no-debugger
debugger;
return err;
};
const _printed = /*#__PURE__*/ new Set();
const logOnceWarn = (message, ...optionalParams) => {
if (qDev) {
const key = 'warn' + String(message);
if (!_printed.has(key)) {
_printed.add(key);
logWarn(message, ...optionalParams);
}
}
};
const logWarn = (message, ...optionalParams) => {
if (qDev) {
console.warn('%cQWIK WARN', STYLE, message, ...printParams(optionalParams));
}
};
const logDebug = (message, ...optionalParams) => {
if (qDev) {
// eslint-disable-next-line no-console
console.debug('%cQWIK', STYLE, message, ...printParams(optionalParams));
}
};
const tryGetContext$1 = (element) => {
return element['_qc_'];
};
const printParams = (optionalParams) => {
if (qDev) {
return optionalParams.map((p) => {
if (isNode$1(p) && isElement$1(p)) {
return printElement(p);
}
return p;
});
}
return optionalParams;
};
const printElement = (el) => {
const ctx = tryGetContext$1(el);
const isServer = /*#__PURE__*/ (() => typeof process !== 'undefined' && !!process.versions && !!process.versions.node)();
return {
tagName: el.tagName,
renderQRL: ctx?.$componentQrl$?.getSymbol(),
element: isServer ? undefined : el,
ctx: isServer ? undefined : ctx,
};
};
const createAndLogError = (asyncThrow, message, ...optionalParams) => {
const err = message instanceof Error ? message : new Error(message);
// display the error message first, then the optional params, and finally the stack trace
// the stack needs to be displayed last because the given params will be lost among large stack traces so it will
// provide a bad developer experience
console.error('%cQWIK ERROR', STYLE, err.message, ...printParams(optionalParams), err.stack);
asyncThrow &&
!qTest &&
setTimeout(() => {
// throwing error asynchronously to avoid breaking the current call stack.
// We throw so that the error is delivered to the global error handler for
// reporting it to a third-party tools such as Qwik Insights, Sentry or New Relic.
throw err;
}, 0);
return err;
};
const ASSERT_DISCLAIMER = 'Internal assert, this is likely caused by a bug in Qwik: ';
function assertDefined(value, text, ...parts) {
if (qDev) {
if (value != null) {
return;
}
throwErrorAndStop(ASSERT_DISCLAIMER + text, ...parts);
}
}
function assertEqual(value1, value2, text, ...parts) {
if (qDev) {
if (value1 === value2) {
return;
}
throwErrorAndStop(ASSERT_DISCLAIMER + text, ...parts);
}
}
function assertFail(text, ...parts) {
if (qDev) {
throwErrorAndStop(ASSERT_DISCLAIMER + text, ...parts);
}
}
function assertTrue(value1, text, ...parts) {
if (qDev) {
if (value1 === true) {
return;
}
throwErrorAndStop(ASSERT_DISCLAIMER + text, ...parts);
}
}
function assertNumber(value1, text, ...parts) {
if (qDev) {
if (typeof value1 === 'number') {
return;
}
throwErrorAndStop(ASSERT_DISCLAIMER + text, ...parts);
}
}
function assertString(value1, text, ...parts) {
if (qDev) {
if (typeof value1 === 'string') {
return;
}
throwErrorAndStop(ASSERT_DISCLAIMER + text, ...parts);
}
}
function assertQwikElement(el) {
if (qDev) {
if (!isQwikElement(el)) {
console.error('Not a Qwik Element, got', el);
throwErrorAndStop(ASSERT_DISCLAIMER + 'Not a Qwik Element');
}
}
}
function assertElement(el) {
if (qDev) {
if (!isElement$1(el)) {
console.error('Not a Element, got', el);
throwErrorAndStop(ASSERT_DISCLAIMER + 'Not an Element');
}
}
}
const codeToText = (code, ...parts) => {
if (qDev) {
// Keep one error, one line to make it easier to search for the error message.
const MAP = [
'Error while serializing class or style attributes', // 0
'Can not serialize a HTML Node that is not an Element', // 1
'Runtime but no instance found on element.', // 2
'Only primitive and object literals can be serialized', // 3
'Crash while rendering', // 4
'You can render over a existing q:container. Skipping render().', // 5
'Set property {{0}}', // 6
"Only function's and 'string's are supported.", // 7
"Only objects can be wrapped in 'QObject'", // 8
`Only objects literals can be wrapped in 'QObject'`, // 9
'QRL is not a function', // 10
'Dynamic import not found', // 11
'Unknown type argument', // 12
`Actual value for useContext({{0}}) can not be found, make sure some ancestor component has set a value using useContextProvider(). In the browser make sure that the context was used during SSR so its state was serialized.`, // 13
"Invoking 'use*()' method outside of invocation context.", // 14
'Cant access renderCtx for existing context', // 15
'Cant access document for existing context', // 16
'props are immutable', // 17
'<div> component can only be used at the root of a Qwik component$()', // 18
'Props are immutable by default.', // 19
`Calling a 'use*()' method outside 'component$(() => { HERE })' is not allowed. 'use*()' methods provide hooks to the 'component$' state and lifecycle, ie 'use' hooks can only be called synchronously within the 'component$' function or another 'use' method.\nSee https://qwik.dev/docs/components/tasks/#use-method-rules`, // 20
'Container is already paused. Skipping', // 21
'', // 22 -- unused
'When rendering directly on top of Document, the root node must be a <html>', // 23
'A <html> node must have 2 children. The first one <head> and the second one a <body>', // 24
'Invalid JSXNode type "{{0}}". It must be either a function or a string. Found:', // 25
'Tracking value changes can only be done to useStore() objects and component props', // 26
'Missing Object ID for captured object', // 27
'The provided Context reference "{{0}}" is not a valid context created by createContextId()', // 28
'<html> is the root container, it can not be rendered inside a component', // 29
'QRLs can not be resolved because it does not have an attached container. This means that the QRL does not know where it belongs inside the DOM, so it cant dynamically import() from a relative path.', // 30
'QRLs can not be dynamically resolved, because it does not have a chunk path', // 31
'The JSX ref attribute must be a Signal', // 32
];
let text = MAP[code] ?? '';
if (parts.length) {
text = text.replaceAll(/{{(\d+)}}/g, (_, index) => {
let v = parts[index];
if (v && typeof v === 'object' && v.constructor === Object) {
v = JSON.stringify(v).slice(0, 50);
}
return v;
});
}
return `Code(${code}): ${text}`;
}
else {
// cute little hack to give roughly the correct line number. Update the line number if it shifts.
return `Code(${code}) https://github.com/QwikDev/qwik/blob/main/packages/qwik/src/core/error/error.ts#L${8 + code}`;
}
};
const QError_stringifyClassOrStyle = 0;
const QError_verifySerializable = 3;
const QError_cannotRenderOverExistingContainer = 5;
const QError_setProperty = 6;
const QError_qrlIsNotFunction = 10;
const QError_dynamicImportFailed = 11;
const QError_unknownTypeArgument = 12;
const QError_notFoundContext = 13;
const QError_useMethodOutsideContext = 14;
const QError_immutableProps = 17;
const QError_useInvokeContext = 20;
const QError_containerAlreadyPaused = 21;
const QError_invalidJsxNodeType = 25;
const QError_trackUseStore = 26;
const QError_missingObjectId = 27;
const QError_invalidContext = 28;
const QError_canNotRenderHTML = 29;
const QError_qrlMissingContainer = 30;
const QError_qrlMissingChunk = 31;
const QError_invalidRefValue = 32;
const qError = (code, ...parts) => {
const text = codeToText(code, ...parts);
return logErrorAndStop(text, ...parts);
};
// keep this import from qwik/build so the cjs build works
const createPlatform = () => {
return {
isServer: build.isServer,
importSymbol(containerEl, url, symbolName) {
if (build.isServer) {
const hash = getSymbolHash(symbolName);
const regSym = globalThis.__qwik_reg_symbols?.get(hash);
if (regSym) {
return regSym;
}
}
if (!url) {
throw qError(QError_qrlMissingChunk, symbolName);
}
if (!containerEl) {
throw qError(QError_qrlMissingContainer, url, symbolName);
}
const urlDoc = toUrl(containerEl.ownerDocument, containerEl, url).toString();
const urlCopy = new URL(urlDoc);
urlCopy.hash = '';
const importURL = urlCopy.href;
return import(/* @vite-ignore */ importURL).then((mod) => {
return mod[symbolName];
});
},
raf: (fn) => {
return new Promise((resolve) => {
requestAnimationFrame(() => {
resolve(fn());
});
});
},
nextTick: (fn) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve(fn());
});
});
},
chunkForSymbol(symbolName, chunk) {
return [symbolName, chunk ?? '_'];
},
};
};
/**
* Convert relative base URI and relative URL into a fully qualified URL.
*
* @param base -`QRL`s are relative, and therefore they need a base for resolution.
*
* - `Element` use `base.ownerDocument.baseURI`
* - `Document` use `base.baseURI`
* - `string` use `base` as is
* - `QConfig` use `base.baseURI`
*
* @param url - Relative URL
* @returns Fully qualified URL.
*/
const toUrl = (doc, containerEl, url) => {
const baseURI = doc.baseURI;
const base = new URL(containerEl.getAttribute('q:base') ?? baseURI, baseURI);
return new URL(url, base);
};
let _platform = /*#__PURE__ */ createPlatform();
// <docs markdown="./readme.md#setPlatform">
// !!DO NOT EDIT THIS COMMENT DIRECTLY!!!
// (edit ./readme.md#setPlatform instead)
/**
* Sets the `CorePlatform`.
*
* This is useful to override the platform in tests to change the behavior of,
* `requestAnimationFrame`, and import resolution.
*
* @param doc - The document of the application for which the platform is needed.
* @param platform - The platform to use.
* @public
*/
// </docs>
const setPlatform = (plt) => (_platform = plt);
// <docs markdown="./readme.md#getPlatform">
// !!DO NOT EDIT THIS COMMENT DIRECTLY!!!
// (edit ./readme.md#getPlatform instead)
/**
* Retrieve the `CorePlatform`.
*
* The `CorePlatform` is also responsible for retrieving the Manifest, that contains mappings from
* symbols to javascript import chunks. For this reason, `CorePlatform` can't be global, but is
* specific to the application currently running. On server it is possible that many different
* applications are running in a single server instance, and for this reason the `CorePlatform` is
* associated with the application document.
*
* @param docOrNode - The document (or node) of the application for which the platform is needed.
* @public
*/
// </docs>
const getPlatform = () => {
return _platform;
};
const isServerPlatform = () => {
if (qDynamicPlatform) {
return _platform.isServer;
}
return false;
};
/** @private */
const isSerializableObject = (v) => {
const proto = Object.getPrototypeOf(v);
return proto === Object.prototype || proto === null;
};
const isObject = (v) => {
return !!v && typeof v === 'object';
};
const isArray = (v) => {
return Array.isArray(v);
};
const isString = (v) => {
return typeof v === 'string';
};
const isFunction = (v) => {
return typeof v === 'function';
};
const isPromise = (value) => {
// not using "value instanceof Promise" to have zone.js support
return value && typeof value.then === 'function';
};
const safeCall = (call, thenFn, rejectFn) => {
try {
const promise = call();
if (isPromise(promise)) {
return promise.then(thenFn, rejectFn);
}
else {
return thenFn(promise);
}
}
catch (e) {
return rejectFn(e);
}
};
const maybeThen = (promise, thenFn) => {
return isPromise(promise) ? promise.then(thenFn) : thenFn(promise);
};
const promiseAll = (promises) => {
const hasPromise = promises.some(isPromise);
if (hasPromise) {
return Promise.all(promises);
}
return promises;
};
const promiseAllLazy = (promises) => {
if (promises.length > 0) {
return Promise.all(promises);
}
return promises;
};
const isNotNullable = (v) => {
return v != null;
};
const delay = (timeout) => {
return new Promise((resolve) => {
setTimeout(resolve, timeout);
});
};
// import { qDev } from './qdev';
const EMPTY_ARRAY = [];
const EMPTY_OBJ = {};
if (qDev) {
Object.freeze(EMPTY_ARRAY);
Object.freeze(EMPTY_OBJ);
}
const getDocument = (node) => {
if (!qDynamicPlatform) {
return document;
}
if (typeof document !== 'undefined') {
return document;
}
if (node.nodeType === 9) {
return node;
}
const doc = node.ownerDocument;
assertDefined(doc, 'doc must be defined');
return doc;
};
/** State factory of the component. */
const OnRenderProp = 'q:renderFn';
/** Component style content prefix */
const ComponentStylesPrefixContent = '⭐️';
/** `<some-element q:slot="...">` */
const QSlot = 'q:slot';
const QSlotRef = 'q:sref';
const QSlotS = 'q:s';
const QStyle = 'q:style';
const QScopedStyle = 'q:sstyle';
const QInstance = 'q:instance';
const QFuncsPrefix = 'qFuncs_';
const getQFuncs = (document, hash) => {
return document[QFuncsPrefix + hash] || [];
};
const QLocaleAttr = 'q:locale';
const QContainerAttr = 'q:container';
const QContainerSelector = '[q\\:container]';
const ResourceEvent = 'qResource';
const ComputedEvent = 'qComputed';
const RenderEvent = 'qRender';
const TaskEvent = 'qTask';
const ELEMENT_ID = 'q:id';
const ELEMENT_ID_PREFIX = '#';
const QObjectRecursive = 1 << 0;
const QObjectImmutable = 1 << 1;
const QOjectTargetSymbol = Symbol('proxy target');
const QObjectFlagsSymbol = Symbol('proxy flags');
const QObjectManagerSymbol = Symbol('proxy manager');
/** @internal */
const _IMMUTABLE = Symbol('IMMUTABLE');
const _IMMUTABLE_PREFIX = '$$';
/**
* @internal
* Key for the virtual element stored on qv comments
*/
const VIRTUAL_SYMBOL = '__virtual';
/**
* @internal
* Key for the `QContext` object stored on QwikElements
*/
const Q_CTX = '_qc_';
const directSetAttribute = (el, prop, value) => {
return el.setAttribute(prop, value);
};
const directGetAttribute = (el, prop) => {
return el.getAttribute(prop);
};
const directRemoveAttribute = (el, prop) => {
return el.removeAttribute(prop);
};
const fromCamelToKebabCase = (text) => {
return text.replace(/([A-Z])/g, '-$1').toLowerCase();
};
const fromKebabToCamelCase = (text) => {
return text.replace(/-./g, (x) => x[1].toUpperCase());
};
// keep this import from qwik/build so the cjs build works
const emitEvent$1 = (el, eventName, detail, bubbles) => {
if (!qTest && (build.isBrowser || typeof CustomEvent === 'function')) {
if (el) {
el.dispatchEvent(new CustomEvent(eventName, {
detail,
bubbles: bubbles,
composed: bubbles,
}));
}
}
};
/** Creates a proxy that notifies of any writes. */
const getOrCreateProxy = (target, containerState, flags = 0) => {
const proxy = containerState.$proxyMap$.get(target);
if (proxy) {
return proxy;
}
if (flags !== 0) {
setObjectFlags(target, flags);
}
return createProxy(target, containerState, undefined);
};
const createProxy = (target, containerState, subs) => {
assertEqual(unwrapProxy(target), target, 'Unexpected proxy at this location', target);
assertTrue(!containerState.$proxyMap$.has(target), 'Proxy was already created', target);
assertTrue(isObject(target), 'Target must be an object');
assertTrue(isSerializableObject(target) || isArray(target), 'Target must be a serializable object');
const manager = containerState.$subsManager$.$createManager$(subs);
const proxy = new Proxy(target, new ReadWriteProxyHandler(containerState, manager));
containerState.$proxyMap$.set(target, proxy);
return proxy;
};
const createPropsState = () => {
const props = {};
setObjectFlags(props, QObjectImmutable);
return props;
};
const setObjectFlags = (obj, flags) => {
Object.defineProperty(obj, QObjectFlagsSymbol, { value: flags, enumerable: false });
};
/** @internal */
const _restProps = (props, omit) => {
const rest = {};
for (const key in props) {
if (!omit.includes(key)) {
rest[key] = props[key];
}
}
return rest;
};
class ReadWriteProxyHandler {
$containerState$;
$manager$;
constructor($containerState$, $manager$) {
this.$containerState$ = $containerState$;
this.$manager$ = $manager$;
}
deleteProperty(target, prop) {
if (target[QObjectFlagsSymbol] & QObjectImmutable) {
throw qError(QError_immutableProps);
}
if (typeof prop != 'string' || !delete target[prop]) {
return false;
}
this.$manager$.$notifySubs$(isArray(target) ? undefined : prop);
return true;
}
get(target, prop) {
if (typeof prop === 'symbol') {
if (prop === QOjectTargetSymbol) {
return target;
}
if (prop === QObjectManagerSymbol) {
return this.$manager$;
}
return target[prop];
}
const flags = target[QObjectFlagsSymbol] ?? 0;
assertNumber(flags, 'flags must be an number');
const invokeCtx = tryGetInvokeContext();
const recursive = (flags & QObjectRecursive) !== 0;
const immutable = (flags & QObjectImmutable) !== 0;
const hiddenSignal = target[_IMMUTABLE_PREFIX + prop];
let subscriber;
let value;
if (invokeCtx) {
subscriber = invokeCtx.$subscriber$;
}
if (immutable && (!(prop in target) || immutableValue(target[_IMMUTABLE]?.[prop]))) {
subscriber = null;
}
if (hiddenSignal) {
assertTrue(isSignal(hiddenSignal), '$$ prop must be a signal');
value = hiddenSignal.value;
subscriber = null;
}
else {
value = target[prop];
}
if (subscriber) {
const isA = isArray(target);
this.$manager$.$addSub$(subscriber, isA ? undefined : prop);
}
return recursive ? wrap(value, this.$containerState$) : value;
}
set(target, prop, newValue) {
if (typeof prop === 'symbol') {
target[prop] = newValue;
return true;
}
const flags = target[QObjectFlagsSymbol] ?? 0;
assertNumber(flags, 'flags must be an number');
const immutable = (flags & QObjectImmutable) !== 0;
if (immutable) {
throw qError(QError_immutableProps);
}
const recursive = (flags & QObjectRecursive) !== 0;
const unwrappedNewValue = recursive ? unwrapProxy(newValue) : newValue;
if (qDev) {
if (qSerialize) {
verifySerializable(unwrappedNewValue);
}
const invokeCtx = tryGetInvokeContext();
if (invokeCtx) {
if (invokeCtx.$event$ === RenderEvent) {
logError('State mutation inside render function. Move mutation to useTask$() or useVisibleTask$()', prop);
}
else if (invokeCtx.$event$ === ComputedEvent) {
logWarn('State mutation inside useComputed$() is an antipattern. Use useTask$() instead', invokeCtx.$hostElement$);
}
else if (invokeCtx.$event$ === ResourceEvent) {
logWarn('State mutation inside useResource$() is an antipattern. Use useTask$() instead', invokeCtx.$hostElement$);
}
}
}
const isA = isArray(target);
if (isA) {
target[prop] = unwrappedNewValue;
this.$manager$.$notifySubs$();
return true;
}
const oldValue = target[prop];
target[prop] = unwrappedNewValue;
if (oldValue !== unwrappedNewValue) {
this.$manager$.$notifySubs$(prop);
}
return true;
}
has(target, prop) {
if (prop === QOjectTargetSymbol) {
return true;
}
const invokeCtx = tryGetInvokeContext();
if (typeof prop === 'string' && invokeCtx) {
const subscriber = invokeCtx.$subscriber$;
if (subscriber) {
const isA = isArray(target);
this.$manager$.$addSub$(subscriber, isA ? undefined : prop);
}
}
const hasOwnProperty = Object.prototype.hasOwnProperty;
if (hasOwnProperty.call(target, prop)) {
return true;
}
if (typeof prop === 'string' && hasOwnProperty.call(target, _IMMUTABLE_PREFIX + prop)) {
return true;
}
return false;
}
ownKeys(target) {
const flags = target[QObjectFlagsSymbol] ?? 0;
assertNumber(flags, 'flags must be an number');
const immutable = (flags & QObjectImmutable) !== 0;
if (!immutable) {
let subscriber = null;
const invokeCtx = tryGetInvokeContext();
if (invokeCtx) {
subscriber = invokeCtx.$subscriber$;
}
if (subscriber) {
this.$manager$.$addSub$(subscriber);
}
}
if (isArray(target)) {
return Reflect.ownKeys(target);
}
return Reflect.ownKeys(target).map((a) => {
return typeof a === 'string' && a.startsWith(_IMMUTABLE_PREFIX)
? a.slice(_IMMUTABLE_PREFIX.length)
: a;
});
}
getOwnPropertyDescriptor(target, prop) {
const descriptor = Reflect.getOwnPropertyDescriptor(target, prop);
if (isArray(target) || typeof prop === 'symbol') {
return descriptor;
}
if (descriptor && !descriptor.configurable) {
return descriptor;
}
return {
enumerable: true,
configurable: true,
};
}
}
const immutableValue = (value) => {
return value === _IMMUTABLE || isSignal(value);
};
const wrap = (value, containerState) => {
if (isObject(value)) {
if (Object.isFrozen(value)) {
return value;
}
const nakedValue = unwrapProxy(value);
if (nakedValue !== value) {
// already a proxy return;
return value;
}
if (fastSkipSerialize(nakedValue)) {
return value;
}
if (isSerializableObject(nakedValue) || isArray(nakedValue)) {
const proxy = containerState.$proxyMap$.get(nakedValue);
return proxy ? proxy : getOrCreateProxy(nakedValue, containerState, QObjectRecursive);
}
}
return value;
};
const ON_PROP_REGEX = /^(on|window:|document:)/;
const PREVENT_DEFAULT = 'preventdefault:';
const isOnProp = (prop) => {
return prop.endsWith('$') && ON_PROP_REGEX.test(prop);
};
const groupListeners = (listeners) => {
if (listeners.length === 0) {
return EMPTY_ARRAY;
}
if (listeners.length === 1) {
const listener = listeners[0];
return [[listener[0], [listener[1]]]];
}
const keys = [];
for (let i = 0; i < listeners.length; i++) {
const eventName = listeners[i][0];
if (!keys.includes(eventName)) {
keys.push(eventName);
}
}
return keys.map((eventName) => {
return [eventName, listeners.filter((l) => l[0] === eventName).map((a) => a[1])];
});
};
const setEvent = (existingListeners, prop, input, containerEl) => {
assertTrue(prop.endsWith('$'), 'render: event property does not end with $', prop);
prop = normalizeOnProp(prop.slice(0, -1));
if (input) {
if (isArray(input)) {
const processed = input
.flat(Infinity)
.filter((q) => q != null)
.map((q) => [prop, ensureQrl(q, containerEl)]);
existingListeners.push(...processed);
}
else {
existingListeners.push([prop, ensureQrl(input, containerEl)]);
}
}
return prop;
};
const PREFIXES = ['on', 'window:on', 'document:on'];
const SCOPED = ['on', 'on-window', 'on-document'];
const normalizeOnProp = (prop) => {
let scope = 'on';
for (let i = 0; i < PREFIXES.length; i++) {
const prefix = PREFIXES[i];
if (prop.startsWith(prefix)) {
scope = SCOPED[i];
prop = prop.slice(prefix.length);
break;
}
}
if (prop.startsWith('-')) {
prop = fromCamelToKebabCase(prop.slice(1));
}
else {
prop = prop.toLowerCase();
}
return scope + ':' + prop;
};
const ensureQrl = (value, containerEl) => {
if (qSerialize && !qRuntimeQrl) {
assertQrl(value);
value.$setContainer$(containerEl);
return value;
}
const qrl = isQrl(value) ? value : $(value);
qrl.$setContainer$(containerEl);
return qrl;
};
const getDomListeners = (elCtx, containerEl) => {
const attributes = elCtx.$element$.attributes;
const listeners = [];
for (let i = 0; i < attributes.length; i++) {
const { name, value } = attributes.item(i);
if (name.startsWith('on:') ||
name.startsWith('on-window:') ||
name.startsWith('on-document:')) {
const urls = value.split('\n');
for (const url of urls) {
const qrl = parseQRL(url, containerEl);
if (qrl.$capture$) {
inflateQrl(qrl, elCtx);
}
listeners.push([name, qrl]);
}
}
}
return listeners;
};
const hashCode = (text, hash = 0) => {
for (let i = 0; i < text.length; i++) {
const chr = text.charCodeAt(i);
hash = (hash << 5) - hash + chr;
hash |= 0; // Convert to 32bit integer
}
return Number(Math.abs(hash)).toString(36);
};
const styleKey = (qStyles, index) => {
assertQrl(qStyles);
return `${hashCode(qStyles.$hash$)}-${index}`;
};
const styleContent = (styleId) => {
return ComponentStylesPrefixContent + styleId;
};
const serializeSStyle = (scopeIds) => {
const value = scopeIds.join('|');
if (value.length > 0) {
return value;
}
return undefined;
};
/**
* QWIK_VERSION
*
* @public
*/
const version = "1.13.0-dev+4571b3c";
/**
* @internal
* The storage provider for hooks. Each invocation increases index i. Data is stored in an array.
*/
const useSequentialScope = () => {
const iCtx = useInvokeContext();
const hostElement = iCtx.$hostElement$;
const elCtx = getContext(hostElement, iCtx.$renderCtx$.$static$.$containerState$);
const seq = (elCtx.$seq$ ||= []);
const i = iCtx.$i$++;
const set = (value) => {
if (qDev && qSerialize) {
verifySerializable(value);
}
return (seq[i] = value);
};
return {
val: seq[i],
set,
i,
iCtx,
elCtx,
};
};
// <docs markdown="../readme.md#createContextId">
// !!DO NOT EDIT THIS COMMENT DIRECTLY!!!
// (edit ../readme.md#createContextId instead)
/**
* Create a context ID to be used in your application. The name should be written with no spaces.
*
* Context is a way to pass stores to the child components without prop-drilling.
*
* Use `createContextId()` to create a `ContextId`. A `ContextId` is just a serializable identifier
* for the context. It is not the context value itself. See `useContextProvider()` and
* `useContext()` for the values. Qwik needs a serializable ID for the context so that the it can
* track context providers and consumers in a way that survives resumability.
*
* ### Example
*
* ```tsx
* // Declare the Context type.
* interface TodosStore {
* items: string[];
* }
* // Create a Context ID (no data is saved here.)
* // You will use this ID to both create and retrieve the Context.
* export const TodosContext = createContextId<TodosStore>('Todos');
*
* // Example of providing context to child components.
* export const App = component$(() => {
* useContextProvider(
* TodosContext,
* useStore<TodosStore>({
* items: ['Learn Qwik', 'Build Qwik app', 'Profit'],
* })
* );
*
* return <Items />;
* });
*
* // Example of retrieving the context provided by a parent component.
* export const Items = component$(() => {
* const todos = useContext(TodosContext);
* return (
* <ul>
* {todos.items.map((item) => (
* <li>{item}</li>
* ))}
* </ul>
* );
* });
*
* ```