-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsupport.js
More file actions
1687 lines (1671 loc) · 59.6 KB
/
Copy pathsupport.js
File metadata and controls
1687 lines (1671 loc) · 59.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
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
// GENERATED from dc-runtime/src/*.ts — do not edit. Rebuild with `cd dc-runtime && bun run build`.
"use strict";
(() => {
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
// src/react.ts
function getReact() {
const R = window.React;
if (!R) throw new Error("dc-runtime: window.React is not available yet");
return R;
}
function getReactDOM() {
const RD = window.ReactDOM;
if (!RD) throw new Error("dc-runtime: window.ReactDOM is not available yet");
return RD;
}
var h = ((...args) => getReact().createElement(
...args
));
// src/parse.ts
function parseDcDocument(doc) {
const dc = doc.querySelector("x-dc");
if (!dc) return null;
const scriptEl = doc.querySelector("script[data-dc-script]");
const { props, preview } = parseDataProps(
scriptEl?.getAttribute("data-props") ?? null
);
return {
template: dc.innerHTML,
js: scriptEl ? scriptEl.textContent || "" : "",
props,
preview
};
}
function parseDcText(src) {
const openMatch = /<x-dc(?:\s[^>]*)?>/.exec(src);
if (!openMatch) return null;
const close = src.lastIndexOf("</x-dc>");
if (close === -1 || close < openMatch.index) return null;
const template = src.slice(openMatch.index + openMatch[0].length, close);
const doc = new DOMParser().parseFromString(src, "text/html");
const scriptEl = doc.querySelector("script[data-dc-script]");
const { props, preview } = parseDataProps(
scriptEl?.getAttribute("data-props") ?? null
);
return {
template,
js: scriptEl ? scriptEl.textContent || "" : "",
props,
preview
};
}
function parseDataProps(raw) {
if (!raw) return { props: null, preview: null };
let parsed;
try {
parsed = JSON.parse(raw);
} catch {
return { props: null, preview: null };
}
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
return { props: null, preview: null };
}
const obj = parsed;
const preview = obj.$preview && typeof obj.$preview === "object" ? obj.$preview : null;
const rest = {};
for (const k of Object.keys(obj)) {
if (k[0] !== "$") rest[k] = obj[k];
}
return { props: Object.keys(rest).length ? rest : null, preview };
}
function dcNameFromPath(pathname) {
let p = pathname || "";
try {
p = decodeURIComponent(p);
} catch {
}
const base = p.split("/").pop() || "Root";
return base.replace(/\.dc\.html$/, "").replace(/\.html?$/, "") || "Root";
}
// src/boot.ts
var BASE_CSS = `
.sc-placeholder{background:color-mix(in srgb,currentColor 8%,transparent);
border:1px solid color-mix(in srgb,currentColor 50%,transparent);
border-radius:2px;box-sizing:border-box;overflow:hidden}
@keyframes sc-shine{0%{background-position:100% 50%}100%{background-position:0% 50%}}
html.sc-dc-streaming .sc-placeholder,
html.sc-dc-streaming .sc-interp.sc-missing{position:relative;
background:color-mix(in srgb,currentColor 5%,transparent);
border-color:transparent}
html.sc-dc-streaming .sc-placeholder::before,
html.sc-dc-streaming .sc-interp.sc-missing::before{content:'';
position:absolute;inset:0;pointer-events:none;
background:linear-gradient(90deg,rgba(217,119,87,0) 25%,rgba(247,225,211,.95) 37%,rgba(217,119,87,0) 63%);
background-size:400% 100%;animation:sc-shine 1.4s ease infinite}
html.sc-dc-streaming .sc-placeholder:nth-child(n+9 of .sc-placeholder)::before,
html.sc-dc-streaming .sc-interp.sc-missing:nth-child(n+9 of .sc-interp.sc-missing)::before{animation:none;
background:color-mix(in srgb,currentColor 8%,transparent)}
.sc-placeholder-error{padding:4px 8px;font:11px/1.4 ui-monospace,monospace;
color:color-mix(in srgb,currentColor 70%,transparent);word-break:break-word}
.sc-interp.sc-missing{display:inline-block;width:2em;height:1em;overflow:hidden;
vertical-align:text-bottom;background:rgba(255,255,255,.3);border:1px solid rgba(0,0,0,.5);
border-radius:2px;box-sizing:border-box;color:transparent;
user-select:none}
.sc-interp.sc-unresolved{font-family:ui-monospace,monospace;font-size:.85em;
color:color-mix(in srgb,currentColor 50%,transparent);
background:color-mix(in srgb,currentColor 10%,transparent);border-radius:3px;
padding:0 3px}
.sc-host.sc-has-error{position:relative}
.sc-logic-error{position:absolute;top:8px;left:8px;z-index:2147483647;max-width:60ch;
padding:6px 10px;background:#b00020;color:#fff;font:12px/1.4 ui-monospace,monospace;
border-radius:4px;white-space:pre-wrap;pointer-events:none}
/* Mirrors PRINT_BASELINE_CSS in apps/web deck-stage-export.ts \u2014 keep both
in sync until dc-runtime regains a build step. */
@media print {
@page { margin: 0.5cm; }
figure, table { break-inside: avoid; }
#dc-root, #dc-root > .sc-host { height: auto; }
*, *::before, *::after {
print-color-adjust: exact; -webkit-print-color-adjust: exact;
backdrop-filter: none !important; -webkit-backdrop-filter: none !important;
animation-delay: -99s !important; animation-duration: .001s !important;
animation-iteration-count: 1 !important; animation-fill-mode: both !important;
animation-play-state: running !important; transition-duration: 0s !important;
}
}
`;
var FULL_PAGE_CSS = "html,body{height:100%;margin:0}#dc-root,#dc-root>.sc-host{height:100%}";
function rootNameForDocument(doc, loc) {
let bootPath = loc.pathname || "";
if (!/\.dc\.html?$/i.test(safeDecode(bootPath))) {
try {
bootPath = new URL(doc.baseURI || "/").pathname;
} catch {
}
}
return dcNameFromPath(bootPath);
}
function safeDecode(s) {
try {
return decodeURIComponent(s);
} catch {
return s;
}
}
function boot(runtime, doc = document) {
const parsed = parseDcDocument(doc);
if (!parsed) return null;
const React = getReact();
const rootName = rootNameForDocument(doc, location);
runtime.markFetched(rootName);
runtime.setRootName(rootName);
runtime.adoptParsed(rootName, parsed);
fetch(location.href).then((res) => res.ok ? res.text() : "").then((t) => {
const raw = t ? parseDcText(t) : null;
if (raw?.template) runtime.updateHtml(rootName, raw.template);
}).catch(() => {
});
const dc = doc.querySelector("x-dc");
const hostEl = doc.createElement("div");
hostEl.id = "dc-root";
dc.replaceWith(hostEl);
if (!parsed.preview) {
const s = doc.createElement("style");
s.textContent = FULL_PAGE_CSS;
doc.head.appendChild(s);
}
const Root = runtime.getDC(rootName);
const entry = runtime.registry.get(rootName);
function StandaloneRoot() {
const [, setTick] = React.useState(0);
React.useEffect(() => {
const sub = () => setTick((n) => n + 1);
entry.subs.add(sub);
return () => {
entry.subs.delete(sub);
};
}, []);
const defaults = React.useMemo(() => {
const d = {};
for (const k in entry.propsMeta || {}) {
const v = entry.propsMeta?.[k]?.default;
if (v !== void 0) d[k] = v;
}
return d;
}, [entry.propsMeta]);
return h(Root, { ...defaults, ...entry.propOverrides || {} });
}
const ReactDOM = getReactDOM();
if (ReactDOM.createRoot)
ReactDOM.createRoot(hostEl).render(h(StandaloneRoot));
else ReactDOM.render(h(StandaloneRoot), hostEl);
return rootName;
}
// src/expr.ts
var IDENT_RE = /^[A-Za-z_$][A-Za-z0-9_$]*/;
var NUMBER_RE = /^-?\d+(\.\d+)?$/;
function resolve(vals, src) {
const expr = String(src).trim();
if (!expr) return void 0;
if (expr[0] === "(" && expr[expr.length - 1] === ")" && parensWrapWhole(expr)) {
return resolve(vals, expr.slice(1, -1));
}
const eq = findTopLevelEquality(expr);
if (eq) {
const lv = resolve(vals, expr.slice(0, eq.index));
const rv = resolve(vals, expr.slice(eq.index + eq.op.length));
switch (eq.op) {
case "===":
return lv === rv;
case "!==":
return lv !== rv;
case "==":
return lv == rv;
default:
return lv != rv;
}
}
if (expr[0] === "!") return !resolve(vals, expr.slice(1));
if (expr === "true") return true;
if (expr === "false") return false;
if (expr === "null") return null;
if (expr === "undefined") return void 0;
if (NUMBER_RE.test(expr)) return Number(expr);
if (expr.length >= 2 && (expr[0] === '"' || expr[0] === "'") && expr[expr.length - 1] === expr[0]) {
return expr.slice(1, -1);
}
return resolvePath(vals, expr);
}
function parensWrapWhole(expr) {
let depth = 0;
for (let i = 0; i < expr.length - 1; i++) {
if (expr[i] === "(") depth++;
else if (expr[i] === ")") {
depth--;
if (depth === 0) return false;
}
}
return true;
}
function findTopLevelEquality(expr) {
let depth = 0;
for (let i = 0; i < expr.length; i++) {
const c = expr[i];
if (c === "[" || c === "(") depth++;
else if (c === "]" || c === ")") depth--;
else if (depth === 0 && (c === "=" || c === "!") && expr[i + 1] === "=") {
if (i > 0 && (expr[i - 1] === "=" || expr[i - 1] === "!")) continue;
if (!expr.slice(0, i).trim()) continue;
const op = expr[i + 2] === "=" ? c + "==" : c + "=";
return { index: i, op };
}
}
return null;
}
function resolvePath(vals, expr) {
const head = expr.match(IDENT_RE);
if (!head) return void 0;
let cur = vals == null ? void 0 : vals[head[0]];
let i = head[0].length;
while (i < expr.length) {
if (expr[i] === ".") {
const m = expr.slice(i + 1).match(IDENT_RE) || expr.slice(i + 1).match(/^\d+/);
if (!m) return void 0;
cur = cur == null ? void 0 : cur[m[0]];
i += 1 + m[0].length;
} else if (expr[i] === "[") {
let depth = 1;
let j = i + 1;
while (j < expr.length && depth > 0) {
if (expr[j] === "[") depth++;
else if (expr[j] === "]") {
depth--;
if (depth === 0) break;
}
j++;
}
if (depth !== 0) return void 0;
const key = resolve(vals, expr.slice(i + 1, j));
cur = cur == null ? void 0 : cur[key];
i = j + 1;
} else {
return void 0;
}
}
return cur;
}
// src/encode.ts
var CAMEL_ATTR = "sc-camel-";
var INLINE_TEXT_TAGS = new Set(
"a abbr b bdi bdo br cite code del dfn em i ins kbd mark q s samp small span strike strong sub sup u var wbr".split(
" "
)
);
var RAW_WRAP = {
select: "sc-raw-select",
table: "sc-raw-table",
tbody: "sc-raw-tbody",
thead: "sc-raw-thead",
tfoot: "sc-raw-tfoot",
tr: "sc-raw-tr",
td: "sc-raw-td",
th: "sc-raw-th",
caption: "sc-raw-caption"
};
var RAW_UNWRAP = Object.fromEntries(
Object.entries(RAW_WRAP).map(([k, v]) => [v, k])
);
var EVENT_MAP = {
onclick: "onClick",
onchange: "onChange",
oninput: "onInput",
onsubmit: "onSubmit",
onkeydown: "onKeyDown",
onkeyup: "onKeyUp",
onkeypress: "onKeyPress",
onmousedown: "onMouseDown",
onmouseup: "onMouseUp",
onmouseenter: "onMouseEnter",
onmouseleave: "onMouseLeave",
onfocus: "onFocus",
onblur: "onBlur",
ondoubleclick: "onDoubleClick",
oncontextmenu: "onContextMenu"
};
var ATTRS = `(?:[^>"']|"[^"]*"|'[^']*')*`;
var IMPORT_SELF_CLOSE_RE = new RegExp(
"<(x-import|dc-import)(" + ATTRS + ")/>",
"gi"
);
var CAMEL_ATTR_RE = /(\s)([a-z]+[A-Z][A-Za-z0-9]*)(\s*=)/g;
function encodeCase(html) {
html = html.replace(
IMPORT_SELF_CLOSE_RE,
(_, t, a) => "<" + t + a + "></" + t + ">"
);
html = html.replace(/<helmet(\s|>)/gi, "<sc-helmet$1");
html = html.replace(/<\/helmet\s*>/gi, "</sc-helmet>");
html = html.replace(
CAMEL_ATTR_RE,
(_, sp, name, eq) => sp + CAMEL_ATTR + name.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase()) + eq
);
for (const [real, alias] of Object.entries(RAW_WRAP)) {
html = html.replace(
new RegExp("(</?)" + real + "(?=[\\s>])", "gi"),
"$1" + alias
);
}
return html;
}
function kebabToCamel(s) {
return s.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
}
function cssToObj(css) {
const o = {};
for (const decl of css.split(";")) {
const i = decl.indexOf(":");
if (i < 0) continue;
const prop = decl.slice(0, i).trim();
o[prop.startsWith("--") ? prop : kebabToCamel(prop)] = decl.slice(i + 1).trim();
}
return o;
}
function compileAttr(raw) {
const whole = raw.match(/^\s*\{\{([\s\S]+?)\}\}\s*$/);
if (whole) {
const path = whole[1];
return (vals) => resolve(vals, path);
}
if (raw.includes("{{")) {
const parts = raw.split(/\{\{([\s\S]+?)\}\}/g);
return (vals) => parts.map((s, i) => i & 1 ? resolve(vals, s) ?? "" : s).join("");
}
return () => raw;
}
// src/compile.ts
function collectProps(node, kind, host) {
const propGetters = [];
const pseudoClasses = [];
let hintSize = null;
for (const { name, value } of [...node.attributes]) {
if (name === "sc-name" || name === "data-dc-tpl") continue;
let key = name;
if (key.startsWith(CAMEL_ATTR))
key = kebabToCamel(key.slice(CAMEL_ATTR.length));
if (key === "hint-size") {
hintSize = value;
continue;
}
if (key.startsWith("style-")) {
pseudoClasses.push(host.pseudoClass(key.slice(6), value));
continue;
}
if (kind !== "dom") {
if (key.includes("-") && !(kind === "x-import" && (key.startsWith("aria-") || key.startsWith("data-"))))
key = kebabToCamel(key);
} else {
if (key === "class") key = "className";
else if (key === "for") key = "htmlFor";
else if (key.startsWith("on"))
key = EVENT_MAP[key] || "on" + key[2].toUpperCase() + key.slice(3);
}
propGetters.push([key, compileAttr(value)]);
}
return { propGetters, pseudoClasses, hintSize };
}
var HOST_STYLE_PROPS = /* @__PURE__ */ new Set([
"position",
"left",
"right",
"top",
"bottom",
"inset",
"width",
"height",
"z-index",
"transform"
]);
function hostPositionStyle(style) {
const all = typeof style === "string" ? cssToObj(style) : style != null && typeof style === "object" ? style : null;
if (!all) return void 0;
const out = {};
for (const [k, v] of Object.entries(all)) {
const kebab = k.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase());
if (HOST_STYLE_PROPS.has(kebab)) out[k] = v;
}
return Object.keys(out).length ? out : void 0;
}
function compileTemplate(html, host) {
const tpl = document.createElement("template");
//! nosemgrep: direct-inner-html-assignment
tpl.innerHTML = encodeCase(html);
let tplN = 0;
(function stamp(node) {
if (node.nodeType === Node.ELEMENT_NODE) {
node.setAttribute("data-dc-tpl", String(tplN++));
}
for (const c of node.childNodes) stamp(c);
})(tpl.content);
const builders = walkChildren(tpl.content, host);
const render = ((vals, ctx) => builders.map((b, i) => b(vals || {}, ctx, i)));
render.__annotated = tpl.innerHTML;
return render;
}
function walkChildren(node, host) {
return [...node.childNodes].map((c) => walk(c, host)).filter((b) => b != null);
}
function walk(node, host) {
if (node.nodeType === Node.TEXT_NODE) return walkText(node);
if (node.nodeType !== Node.ELEMENT_NODE) return null;
const el = node;
const tag = el.tagName.toLowerCase();
if (tag === "sc-for") return walkFor(el, host);
if (tag === "sc-if") return walkIf(el, host);
if (tag === "x-import") return walkXImport(el, host);
if (tag === "sc-helmet") return host.helmet(el);
if (tag === "dc-import") return walkComponent(el, host);
return walkElement(el, host);
}
var warnedHoles = /* @__PURE__ */ new Set();
function warnUnresolved(ctx, what) {
const key = (ctx?.__name || "?") + "\0" + what;
if (warnedHoles.has(key)) return;
warnedHoles.add(key);
console.warn("[dc-runtime] " + (ctx?.__name || "template") + ": " + what);
}
function walkText(node) {
const txt = node.nodeValue ?? "";
if (!txt.includes("{{")) {
if (!txt.trim() && !txt.includes(" ")) return null;
return () => txt;
}
const parts = txt.split(/\{\{([\s\S]+?)\}\}/g);
return (vals, ctx, key) => h(
getReact().Fragment,
{ key },
...parts.map((p, i) => {
if (!(i & 1)) return p;
const v = resolve(vals, p);
if (v === void 0) {
if (!ctx?.__streamingNow) {
if (document.body?.hasAttribute("data-dc-editor-on")) {
return h(
"span",
{ key: i, className: "sc-interp sc-unresolved" },
"{{ " + p.trim() + " }}"
);
}
warnUnresolved(
ctx,
"{{ " + p.trim() + " }} never resolved \u2014 rendered as empty"
);
return null;
}
return h(
"span",
{ key: i, className: "sc-interp sc-missing" },
p.trim()
);
}
if (getReact().isValidElement(v) || Array.isArray(v)) {
return h(getReact().Fragment, { key: i }, v);
}
if (v === null || typeof v === "boolean") return null;
return h("span", { key: i, className: "sc-interp" }, String(v));
})
);
}
function walkFor(el, host) {
const listGet = compileAttr(el.getAttribute("list") || "");
const asName = el.getAttribute("as") || "item";
const hintN = parseInt(el.getAttribute("hint-placeholder-count") || "0", 10);
const kids = walkChildren(el, host);
const listSrc = el.getAttribute("list") || "";
return (vals, ctx, key) => {
let list = listGet(vals);
if (!Array.isArray(list)) {
if (!ctx?.__streamingNow) {
if (list !== void 0 && list !== null) {
warnUnresolved(
ctx,
'sc-for list="' + listSrc + '" is not an array (' + typeof list + ")"
);
}
list = [];
} else {
list = hintN > 0 ? Array(hintN).fill(void 0) : [];
}
}
return h(
getReact().Fragment,
{ key },
list.map((item, i) => {
const sub = { ...vals, [asName]: item, $index: i };
return h(
getReact().Fragment,
{ key: i },
kids.map((b, j) => b(sub, ctx, j))
);
})
);
};
}
function walkIf(el, host) {
const valGet = compileAttr(el.getAttribute("value") || "");
const hintRaw = el.getAttribute("hint-placeholder-val");
const hintGet = hintRaw != null ? compileAttr(hintRaw) : null;
const kids = walkChildren(el, host);
return (vals, ctx, key) => {
let v = valGet(vals);
if (v === void 0 && hintGet && ctx?.__streamingNow) v = hintGet(vals);
return v ? h(
getReact().Fragment,
{ key },
kids.map((b, j) => b(vals, ctx, j))
) : null;
};
}
function walkComponent(el, host) {
const name = el.getAttribute("name") || el.getAttribute("component") || "";
el.removeAttribute("name");
el.removeAttribute("component");
const tplId = el.getAttribute("data-dc-tpl");
const styleRaw = el.getAttribute("style");
el.removeAttribute("style");
const styleGet = styleRaw != null ? compileAttr(styleRaw) : null;
const { propGetters, hintSize } = collectProps(el, "dc-import", host);
const kids = walkChildren(el, host);
return (vals, ctx, key) => {
const props = {
key,
__hintSize: hintSize,
__tplId: tplId,
__hostStyle: styleGet ? hostPositionStyle(styleGet(vals)) : void 0
};
for (const [k, g] of propGetters) {
const v = g(vals);
if (k === "dcProps") {
if (v && typeof v === "object") Object.assign(props, v);
continue;
}
props[k] = v;
}
if (kids.length) props.children = kids.map((b, j) => b(vals, ctx, j));
return h(host.component(name), props);
};
}
function walkXImport(el, host) {
const globalNameGet = compileAttr(
el.getAttribute("component-from-global-scope") || ""
);
const exportNameGet = compileAttr(
el.getAttribute("component") || el.getAttribute("name") || ""
);
const fromRaw = el.getAttribute("from") || el.getAttribute("src") || el.getAttribute("import") || "";
const urls = fromRaw.trim() ? fromRaw.trim().split(/\s+/) : [];
const url = urls.length ? urls[urls.length - 1] : "";
const kindOf = (u) => /\.(jsx|tsx)(\?|#|$)/i.test(u) ? "jsx" : "js";
const tplId = el.getAttribute("data-dc-tpl");
const styleRaw = el.getAttribute("style");
el.removeAttribute("style");
const styleGet = styleRaw != null ? compileAttr(styleRaw) : null;
const wrap = tplId != null || styleGet != null;
const { propGetters, hintSize } = collectProps(el, "x-import", host);
const hasContent = el.children.length > 0 || !!(el.textContent || "").trim();
const kids = hasContent ? walkChildren(el, host) : [];
const urlBindable = fromRaw.includes("{{");
if (urls.length && !urlBindable) {
let prev;
for (const u of urls) prev = host.loadExternal(kindOf(u), u, prev);
}
const evalName = (g, vals) => {
const v = g(vals);
const s = v == null ? "" : String(v);
return s.includes("{{") ? "" : s;
};
return (vals, ctx, key) => {
const globalName = evalName(globalNameGet, vals);
const name = globalName || evalName(exportNameGet, vals);
const C = !name || urlBindable ? null : globalName ? host.resolveExternalGlobal(url, globalName) : host.resolveExternal(url, name);
const hostStyle = styleGet ? hostPositionStyle(styleGet(vals)) : void 0;
const wrapper = wrap ? {
key,
className: "sc-host-x",
"data-dc-tpl": tplId,
style: hostStyle || { display: "contents" }
} : null;
if (!C) {
const error = urlBindable ? "x-import `from` cannot contain {{ \u2026 }} \u2014 module URLs are resolved at parse time; use a literal URL" : host.resolveExternalError(url, name);
const ph = host.placeholder({
key: wrapper ? void 0 : key,
name,
hintSize,
error
});
return wrapper ? h("div", wrapper, ph) : ph;
}
const props = wrapper ? {} : { key };
let unresolvedHole = false;
for (const [k, g] of propGetters) {
if (k === "component" || k === "componentFromGlobalScope" || k === "from") {
continue;
}
const v = g(vals);
if (v === void 0) unresolvedHole = true;
if (k === "dcProps") {
if (v && typeof v === "object") Object.assign(props, v);
continue;
}
props[k] = v;
}
if (unresolvedHole && ctx?.__htmlStreamingNow) {
const ph = host.placeholder({
key: wrapper ? void 0 : key,
name,
hintSize,
error: null
});
return wrapper ? h("div", wrapper, ph) : ph;
}
if (kids.length) props.children = kids.map((b, j) => b(vals, ctx, j));
return wrapper ? h("div", wrapper, h(C, props)) : h(C, props);
};
}
function contentKey(el) {
const clone = el.cloneNode(true);
for (const d of clone.querySelectorAll("*")) {
while (d.attributes.length) d.removeAttribute(d.attributes[0].name);
}
const s = clone.innerHTML;
let h2 = 5381;
for (let i = 0; i < s.length; i++) h2 = (h2 << 5) + h2 + s.charCodeAt(i) | 0;
return s.length + "." + (h2 >>> 0).toString(36);
}
var NEVER_CONTENT_KEYED = new Set(
"script style textarea option title select canvas iframe video audio".split(
" "
)
);
var NOT_INLINE_SELECTOR = ":not(" + [...INLINE_TEXT_TAGS].join(",") + ")";
function walkElement(el, host) {
const realTag = RAW_UNWRAP[el.localName] || el.localName;
const tplId = el.getAttribute("data-dc-tpl");
const inlineOnly = el.childNodes.length > 0 && !NEVER_CONTENT_KEYED.has(realTag) && el.querySelector(NOT_INLINE_SELECTOR) === null;
const keySuffix = inlineOnly ? "|" + contentKey(el) : "";
const { propGetters, pseudoClasses } = collectProps(el, "dom", host);
const kids = walkChildren(el, host);
return (vals, ctx, key) => {
const props = {
key: key + keySuffix,
"data-dc-tpl": tplId
};
for (const [k, g] of propGetters) {
let v = g(vals);
if (k === "style" && typeof v === "string") v = cssToObj(v);
if ((k === "value" || k === "checked") && v === void 0) {
v = k === "checked" ? false : "";
}
props[k] = v;
}
if (pseudoClasses.length) {
props.className = [props.className, ...pseudoClasses].filter(Boolean).join(" ");
}
return h(realTag, props, ...kids.map((b, j) => b(vals, ctx, j)));
};
}
// src/logic.ts
var StreamableLogic = class {
constructor(props) {
__publicField(this, "props");
__publicField(this, "state", {});
/** Back-pointer to the wrapper component, installed after construction. */
__publicField(this, "__host");
this.props = props || {};
}
setState(update, cb) {
this.__host && this.__host.__setLogicState(update, cb);
}
forceUpdate() {
this.__host && this.__host.forceUpdate();
}
componentDidMount() {
}
componentDidUpdate(_prevProps) {
}
componentWillUnmount() {
}
/** The flat object the template renders against (merged over props). */
renderVals() {
return {};
}
};
function evalDcLogic(src) {
//! nosemgrep: eval-and-function-constructor
const fn = new Function(
"DCLogic",
"StreamableLogic",
"React",
src + '\n;return (typeof Component!=="undefined"&&Component)||undefined;'
);
return fn(StreamableLogic, StreamableLogic, getReact());
}
// src/component.ts
function shallowEqual(a, b) {
if (!b) return false;
const ak = Object.keys(a).filter((k) => k !== "children");
const bk = Object.keys(b).filter((k) => k !== "children");
if (ak.length !== bk.length) return false;
for (const k of ak) if (a[k] !== b[k]) return false;
return true;
}
function Placeholder({
name,
hintSize,
streaming,
error
}) {
const [w, hgt] = (hintSize || "100%,60px").split(",");
return h(
"div",
{
className: "sc-placeholder" + (streaming ? " sc-streaming" : ""),
style: { width: w.trim(), height: hgt && hgt.trim() },
title: name
},
error ? h(
"div",
{ className: "sc-placeholder-error" },
(name ? name + ": " : "") + error
) : null
);
}
function hintToMin(hint) {
if (!hint) return void 0;
const [w, hgt] = hint.split(",");
return { minWidth: w.trim(), minHeight: hgt && hgt.trim() };
}
function createComponentFactory(registry, ensureFetched) {
const React = getReact();
const AncestorContext = React.createContext([]);
class StreamableComponent extends React.Component {
constructor(props) {
super(props);
__publicField(this, "__name");
__publicField(this, "__sub");
__publicField(this, "__needsDidMount", false);
/** Snapshot of the registry's streaming flags taken at render time —
* builders read it off the RenderCtx (this) to pick placeholder vs
* render-nothing for unresolved values. */
__publicField(this, "__streamingNow", false);
__publicField(this, "__htmlStreamingNow", false);
/** When a construct throws, remember the (class, registry.ver, props)
* triple so render-time reconcile doesn't re-attempt it on every parent
* re-render. A registry bump (new class, template, external module
* resolving via bumpAll) changes `ver` and breaks the memo so an
* env-dependent constructor can self-heal. */
__publicField(this, "__failedLogic", null);
__publicField(this, "__failedUserProps", null);
__publicField(this, "__failedVer", -1);
/** Per-instance constructor error — kept here (not on the registry entry)
* so one instance's successful construct can't hide a sibling's failure,
* and a construct can never wipe an eval error `updateJs` recorded on
* `r.logicError`. */
__publicField(this, "__ctorError", null);
__publicField(this, "logic");
this.__name = props.__name;
this.state = { __v: 0, __err: null };
this.__sub = () => {
if (this.state.__err) this.setState({ __err: null });
this.forceUpdate();
};
this.__makeLogic(registry.get(this.__name).Logic, null);
ensureFetched(this.__name);
}
/** Error-boundary hook: a render crash anywhere in this DC's subtree
* (its own template, an x-import'd component, a child DC without its
* own deeper boundary) lands here instead of unmounting the page. */
static getDerivedStateFromError(e) {
return { __err: e instanceof Error && e.message ? e.message : String(e) };
}
componentDidCatch(e, info) {
console.error(
"[dc-runtime] render error in <" + this.__name + ">:",
e,
info?.componentStack || ""
);
}
/** Instantiate the logic class (or the no-op base) and adopt `prevState`
* over its initial state — used both at mount and on hot-swap. */
__makeLogic(Logic, prevState) {
const L = Logic || StreamableLogic;
try {
this.logic = new L(this.__userProps());
this.__failedLogic = null;
this.__failedUserProps = null;
this.__ctorError = null;
} catch (e) {
console.error(e);
this.__failedLogic = Logic;
this.__failedUserProps = this.__userProps();
this.__failedVer = registry.get(this.__name).ver;
this.__ctorError = this.__name + ": " + (e instanceof Error && e.message ? e.message : String(e));
this.logic = new StreamableLogic(
this.__userProps()
);
}
this.logic.__host = this;
if (prevState)
this.logic.state = { ...this.logic.state || {}, ...prevState };
}
/** The props the author's logic + template see — internal __-prefixed
* wiring stripped. */
__userProps() {
const { __name, __hintSize, __tplId, __hostStyle, ...rest } = this.props;
return rest;
}
__setLogicState(update, cb) {
const prev = this.logic.state;
const patch = typeof update === "function" ? update(prev) : update;
this.logic.state = { ...prev, ...patch };
this.setState((s) => ({ __v: s.__v + 1 }), cb);
}
/** Swap the logic instance when the registry's Logic class changed
* (streaming completion, hot reload). State carries over; didMount
* re-fires after the swap commits so refs exist. */
__reconcileLogic() {
const r = registry.get(this.__name);
const Next = r.Logic;
const Cur = this.logic.constructor;
if (Next === Cur || !Next && Cur === StreamableLogic || Next === this.__failedLogic && r.ver === this.__failedVer && shallowEqual(this.__userProps(), this.__failedUserProps)) {
return;
}
if (!this.__needsDidMount) {
try {
this.logic.componentWillUnmount();
} catch (e) {
console.error(e);
}
}
this.__makeLogic(Next, this.logic.state);
this.__needsDidMount = true;
}
componentDidMount() {
registry.get(this.__name).subs.add(this.__sub);
try {
this.logic.componentDidMount();
} catch (e) {
console.error(e);
}
}
componentDidUpdate(prevProps) {
this.logic.props = this.__userProps();
if (this.__needsDidMount) {
if (this.state.__err || !registry.get(this.__name).tpl) return;
this.__needsDidMount = false;
try {
this.logic.componentDidMount();
} catch (e) {
console.error(e);
}
} else {
try {
this.logic.componentDidUpdate(prevProps);
} catch (e) {
console.error(e);
}
}
}
componentWillUnmount() {
registry.get(this.__name).subs.delete(this.__sub);
if (!this.__needsDidMount) {
try {
this.logic.componentWillUnmount();
} catch (e) {
console.error(e);
}
}
}
render() {
const r = registry.get(this.__name);
const cls = "sc-host" + (r.htmlStreaming ? " sc-streaming-html" : "") + (r.jsStreaming ? " sc-streaming-js" : "");
const hintStyle = r.htmlStreaming ? hintToMin(this.props.__hintSize) : void 0;
const hostStyle = this.props.__hostStyle || hintStyle ? { ...hintStyle || {}, ...this.props.__hostStyle || {} } : void 0;
const hostBase = {
className: cls,
style: hostStyle,
"data-sc-name": this.__name,
"data-dc-tpl": this.props.__tplId
};
const chain = Array.isArray(this.context) ? this.context : [];
if (chain.includes(this.__name)) {
const cycle = [
...chain.slice(chain.indexOf(this.__name)),
this.__name
].join(" \u2192 ");
return h(
"div",
{ ...hostBase, className: cls + " sc-has-error" },
h(Placeholder, {
name: this.__name,
hintSize: this.props.__hintSize,
error: "circular import: " + cycle
})
);
}
if (this.state.__err) {
return h(
"div",
{ ...hostBase, className: cls + " sc-has-error" },
h(
"div",
{ className: "sc-logic-error", "data-omelette-chrome": "" },
this.__name + ": " + this.state.__err
),
h(Placeholder, {
name: this.__name,
hintSize: this.props.__hintSize,
error: this.state.__err
})
);
}
this.__reconcileLogic();
if (!r.tpl) {
return h(
"div",
hostBase,
h(Placeholder, { name: this.__name, hintSize: this.props.__hintSize })
);
}
const userProps = this.__userProps();
this.logic.props = userProps;
let vals = userProps;
let renderErr = r.logicError || this.__ctorError;
try {
vals = { ...userProps, ...this.logic.renderVals() || {} };
} catch (e) {
console.error(e);
renderErr = this.__name + ".renderVals(): " + (e instanceof Error && e.message ? e.message : String(e));
}
this.__streamingNow = !!(r.htmlStreaming || r.jsStreaming);
this.__htmlStreamingNow = !!r.htmlStreaming;
return h(
"div",
{ ...hostBase, className: cls + (renderErr ? " sc-has-error" : "") },
renderErr && h(
"div",
{ className: "sc-logic-error", "data-omelette-chrome": "" },
renderErr
),
h(
AncestorContext.Provider,