@designos/compiler-cli 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +68 -2
- package/dist/cli.js +1554 -0
- package/dist/cli.js.map +1 -0
- package/package.json +38 -3
package/dist/cli.js
ADDED
|
@@ -0,0 +1,1554 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/run.ts
|
|
4
|
+
import { copyFile, lstat, mkdir, readFile, realpath, rename, rm, stat, writeFile } from "fs/promises";
|
|
5
|
+
import { randomUUID } from "crypto";
|
|
6
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from "path";
|
|
7
|
+
|
|
8
|
+
// ../compiler-core/dist/index.js
|
|
9
|
+
import {
|
|
10
|
+
componentToAlpine,
|
|
11
|
+
componentToBuilder,
|
|
12
|
+
componentToAngular,
|
|
13
|
+
componentToCustomElement,
|
|
14
|
+
componentToHtml,
|
|
15
|
+
componentToLiquid,
|
|
16
|
+
componentToLit,
|
|
17
|
+
componentToMarko,
|
|
18
|
+
componentToMitosis,
|
|
19
|
+
componentToPreact,
|
|
20
|
+
componentToQwik,
|
|
21
|
+
componentToReact,
|
|
22
|
+
componentToReactNative,
|
|
23
|
+
componentToRsc,
|
|
24
|
+
componentToSolid,
|
|
25
|
+
componentToStencil,
|
|
26
|
+
componentToSvelte,
|
|
27
|
+
componentToSwift,
|
|
28
|
+
componentToTaro,
|
|
29
|
+
componentToTemplate,
|
|
30
|
+
componentToVue
|
|
31
|
+
} from "@builder.io/mitosis";
|
|
32
|
+
import { parseJsx } from "@builder.io/mitosis";
|
|
33
|
+
var mitosisTargets = [
|
|
34
|
+
"alpine",
|
|
35
|
+
"angular",
|
|
36
|
+
"builder",
|
|
37
|
+
"customElement",
|
|
38
|
+
"html",
|
|
39
|
+
"liquid",
|
|
40
|
+
"lit",
|
|
41
|
+
"marko",
|
|
42
|
+
"mitosis",
|
|
43
|
+
"preact",
|
|
44
|
+
"qwik",
|
|
45
|
+
"react",
|
|
46
|
+
"reactNative",
|
|
47
|
+
"rsc",
|
|
48
|
+
"solid",
|
|
49
|
+
"stencil",
|
|
50
|
+
"svelte",
|
|
51
|
+
"swift",
|
|
52
|
+
"taro",
|
|
53
|
+
"template",
|
|
54
|
+
"vue",
|
|
55
|
+
"webcomponent"
|
|
56
|
+
];
|
|
57
|
+
var mitosisTargetCapabilities = Object.freeze(
|
|
58
|
+
Object.fromEntries(mitosisTargets.map((target) => [target, Object.freeze({
|
|
59
|
+
generation: "smoke-tested",
|
|
60
|
+
semanticParity: "unverified",
|
|
61
|
+
sourceMaps: "unverified",
|
|
62
|
+
diagnostics: "partial"
|
|
63
|
+
})]))
|
|
64
|
+
);
|
|
65
|
+
var propTypeTargets = /* @__PURE__ */ new Set(["preact", "qwik", "react", "reactNative", "rsc", "solid", "taro"]);
|
|
66
|
+
var stateTypeTargets = /* @__PURE__ */ new Set(["angular", "preact", "react", "reactNative", "rsc", "taro"]);
|
|
67
|
+
function createComponentPropType(component) {
|
|
68
|
+
if (!component.props.some((prop) => typeof prop.type === "string" && prop.type.trim())) return void 0;
|
|
69
|
+
const importedNames = new Set(component.imports.flatMap((item) => item.names));
|
|
70
|
+
const componentName = component.name.replace(/[^A-Za-z0-9_$]/g, "_");
|
|
71
|
+
let name = `__DesignOS_${componentName}_Props`;
|
|
72
|
+
while (importedNames.has(name)) name = `_${name}`;
|
|
73
|
+
const properties = component.props.map((prop) => {
|
|
74
|
+
const propertyName = /^[$A-Z_a-z][$\w]*$/.test(prop.name) ? prop.name : JSON.stringify(prop.name);
|
|
75
|
+
const optional = prop.optional || prop.defaultValue !== void 0 ? "?" : "";
|
|
76
|
+
const type = typeof prop.type === "string" && prop.type.trim() ? prop.type.trim() : "any";
|
|
77
|
+
return ` ${propertyName}${optional}: ${type};`;
|
|
78
|
+
});
|
|
79
|
+
return { name, declaration: `type ${name} = {
|
|
80
|
+
${properties.join("\n")}
|
|
81
|
+
};` };
|
|
82
|
+
}
|
|
83
|
+
function toMitosisNode(node) {
|
|
84
|
+
const base = { "@type": "@builder.io/mitosis/node", name: "div", meta: {}, scope: {}, properties: {}, bindings: {}, children: [] };
|
|
85
|
+
if (node.kind === "text") {
|
|
86
|
+
base.properties._text = node.value;
|
|
87
|
+
} else if (node.kind === "expression") {
|
|
88
|
+
base.bindings._text = { code: node.binding.code, type: "single", bindingType: "expression" };
|
|
89
|
+
} else if (node.kind === "slot") {
|
|
90
|
+
base.name = "Slot";
|
|
91
|
+
if (node.name) base.properties.name = node.name;
|
|
92
|
+
if (node.fallback) base.children = node.fallback.map((child) => toMitosisNode(child));
|
|
93
|
+
} else if (node.kind === "fragment") {
|
|
94
|
+
base.name = "Fragment";
|
|
95
|
+
base.children = node.children.map((child) => toMitosisNode(child));
|
|
96
|
+
} else if (node.kind === "conditional") {
|
|
97
|
+
base.name = "Show";
|
|
98
|
+
base.bindings.when = { code: node.condition.code, type: "single", bindingType: "expression" };
|
|
99
|
+
base.children = node.then.map((child) => toMitosisNode(child));
|
|
100
|
+
if (node.otherwise?.length) {
|
|
101
|
+
base.meta.else = toMitosisNode({ kind: "fragment", children: node.otherwise });
|
|
102
|
+
}
|
|
103
|
+
} else if (node.kind === "loop") {
|
|
104
|
+
base.name = "For";
|
|
105
|
+
base.scope = { forName: node.itemName, indexName: node.indexName, collectionName: void 0 };
|
|
106
|
+
base.bindings.each = { code: node.collection.code, type: "single", bindingType: "expression" };
|
|
107
|
+
base.children = node.children.map((child) => toMitosisNode(child));
|
|
108
|
+
} else {
|
|
109
|
+
base.name = node.kind === "element" ? node.tag : node.name;
|
|
110
|
+
base.children = (node.children ?? []).map((child) => toMitosisNode(child));
|
|
111
|
+
for (const attribute of node.attributes ?? []) applyAttribute(base, attribute);
|
|
112
|
+
if (node.kind === "component" && node.slots) {
|
|
113
|
+
const { default: defaultSlot, ...namedSlots } = node.slots;
|
|
114
|
+
if (defaultSlot) base.children.push(...defaultSlot.map((child) => toMitosisNode(child)));
|
|
115
|
+
if (Object.keys(namedSlots).length) {
|
|
116
|
+
base.slots = Object.fromEntries(Object.entries(namedSlots).map(([name, children]) => [name, toMitosisSlotChildren(children)]));
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return base;
|
|
121
|
+
}
|
|
122
|
+
function toMitosisSlotChildren(children) {
|
|
123
|
+
const nodes = children.length === 1 && children[0].kind === "fragment" ? children[0].children : children;
|
|
124
|
+
if (nodes.length === 1 && nodes[0].kind === "text") {
|
|
125
|
+
const child = nodes[0];
|
|
126
|
+
const node = toMitosisNode(child);
|
|
127
|
+
node.properties._text = JSON.stringify(child.value);
|
|
128
|
+
return [node];
|
|
129
|
+
}
|
|
130
|
+
return nodes.map((child) => toMitosisNode(child));
|
|
131
|
+
}
|
|
132
|
+
function applyAttribute(node, attribute) {
|
|
133
|
+
if (!attribute.binding) {
|
|
134
|
+
if (attribute.value !== void 0) node.properties[attribute.name] = attribute.value;
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
const binding = attribute.binding;
|
|
138
|
+
const eventName = binding.eventName ?? attribute.name;
|
|
139
|
+
const key = binding.kind === "event" && !eventName.startsWith("on") ? `on${eventName.charAt(0).toUpperCase()}${eventName.slice(1)}` : attribute.name;
|
|
140
|
+
node.bindings[key] = {
|
|
141
|
+
code: binding.code,
|
|
142
|
+
type: binding.kind === "spread" ? "spread" : "single",
|
|
143
|
+
...binding.kind === "spread" ? { spreadType: "normal" } : { bindingType: binding.kind === "event" ? "function" : "expression" },
|
|
144
|
+
...binding.parameters ? { arguments: binding.parameters } : {}
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
function componentIRToMitosis(component) {
|
|
148
|
+
const imports = component.imports.map((item) => ({
|
|
149
|
+
path: item.source,
|
|
150
|
+
imports: Object.fromEntries(item.names.map((name) => [name, name])),
|
|
151
|
+
...item.typeOnly ? { importKind: "type" } : {}
|
|
152
|
+
}));
|
|
153
|
+
const propType = createComponentPropType(component);
|
|
154
|
+
return {
|
|
155
|
+
"@type": "@builder.io/mitosis/component",
|
|
156
|
+
name: component.name,
|
|
157
|
+
imports,
|
|
158
|
+
exports: {},
|
|
159
|
+
inputs: component.props.map((prop) => ({ name: prop.name, defaultValue: prop.defaultValue })),
|
|
160
|
+
props: Object.fromEntries(component.props.map((prop) => [prop.name, { propertyType: "normal", optional: !!prop.optional || prop.defaultValue !== void 0 }])),
|
|
161
|
+
defaultProps: Object.fromEntries(component.props.filter((prop) => prop.defaultValue !== void 0).map((prop) => [prop.name, { type: "property", code: JSON.stringify(prop.defaultValue) }])),
|
|
162
|
+
state: Object.fromEntries(component.state.map((item) => [item.name, {
|
|
163
|
+
type: "property",
|
|
164
|
+
code: item.initialValue,
|
|
165
|
+
...typeof item.type === "string" && item.type.trim() ? { typeParameter: item.type.trim() } : {}
|
|
166
|
+
}])),
|
|
167
|
+
meta: { ...component.metadata ?? {} },
|
|
168
|
+
refs: {},
|
|
169
|
+
context: { get: {}, set: {} },
|
|
170
|
+
hooks: { onMount: [], onEvent: [] },
|
|
171
|
+
children: component.root.kind === "fragment" ? component.root.children.map((node) => toMitosisNode(node)) : [toMitosisNode(component.root)],
|
|
172
|
+
subComponents: [],
|
|
173
|
+
...component.styles ? { style: component.styles } : {},
|
|
174
|
+
...propType ? { types: [propType.declaration], propsTypeRef: propType.name } : {}
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
function normalizeReactNativeFragmentLinks(component) {
|
|
178
|
+
const visit = (node) => {
|
|
179
|
+
const href = node.properties?.href;
|
|
180
|
+
if (typeof href === "string" && href.startsWith("#")) {
|
|
181
|
+
delete node.properties.href;
|
|
182
|
+
node.bindings ??= {};
|
|
183
|
+
node.bindings.href = {
|
|
184
|
+
code: JSON.stringify(href),
|
|
185
|
+
type: "single",
|
|
186
|
+
bindingType: "expression"
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
if (Array.isArray(node.children)) node.children.forEach(visit);
|
|
190
|
+
if (node.slots && typeof node.slots === "object") {
|
|
191
|
+
for (const children of Object.values(node.slots)) children.forEach(visit);
|
|
192
|
+
}
|
|
193
|
+
};
|
|
194
|
+
if (Array.isArray(component.children)) component.children.forEach(visit);
|
|
195
|
+
}
|
|
196
|
+
var generators = {
|
|
197
|
+
alpine: (c, o) => componentToAlpine(o)({ component: c }),
|
|
198
|
+
builder: (c, o) => componentToBuilder(o)({ component: c }),
|
|
199
|
+
angular: (c, o) => componentToAngular(o)({ component: c }),
|
|
200
|
+
customElement: (c, o) => componentToCustomElement(o)({ component: c }),
|
|
201
|
+
html: (c, o) => componentToHtml(o)({ component: c }),
|
|
202
|
+
liquid: (c, o) => componentToLiquid(o)({ component: c }),
|
|
203
|
+
lit: (c, o) => componentToLit(o)({ component: c }),
|
|
204
|
+
marko: (c, o) => componentToMarko(o)({ component: c }),
|
|
205
|
+
mitosis: (c, o) => componentToMitosis(o)({ component: c }),
|
|
206
|
+
preact: (c, o) => componentToPreact(o)({ component: c }),
|
|
207
|
+
qwik: (c, o) => componentToQwik(o)({ component: c }),
|
|
208
|
+
react: (c, o) => componentToReact(o)({ component: c }),
|
|
209
|
+
reactNative: (c, o) => componentToReactNative(o)({ component: c }),
|
|
210
|
+
rsc: (c, o) => componentToRsc(o)({ component: c }),
|
|
211
|
+
solid: (c, o) => componentToSolid(o)({ component: c }),
|
|
212
|
+
stencil: (c, o) => componentToStencil(o)({ component: c }),
|
|
213
|
+
svelte: (c, o) => componentToSvelte(o)({ component: c }),
|
|
214
|
+
swift: (c, o) => componentToSwift(o)({ component: c }),
|
|
215
|
+
taro: (c, o) => componentToTaro(o)({ component: c }),
|
|
216
|
+
template: (c, o) => componentToTemplate(o)({ component: c }),
|
|
217
|
+
vue: (c, o) => componentToVue(o)({ component: c }),
|
|
218
|
+
webcomponent: (c, o) => componentToCustomElement(o)({ component: c })
|
|
219
|
+
};
|
|
220
|
+
var siblingElseTargets = /* @__PURE__ */ new Set(["alpine", "customElement", "html", "swift", "template", "webcomponent"]);
|
|
221
|
+
var nativeSlotProjectionTargets = /* @__PURE__ */ new Set([
|
|
222
|
+
"alpine",
|
|
223
|
+
"angular",
|
|
224
|
+
"customElement",
|
|
225
|
+
"html",
|
|
226
|
+
"liquid",
|
|
227
|
+
"lit",
|
|
228
|
+
"marko",
|
|
229
|
+
"qwik",
|
|
230
|
+
"stencil",
|
|
231
|
+
"svelte",
|
|
232
|
+
"template",
|
|
233
|
+
"vue",
|
|
234
|
+
"webcomponent"
|
|
235
|
+
]);
|
|
236
|
+
var nativeSlotOutletTargets = /* @__PURE__ */ new Set(["alpine", "customElement", "html", "liquid", "lit", "stencil", "template", "webcomponent"]);
|
|
237
|
+
var eventlessTargets = /* @__PURE__ */ new Set(["liquid", "template"]);
|
|
238
|
+
var nativePropDefaultTargets = /* @__PURE__ */ new Set(["angular", "preact", "react", "reactNative", "rsc", "stencil", "svelte", "taro", "vue"]);
|
|
239
|
+
var expressionPropDefaultTargets = /* @__PURE__ */ new Set(["alpine", "builder", "customElement", "html", "lit", "marko", "mitosis", "solid", "template", "webcomponent"]);
|
|
240
|
+
var swiftTextTags = /* @__PURE__ */ new Set(["span", "p", "h1", "h2", "h3", "h4", "h5", "h6"]);
|
|
241
|
+
function swiftPrimitiveType(type) {
|
|
242
|
+
if (typeof type !== "string") return void 0;
|
|
243
|
+
switch (type.trim().toLowerCase()) {
|
|
244
|
+
case "string":
|
|
245
|
+
return "string";
|
|
246
|
+
case "number":
|
|
247
|
+
return "number";
|
|
248
|
+
case "boolean":
|
|
249
|
+
case "bool":
|
|
250
|
+
return "boolean";
|
|
251
|
+
default:
|
|
252
|
+
return void 0;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
function swiftDefaultLiteral(type, value) {
|
|
256
|
+
const normalizedType = swiftPrimitiveType(type);
|
|
257
|
+
if (normalizedType === "string" && typeof value === "string") {
|
|
258
|
+
if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/.test(value)) return void 0;
|
|
259
|
+
const escaped = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
|
|
260
|
+
return `"${escaped}"`;
|
|
261
|
+
}
|
|
262
|
+
if (normalizedType === "number" && typeof value === "number" && Number.isFinite(value)) return String(value);
|
|
263
|
+
if (normalizedType === "boolean" && typeof value === "boolean") return String(value);
|
|
264
|
+
return void 0;
|
|
265
|
+
}
|
|
266
|
+
function applySwiftPropTypes(component, props) {
|
|
267
|
+
for (const prop of props) {
|
|
268
|
+
const type = swiftPrimitiveType(prop.type);
|
|
269
|
+
if (type && component.props?.[prop.name]) component.props[prop.name].propertyType = type;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
function hasNamedComponentSlots(node) {
|
|
273
|
+
if (node.kind === "component" && Object.keys(node.slots ?? {}).some((name) => name !== "default")) return true;
|
|
274
|
+
if (node.kind === "conditional") return node.then.some(hasNamedComponentSlots) || (node.otherwise ?? []).some(hasNamedComponentSlots);
|
|
275
|
+
if (node.kind === "loop" || node.kind === "fragment") return node.children.some(hasNamedComponentSlots);
|
|
276
|
+
if (node.kind === "slot") return (node.fallback ?? []).some(hasNamedComponentSlots);
|
|
277
|
+
if (node.kind === "element") return (node.children ?? []).some(hasNamedComponentSlots);
|
|
278
|
+
if (node.kind === "component") return (node.children ?? []).some(hasNamedComponentSlots) || Object.values(node.slots ?? {}).some((children) => children.some(hasNamedComponentSlots));
|
|
279
|
+
return false;
|
|
280
|
+
}
|
|
281
|
+
function hasUnsupportedNamedComponentSlots(node, target) {
|
|
282
|
+
if (target === "swift") return hasNamedComponentSlots(node);
|
|
283
|
+
if (target === "solid" && node.kind === "component") {
|
|
284
|
+
const hasUnsupportedSlot = Object.entries(node.slots ?? {}).some(([name, children]) => {
|
|
285
|
+
if (name === "default") return false;
|
|
286
|
+
return children.length !== 1 || children[0]?.kind !== "text" && children[0]?.kind !== "expression";
|
|
287
|
+
});
|
|
288
|
+
if (hasUnsupportedSlot) return true;
|
|
289
|
+
}
|
|
290
|
+
if (node.kind === "conditional") return node.then.some((child) => hasUnsupportedNamedComponentSlots(child, target)) || (node.otherwise ?? []).some((child) => hasUnsupportedNamedComponentSlots(child, target));
|
|
291
|
+
if (node.kind === "loop" || node.kind === "fragment") return node.children.some((child) => hasUnsupportedNamedComponentSlots(child, target));
|
|
292
|
+
if (node.kind === "slot") return (node.fallback ?? []).some((child) => hasUnsupportedNamedComponentSlots(child, target));
|
|
293
|
+
if (node.kind === "element") return (node.children ?? []).some((child) => hasUnsupportedNamedComponentSlots(child, target));
|
|
294
|
+
if (node.kind === "component") return (node.children ?? []).some((child) => hasUnsupportedNamedComponentSlots(child, target)) || Object.values(node.slots ?? {}).some((children) => children.some((child) => hasUnsupportedNamedComponentSlots(child, target)));
|
|
295
|
+
return false;
|
|
296
|
+
}
|
|
297
|
+
function hasUnsupportedNamedSlotOutlet(node, target) {
|
|
298
|
+
if (target === "swift" && node.kind === "slot") return true;
|
|
299
|
+
if (node.kind === "conditional") return node.then.some((child) => hasUnsupportedNamedSlotOutlet(child, target)) || (node.otherwise ?? []).some((child) => hasUnsupportedNamedSlotOutlet(child, target));
|
|
300
|
+
if (node.kind === "loop" || node.kind === "fragment") return node.children.some((child) => hasUnsupportedNamedSlotOutlet(child, target));
|
|
301
|
+
if (node.kind === "slot") return (node.fallback ?? []).some((child) => hasUnsupportedNamedSlotOutlet(child, target));
|
|
302
|
+
if (node.kind === "element") return (node.children ?? []).some((child) => hasUnsupportedNamedSlotOutlet(child, target));
|
|
303
|
+
if (node.kind === "component") return (node.children ?? []).some((child) => hasUnsupportedNamedSlotOutlet(child, target)) || Object.values(node.slots ?? {}).some((children) => children.some((child) => hasUnsupportedNamedSlotOutlet(child, target)));
|
|
304
|
+
return false;
|
|
305
|
+
}
|
|
306
|
+
function hasEventHandlers(node) {
|
|
307
|
+
if ((node.kind === "element" || node.kind === "component") && (node.attributes ?? []).some((attribute) => attribute.binding?.kind === "event")) return true;
|
|
308
|
+
if (node.kind === "conditional") return node.then.some(hasEventHandlers) || (node.otherwise ?? []).some(hasEventHandlers);
|
|
309
|
+
if (node.kind === "loop" || node.kind === "fragment") return node.children.some(hasEventHandlers);
|
|
310
|
+
if (node.kind === "slot") return (node.fallback ?? []).some(hasEventHandlers);
|
|
311
|
+
if (node.kind === "element") return (node.children ?? []).some(hasEventHandlers);
|
|
312
|
+
if (node.kind === "component") return (node.children ?? []).some(hasEventHandlers) || Object.values(node.slots ?? {}).some((children) => children.some(hasEventHandlers));
|
|
313
|
+
return false;
|
|
314
|
+
}
|
|
315
|
+
function preservesPropDefault(target, name, value, propType) {
|
|
316
|
+
if (nativePropDefaultTargets.has(target)) return true;
|
|
317
|
+
if (target === "qwik") return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) && serializeDefaultValue(value) !== void 0;
|
|
318
|
+
if (target === "swift") return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) && swiftDefaultLiteral(propType, value) !== void 0;
|
|
319
|
+
if (target === "liquid") {
|
|
320
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) return false;
|
|
321
|
+
return typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
|
|
322
|
+
}
|
|
323
|
+
return expressionPropDefaultTargets.has(target) && /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) && serializeDefaultValue(value) !== void 0;
|
|
324
|
+
}
|
|
325
|
+
function serializeDefaultValue(value) {
|
|
326
|
+
try {
|
|
327
|
+
const serialized = JSON.stringify(value);
|
|
328
|
+
return typeof serialized === "string" ? serialized : void 0;
|
|
329
|
+
} catch {
|
|
330
|
+
return void 0;
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
function applyExpressionPropDefaults(nodes, props) {
|
|
334
|
+
const defaults = props.flatMap((prop) => {
|
|
335
|
+
if (prop.defaultValue === void 0 || !/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(prop.name)) return [];
|
|
336
|
+
const serialized = serializeDefaultValue(prop.defaultValue);
|
|
337
|
+
return serialized === void 0 ? [] : [{ name: prop.name, serialized }];
|
|
338
|
+
});
|
|
339
|
+
if (defaults.length === 0) return;
|
|
340
|
+
const visit = (node) => {
|
|
341
|
+
for (const binding of Object.values(node.bindings ?? {})) {
|
|
342
|
+
if (typeof binding.code !== "string") continue;
|
|
343
|
+
let code = binding.code;
|
|
344
|
+
for (const { name, serialized } of defaults) {
|
|
345
|
+
const escapedName = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
346
|
+
const access = `props.${name}`;
|
|
347
|
+
const replacement = `(${access} === undefined ? ${serialized} : ${access})`;
|
|
348
|
+
const dotReference = new RegExp(`\\bprops(?:\\?\\.|\\.)${escapedName}\\b`, "g");
|
|
349
|
+
const bracketReference = new RegExp(`\\bprops\\s*\\[\\s*(['"])${escapedName}\\1\\s*\\]`, "g");
|
|
350
|
+
code = code.replace(dotReference, replacement).replace(bracketReference, replacement);
|
|
351
|
+
}
|
|
352
|
+
binding.code = code;
|
|
353
|
+
}
|
|
354
|
+
node.children?.forEach(visit);
|
|
355
|
+
if (node.slots) Object.values(node.slots).forEach((children) => children.forEach(visit));
|
|
356
|
+
const elseNode = node.meta?.else;
|
|
357
|
+
if (elseNode && typeof elseNode === "object") visit(elseNode);
|
|
358
|
+
};
|
|
359
|
+
nodes.forEach(visit);
|
|
360
|
+
}
|
|
361
|
+
function applyQwikPropDefaults(component, props) {
|
|
362
|
+
const usedNames = /* @__PURE__ */ new Set([
|
|
363
|
+
...props.map((prop) => prop.name),
|
|
364
|
+
...Object.keys(component.state ?? {})
|
|
365
|
+
]);
|
|
366
|
+
const defaults = props.flatMap((prop) => {
|
|
367
|
+
if (prop.defaultValue === void 0 || !/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(prop.name)) return [];
|
|
368
|
+
const serialized = serializeDefaultValue(prop.defaultValue);
|
|
369
|
+
if (serialized === void 0) return [];
|
|
370
|
+
let alias = `__designosDefault_${prop.name}`;
|
|
371
|
+
let suffix = 1;
|
|
372
|
+
while (usedNames.has(alias)) alias = `__designosDefault_${prop.name}_${suffix++}`;
|
|
373
|
+
usedNames.add(alias);
|
|
374
|
+
return [{ name: prop.name, alias, serialized }];
|
|
375
|
+
});
|
|
376
|
+
if (defaults.length === 0) return defaults;
|
|
377
|
+
const rewrite = (source) => defaults.reduce((code, { name, alias }) => {
|
|
378
|
+
const escapedName = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
379
|
+
const dotReference = new RegExp(`\\bprops(?:\\?\\.|\\.)${escapedName}\\b`, "g");
|
|
380
|
+
const bracketReference = new RegExp(`\\bprops\\s*\\[\\s*(['"])${escapedName}\\1\\s*\\]`, "g");
|
|
381
|
+
return code.replace(dotReference, alias).replace(bracketReference, alias);
|
|
382
|
+
}, source);
|
|
383
|
+
const visit = (node) => {
|
|
384
|
+
for (const binding of Object.values(node.bindings ?? {})) {
|
|
385
|
+
if (typeof binding.code === "string") binding.code = rewrite(binding.code);
|
|
386
|
+
}
|
|
387
|
+
node.children?.forEach(visit);
|
|
388
|
+
if (node.slots) Object.values(node.slots).forEach((children) => children.forEach(visit));
|
|
389
|
+
const elseNode = node.meta?.else;
|
|
390
|
+
if (elseNode && typeof elseNode === "object") visit(elseNode);
|
|
391
|
+
};
|
|
392
|
+
component.children.forEach(visit);
|
|
393
|
+
for (const state of Object.values(component.state ?? {})) {
|
|
394
|
+
if (typeof state.code === "string") state.code = rewrite(state.code);
|
|
395
|
+
}
|
|
396
|
+
return defaults;
|
|
397
|
+
}
|
|
398
|
+
function addQwikPropDefaults(output, defaults) {
|
|
399
|
+
if (defaults.length === 0) return output;
|
|
400
|
+
const signature = /(component\$\(\s*\(\s*props(?:\s*:\s*[^)]*)?\)\s*=>\s*\{)/;
|
|
401
|
+
if (!signature.test(output)) return void 0;
|
|
402
|
+
const declarations = defaults.map(({ name, alias, serialized }) => ` const ${alias} = props.${name} === undefined ? ${serialized} : props.${name};`).join("\n");
|
|
403
|
+
return output.replace(signature, (match) => `${match}
|
|
404
|
+
${declarations}`);
|
|
405
|
+
}
|
|
406
|
+
function applySwiftPropDefaults(nodes, props) {
|
|
407
|
+
const defaults = props.flatMap((prop) => {
|
|
408
|
+
if (prop.defaultValue === void 0 || !/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(prop.name)) return [];
|
|
409
|
+
const literal = swiftDefaultLiteral(prop.type, prop.defaultValue);
|
|
410
|
+
return literal === void 0 ? [] : [{ name: prop.name, literal }];
|
|
411
|
+
});
|
|
412
|
+
if (defaults.length === 0) return;
|
|
413
|
+
const visit = (node) => {
|
|
414
|
+
for (const binding of Object.values(node.bindings ?? {})) {
|
|
415
|
+
if (typeof binding.code !== "string") continue;
|
|
416
|
+
let code = binding.code;
|
|
417
|
+
for (const { name, literal } of defaults) {
|
|
418
|
+
const escapedName = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
419
|
+
const replacement = `(props.${name} ?? ${literal})`;
|
|
420
|
+
const dotReference = new RegExp(`\\bprops(?:\\?\\.|\\.)${escapedName}\\b`, "g");
|
|
421
|
+
const bracketReference = new RegExp(`\\bprops\\s*\\[\\s*(['"])${escapedName}\\1\\s*\\]`, "g");
|
|
422
|
+
code = code.replace(dotReference, replacement).replace(bracketReference, replacement);
|
|
423
|
+
}
|
|
424
|
+
binding.code = code;
|
|
425
|
+
}
|
|
426
|
+
node.children?.forEach(visit);
|
|
427
|
+
if (node.slots) Object.values(node.slots).forEach((children) => children.forEach(visit));
|
|
428
|
+
const elseNode = node.meta?.else;
|
|
429
|
+
if (elseNode && typeof elseNode === "object") visit(elseNode);
|
|
430
|
+
};
|
|
431
|
+
nodes.forEach(visit);
|
|
432
|
+
}
|
|
433
|
+
function addSwiftPropDefaults(output, props) {
|
|
434
|
+
for (const prop of props) {
|
|
435
|
+
if (prop.defaultValue === void 0 || !/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(prop.name)) continue;
|
|
436
|
+
const literal = swiftDefaultLiteral(prop.type, prop.defaultValue);
|
|
437
|
+
if (literal === void 0) continue;
|
|
438
|
+
const escapedName = prop.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
439
|
+
const declaration = new RegExp(`^([\\t ]*)let\\s+${escapedName}(\\s*:[^\\n]+)$`, "m");
|
|
440
|
+
output = output.replace(declaration, (_match, indent, annotation) => `${indent}var ${prop.name}${annotation} = ${literal}`);
|
|
441
|
+
}
|
|
442
|
+
return output;
|
|
443
|
+
}
|
|
444
|
+
function addLiquidPropDefaults(output, component) {
|
|
445
|
+
const assignments = component.props.flatMap((prop) => {
|
|
446
|
+
if (prop.defaultValue === void 0 || !preservesPropDefault("liquid", prop.name, prop.defaultValue, prop.type)) return [];
|
|
447
|
+
const literal = JSON.stringify(prop.defaultValue);
|
|
448
|
+
if (typeof literal !== "string") return [];
|
|
449
|
+
const allowFalse = prop.defaultValue === false ? ", allow_false: true" : "";
|
|
450
|
+
return [`{% assign ${prop.name} = ${prop.name} | default: ${literal}${allowFalse} %}`];
|
|
451
|
+
});
|
|
452
|
+
return assignments.length ? `${assignments.join("\n")}
|
|
453
|
+
${output}` : output;
|
|
454
|
+
}
|
|
455
|
+
function toLiquidCondition(code) {
|
|
456
|
+
const condition = code.replace(/\b(?:props|state)\./g, "").trim();
|
|
457
|
+
const identifier = "[A-Za-z_][A-Za-z0-9_]*(?:\\.[A-Za-z_][A-Za-z0-9_]*)*";
|
|
458
|
+
const literal = `(?:${identifier}|\\d+(?:\\.\\d+)?|'[^'\\\\]*'|"[^"\\\\]*")`;
|
|
459
|
+
if (new RegExp(`^${identifier}$`).test(condition)) return condition;
|
|
460
|
+
if (new RegExp(`^${literal}\\s*(?:==|!=|>=|<=|>|<)\\s*${literal}$`).test(condition)) return condition;
|
|
461
|
+
return void 0;
|
|
462
|
+
}
|
|
463
|
+
function hasUnsupportedLiquidElse(node) {
|
|
464
|
+
if (node.kind === "conditional") {
|
|
465
|
+
if (node.otherwise?.length && !toLiquidCondition(node.condition.code)) return true;
|
|
466
|
+
return node.then.some(hasUnsupportedLiquidElse) || (node.otherwise ?? []).some(hasUnsupportedLiquidElse);
|
|
467
|
+
}
|
|
468
|
+
if (node.kind === "loop" || node.kind === "fragment") return node.children.some(hasUnsupportedLiquidElse);
|
|
469
|
+
if (node.kind === "slot") return (node.fallback ?? []).some(hasUnsupportedLiquidElse);
|
|
470
|
+
if (node.kind === "element") return (node.children ?? []).some(hasUnsupportedLiquidElse);
|
|
471
|
+
if (node.kind === "component") return (node.children ?? []).some(hasUnsupportedLiquidElse) || Object.values(node.slots ?? {}).some((children) => children.some(hasUnsupportedLiquidElse));
|
|
472
|
+
return false;
|
|
473
|
+
}
|
|
474
|
+
function lowerElseBranches(nodes) {
|
|
475
|
+
const lowered = [];
|
|
476
|
+
for (const sourceNode of nodes) {
|
|
477
|
+
const node = {
|
|
478
|
+
...sourceNode,
|
|
479
|
+
meta: { ...sourceNode.meta ?? {} },
|
|
480
|
+
children: Array.isArray(sourceNode.children) ? lowerElseBranches(sourceNode.children) : sourceNode.children,
|
|
481
|
+
...sourceNode.slots ? {
|
|
482
|
+
slots: Object.fromEntries(Object.entries(sourceNode.slots).map(([name, children]) => [name, lowerElseBranches(children)]))
|
|
483
|
+
} : {}
|
|
484
|
+
};
|
|
485
|
+
const elseNode = node.name === "Show" ? node.meta.else : void 0;
|
|
486
|
+
const condition = node.bindings?.when?.code;
|
|
487
|
+
if (!elseNode || typeof condition !== "string" || !condition.trim()) {
|
|
488
|
+
lowered.push(node);
|
|
489
|
+
continue;
|
|
490
|
+
}
|
|
491
|
+
delete node.meta.else;
|
|
492
|
+
const elseChildren = elseNode.name === "Fragment" && Array.isArray(elseNode.children) ? elseNode.children : [elseNode];
|
|
493
|
+
const alternate = {
|
|
494
|
+
...node,
|
|
495
|
+
bindings: {
|
|
496
|
+
...node.bindings,
|
|
497
|
+
when: { ...node.bindings.when, code: `!(${condition})` }
|
|
498
|
+
},
|
|
499
|
+
children: lowerElseBranches(elseChildren)
|
|
500
|
+
};
|
|
501
|
+
lowered.push(node, alternate);
|
|
502
|
+
}
|
|
503
|
+
return lowered;
|
|
504
|
+
}
|
|
505
|
+
function lowerLiquidElseBranches(nodes, baseComponent, options) {
|
|
506
|
+
const lowered = [];
|
|
507
|
+
for (const sourceNode of nodes) {
|
|
508
|
+
const node = {
|
|
509
|
+
...sourceNode,
|
|
510
|
+
meta: { ...sourceNode.meta ?? {} },
|
|
511
|
+
children: Array.isArray(sourceNode.children) ? lowerLiquidElseBranches(sourceNode.children, baseComponent, options) : sourceNode.children,
|
|
512
|
+
...sourceNode.slots ? {
|
|
513
|
+
slots: Object.fromEntries(Object.entries(sourceNode.slots).map(([name, children]) => [name, lowerLiquidElseBranches(children, baseComponent, options)]))
|
|
514
|
+
} : {}
|
|
515
|
+
};
|
|
516
|
+
const elseNode = node.name === "Show" ? node.meta.else : void 0;
|
|
517
|
+
const condition = node.bindings?.when?.code;
|
|
518
|
+
const liquidCondition = typeof condition === "string" ? toLiquidCondition(condition) : void 0;
|
|
519
|
+
if (!elseNode || !liquidCondition) {
|
|
520
|
+
lowered.push(node);
|
|
521
|
+
continue;
|
|
522
|
+
}
|
|
523
|
+
const elseChildren = elseNode.name === "Fragment" && Array.isArray(elseNode.children) ? lowerLiquidElseBranches(elseNode.children, baseComponent, options) : lowerLiquidElseBranches([elseNode], baseComponent, options);
|
|
524
|
+
const renderNodes = (children) => generators.liquid({ ...baseComponent, children, style: "" }, { ...options, prettier: false, reactive: false });
|
|
525
|
+
lowered.push({
|
|
526
|
+
"@type": "@builder.io/mitosis/node",
|
|
527
|
+
name: "div",
|
|
528
|
+
properties: { _text: `{% if ${liquidCondition} %}${renderNodes(node.children ?? [])}{% else %}${renderNodes(elseChildren)}{% endif %}` },
|
|
529
|
+
bindings: {},
|
|
530
|
+
meta: {},
|
|
531
|
+
scope: {},
|
|
532
|
+
children: []
|
|
533
|
+
});
|
|
534
|
+
}
|
|
535
|
+
return lowered;
|
|
536
|
+
}
|
|
537
|
+
function normalizeSwiftShowBranches(nodes) {
|
|
538
|
+
return nodes.map((sourceNode) => {
|
|
539
|
+
const node = {
|
|
540
|
+
...sourceNode,
|
|
541
|
+
meta: { ...sourceNode.meta ?? {} },
|
|
542
|
+
children: Array.isArray(sourceNode.children) ? normalizeSwiftShowBranches(sourceNode.children) : sourceNode.children,
|
|
543
|
+
...sourceNode.slots ? {
|
|
544
|
+
slots: Object.fromEntries(Object.entries(sourceNode.slots).map(([name, children]) => [name, normalizeSwiftShowBranches(children)]))
|
|
545
|
+
} : {}
|
|
546
|
+
};
|
|
547
|
+
if (node.name === "Show" && node.bindings?.when) {
|
|
548
|
+
node.name = "Group";
|
|
549
|
+
node.bindings.if = node.bindings.when;
|
|
550
|
+
delete node.bindings.when;
|
|
551
|
+
}
|
|
552
|
+
if (typeof node.bindings?._text?.code === "string") {
|
|
553
|
+
node.name = "Text";
|
|
554
|
+
node.bindings.innerHTML = node.bindings._text;
|
|
555
|
+
delete node.bindings._text;
|
|
556
|
+
}
|
|
557
|
+
if (swiftTextTags.has(String(node.name).toLowerCase()) && node.children?.length) {
|
|
558
|
+
if (node.children.length === 1) {
|
|
559
|
+
const child = node.children[0];
|
|
560
|
+
const textBinding = child.bindings?.innerHTML ?? child.bindings?._text;
|
|
561
|
+
if (typeof textBinding?.code === "string") {
|
|
562
|
+
node.name = "Text";
|
|
563
|
+
node.bindings = { ...node.bindings ?? {}, innerHTML: textBinding };
|
|
564
|
+
node.children = [];
|
|
565
|
+
} else if (typeof child.properties?._text === "string") {
|
|
566
|
+
node.name = "Text";
|
|
567
|
+
node.properties = { ...node.properties ?? {}, _text: child.properties._text };
|
|
568
|
+
node.children = [];
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
if (node.children?.length) node.name = "div";
|
|
572
|
+
}
|
|
573
|
+
return node;
|
|
574
|
+
});
|
|
575
|
+
}
|
|
576
|
+
function decodeSlotText(node) {
|
|
577
|
+
const encoded = node.properties?._text;
|
|
578
|
+
if (typeof encoded === "string") {
|
|
579
|
+
try {
|
|
580
|
+
const decoded = JSON.parse(encoded);
|
|
581
|
+
if (typeof decoded === "string" && JSON.stringify(decoded) === encoded) node.properties._text = decoded;
|
|
582
|
+
} catch {
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
return node;
|
|
586
|
+
}
|
|
587
|
+
function isMitosisTextNode(node) {
|
|
588
|
+
return Object.hasOwn(node.properties ?? {}, "_text") || Object.hasOwn(node.bindings ?? {}, "_text");
|
|
589
|
+
}
|
|
590
|
+
function lowerNamedComponentSlots(nodes, target) {
|
|
591
|
+
const result = [];
|
|
592
|
+
for (const sourceNode of nodes) {
|
|
593
|
+
const node = {
|
|
594
|
+
...sourceNode,
|
|
595
|
+
properties: { ...sourceNode.properties ?? {} },
|
|
596
|
+
bindings: { ...sourceNode.bindings ?? {} },
|
|
597
|
+
children: Array.isArray(sourceNode.children) ? lowerNamedComponentSlots(sourceNode.children, target) : sourceNode.children,
|
|
598
|
+
...sourceNode.slots ? {
|
|
599
|
+
slots: Object.fromEntries(Object.entries(sourceNode.slots).map(([name, children]) => [name, lowerNamedComponentSlots(children, target)]))
|
|
600
|
+
} : {}
|
|
601
|
+
};
|
|
602
|
+
if (target === "builder" && node.slots) {
|
|
603
|
+
for (const slotChildren of Object.values(node.slots)) slotChildren.forEach(decodeSlotText);
|
|
604
|
+
} else if (target === "solid" && node.slots) {
|
|
605
|
+
for (const [slotName, slotChildren] of Object.entries(node.slots)) {
|
|
606
|
+
if (slotChildren.length !== 1) continue;
|
|
607
|
+
const slotChild = decodeSlotText(slotChildren[0]);
|
|
608
|
+
if (Object.hasOwn(slotChild.bindings ?? {}, "_text")) node.bindings[slotName] = slotChild.bindings._text;
|
|
609
|
+
else if (typeof slotChild.properties?._text === "string") node.properties[slotName] = slotChild.properties._text;
|
|
610
|
+
}
|
|
611
|
+
delete node.slots;
|
|
612
|
+
} else if (target === "reactNative" && node.slots) {
|
|
613
|
+
for (const slotChildren of Object.values(node.slots)) {
|
|
614
|
+
for (const child of slotChildren) {
|
|
615
|
+
const decoded = decodeSlotText(child).properties?._text;
|
|
616
|
+
if (typeof decoded === "string" && !Object.hasOwn(child.bindings ?? {}, "_text")) {
|
|
617
|
+
child.bindings ??= {};
|
|
618
|
+
child.bindings._text = { code: JSON.stringify(decoded), type: "single", bindingType: "expression" };
|
|
619
|
+
delete child.properties._text;
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
} else if (nativeSlotProjectionTargets.has(target) && node.slots) {
|
|
624
|
+
const projected = [];
|
|
625
|
+
for (const [slotName, slotChildren] of Object.entries(node.slots)) {
|
|
626
|
+
const children = slotChildren.map(decodeSlotText);
|
|
627
|
+
if (target === "vue" || target === "svelte") {
|
|
628
|
+
projected.push({
|
|
629
|
+
"@type": "@builder.io/mitosis/node",
|
|
630
|
+
name: target === "vue" ? "template" : "svelte:fragment",
|
|
631
|
+
properties: target === "vue" ? { [`v-slot:${slotName}`]: "" } : { slot: slotName },
|
|
632
|
+
bindings: {},
|
|
633
|
+
meta: {},
|
|
634
|
+
scope: {},
|
|
635
|
+
children
|
|
636
|
+
});
|
|
637
|
+
continue;
|
|
638
|
+
}
|
|
639
|
+
if (target === "marko") {
|
|
640
|
+
projected.push({
|
|
641
|
+
"@type": "@builder.io/mitosis/node",
|
|
642
|
+
name: `@${slotName}`,
|
|
643
|
+
properties: {},
|
|
644
|
+
bindings: {},
|
|
645
|
+
meta: {},
|
|
646
|
+
scope: {},
|
|
647
|
+
children
|
|
648
|
+
});
|
|
649
|
+
continue;
|
|
650
|
+
}
|
|
651
|
+
const slotAttribute = target === "qwik" ? "q:slot" : target === "angular" ? slotName : "slot";
|
|
652
|
+
for (const child of children) {
|
|
653
|
+
if (isMitosisTextNode(child)) {
|
|
654
|
+
projected.push({
|
|
655
|
+
"@type": "@builder.io/mitosis/node",
|
|
656
|
+
name: "span",
|
|
657
|
+
properties: { [slotAttribute]: slotName },
|
|
658
|
+
bindings: {},
|
|
659
|
+
meta: {},
|
|
660
|
+
scope: {},
|
|
661
|
+
children: [child]
|
|
662
|
+
});
|
|
663
|
+
} else {
|
|
664
|
+
child.properties ??= {};
|
|
665
|
+
child.properties[slotAttribute] = slotAttribute === slotName ? "" : slotName;
|
|
666
|
+
projected.push(child);
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
node.children = [...node.children ?? [], ...projected];
|
|
671
|
+
delete node.slots;
|
|
672
|
+
}
|
|
673
|
+
if (node.name === "Slot" && target === "marko") {
|
|
674
|
+
node.name = node.properties.name ? `@${node.properties.name}` : "@renderBody";
|
|
675
|
+
delete node.properties.name;
|
|
676
|
+
} else if (node.name === "Slot" && target === "solid") {
|
|
677
|
+
const slotName = node.properties.name;
|
|
678
|
+
const code = typeof slotName === "string" && slotName !== "default" ? `props.${slotName}` : "props.children";
|
|
679
|
+
const valueNode = {
|
|
680
|
+
"@type": "@builder.io/mitosis/node",
|
|
681
|
+
name: "div",
|
|
682
|
+
properties: {},
|
|
683
|
+
bindings: { _text: { code, type: "single", bindingType: "expression" } },
|
|
684
|
+
meta: {},
|
|
685
|
+
scope: {},
|
|
686
|
+
children: []
|
|
687
|
+
};
|
|
688
|
+
if (node.children?.length) {
|
|
689
|
+
node.name = "Show";
|
|
690
|
+
node.properties = {};
|
|
691
|
+
node.bindings = { when: { code, type: "single", bindingType: "expression" } };
|
|
692
|
+
node.meta = { ...node.meta, else: { "@type": "@builder.io/mitosis/node", name: "Fragment", properties: {}, bindings: {}, meta: {}, scope: {}, children: node.children } };
|
|
693
|
+
node.children = [valueNode];
|
|
694
|
+
} else {
|
|
695
|
+
node.name = valueNode.name;
|
|
696
|
+
node.properties = valueNode.properties;
|
|
697
|
+
node.bindings = valueNode.bindings;
|
|
698
|
+
node.meta = valueNode.meta;
|
|
699
|
+
node.children = [];
|
|
700
|
+
}
|
|
701
|
+
} else if (node.name === "Slot" && nativeSlotOutletTargets.has(target)) node.name = "slot";
|
|
702
|
+
result.push(node);
|
|
703
|
+
}
|
|
704
|
+
return result;
|
|
705
|
+
}
|
|
706
|
+
function resultFiles(value, target, name) {
|
|
707
|
+
if (typeof value === "string") return [{ path: `${name}.${extensionFor(target)}`, contents: value, kind: "component" }];
|
|
708
|
+
if (value && typeof value === "object") {
|
|
709
|
+
const obj = value;
|
|
710
|
+
if (typeof obj.code === "string") return [{ path: `${name}.${extensionFor(target)}`, contents: obj.code, kind: "component" }];
|
|
711
|
+
if (Array.isArray(obj.files)) return obj.files.flatMap((f, i) => typeof f === "string" ? [{ path: `${name}${i ? `-${i}` : ""}.${extensionFor(target)}`, contents: f, kind: "component" }] : typeof f?.contents === "string" ? [{ path: f.path || `${name}${i ? `-${i}` : ""}.${extensionFor(target)}`, contents: f.contents, kind: f.kind === "style" ? "style" : "component" }] : []);
|
|
712
|
+
}
|
|
713
|
+
return [{ path: `${name}.${extensionFor(target)}`, contents: JSON.stringify(value, null, 2), kind: "component" }];
|
|
714
|
+
}
|
|
715
|
+
function extensionFor(target) {
|
|
716
|
+
const extensions = { builder: "json", webcomponent: "js", react: "tsx", preact: "tsx", reactNative: "tsx", solid: "tsx", angular: "ts", vue: "vue", svelte: "svelte", qwik: "tsx", stencil: "tsx", lit: "ts", html: "html", customElement: "js", liquid: "liquid", alpine: "html", marko: "marko", mitosis: "lite.tsx", swift: "swift", taro: "tsx", template: "template", rsc: "tsx" };
|
|
717
|
+
return extensions[target] ?? "txt";
|
|
718
|
+
}
|
|
719
|
+
function generateWithMitosis(context) {
|
|
720
|
+
const target = context.target;
|
|
721
|
+
if (!(target in generators)) throw new Error(`Unsupported Mitosis target: ${target}`);
|
|
722
|
+
const component = componentIRToMitosis(context.component);
|
|
723
|
+
component.children = lowerNamedComponentSlots(component.children, target);
|
|
724
|
+
const qwikBaseline = target === "qwik" ? JSON.parse(JSON.stringify(component)) : void 0;
|
|
725
|
+
const qwikDefaults = target === "qwik" ? applyQwikPropDefaults(component, context.component.props) : [];
|
|
726
|
+
if (target === "swift") {
|
|
727
|
+
applySwiftPropTypes(component, context.component.props);
|
|
728
|
+
applySwiftPropDefaults(component.children, context.component.props);
|
|
729
|
+
}
|
|
730
|
+
if (expressionPropDefaultTargets.has(target)) applyExpressionPropDefaults(component.children, context.component.props);
|
|
731
|
+
if (target === "liquid") component.children = lowerLiquidElseBranches(component.children, component, context.options);
|
|
732
|
+
if (target === "reactNative") normalizeReactNativeFragmentLinks(component);
|
|
733
|
+
if (siblingElseTargets.has(target)) component.children = lowerElseBranches(component.children);
|
|
734
|
+
if (target === "swift") component.children = normalizeSwiftShowBranches(component.children);
|
|
735
|
+
let output = generators[target](component, context.options);
|
|
736
|
+
let qwikDefaultsInjected = true;
|
|
737
|
+
if (target === "qwik" && qwikDefaults.length > 0) {
|
|
738
|
+
const outputWithDefaults = typeof output === "string" ? addQwikPropDefaults(output, qwikDefaults) : void 0;
|
|
739
|
+
if (outputWithDefaults === void 0) {
|
|
740
|
+
output = generators.qwik(qwikBaseline, context.options);
|
|
741
|
+
qwikDefaultsInjected = false;
|
|
742
|
+
} else {
|
|
743
|
+
output = outputWithDefaults;
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
if (target === "liquid" && typeof output === "string") output = addLiquidPropDefaults(output, context.component);
|
|
747
|
+
if (target === "swift" && typeof output === "string") output = addSwiftPropDefaults(output, context.component.props);
|
|
748
|
+
const emitsPropTypes = context.options.typescript === true && propTypeTargets.has(target);
|
|
749
|
+
const emitsStateTypes = context.options.typescript === true && stateTypeTargets.has(target);
|
|
750
|
+
const diagnostics = [
|
|
751
|
+
{
|
|
752
|
+
severity: "warning",
|
|
753
|
+
code: "MITOSIS_TARGET_SEMANTICS_UNVERIFIED",
|
|
754
|
+
message: `DesignOS has smoke-tested code generation for ${target}, but has not verified semantic parity for this target.`,
|
|
755
|
+
path: `target.${target}`
|
|
756
|
+
},
|
|
757
|
+
...context.component.props.filter((prop) => prop.type !== void 0).filter((prop) => target === "swift" ? !swiftPrimitiveType(prop.type) : !emitsPropTypes || typeof prop.type !== "string" || !prop.type.trim()).map((prop) => ({
|
|
758
|
+
severity: "warning",
|
|
759
|
+
code: "MITOSIS_PROP_TYPE_NOT_PRESERVED",
|
|
760
|
+
message: `The ${target} Mitosis output does not preserve the type annotation for prop "${prop.name}" with the current target options.`,
|
|
761
|
+
path: `props.${prop.name}.type`
|
|
762
|
+
})),
|
|
763
|
+
...context.component.state.filter((state) => state.type !== void 0).filter((state) => !emitsStateTypes || typeof state.type !== "string" || !state.type.trim()).map((state) => ({
|
|
764
|
+
severity: "warning",
|
|
765
|
+
code: "MITOSIS_STATE_TYPE_NOT_PRESERVED",
|
|
766
|
+
message: `The ${target} Mitosis output does not preserve the type annotation for state "${state.name}" with the current target options.`,
|
|
767
|
+
path: `state.${state.name}.type`
|
|
768
|
+
})),
|
|
769
|
+
...context.component.props.filter((prop) => prop.defaultValue !== void 0).filter((prop) => !preservesPropDefault(target, prop.name, prop.defaultValue, prop.type) || target === "qwik" && !qwikDefaultsInjected).map((prop) => ({
|
|
770
|
+
severity: "warning",
|
|
771
|
+
code: "MITOSIS_PROP_DEFAULT_NOT_PRESERVED",
|
|
772
|
+
message: `The ${target} Mitosis output does not preserve the default value for prop "${prop.name}".`,
|
|
773
|
+
path: `props.${prop.name}.defaultValue`
|
|
774
|
+
})),
|
|
775
|
+
...hasUnsupportedNamedComponentSlots(context.component.root, target) ? [{
|
|
776
|
+
severity: "warning",
|
|
777
|
+
code: "MITOSIS_NAMED_COMPONENT_SLOT_NOT_PRESERVED",
|
|
778
|
+
message: `The ${target} Mitosis output does not preserve named component slots for the current target.`,
|
|
779
|
+
path: "root.slots"
|
|
780
|
+
}] : [],
|
|
781
|
+
...hasUnsupportedNamedSlotOutlet(context.component.root, target) ? [{
|
|
782
|
+
severity: "warning",
|
|
783
|
+
code: "MITOSIS_SLOT_OUTLET_NOT_PRESERVED",
|
|
784
|
+
message: "The SwiftUI output does not connect a slot outlet to caller-provided content; only fallback markup may render.",
|
|
785
|
+
path: "root.slot"
|
|
786
|
+
}] : [],
|
|
787
|
+
...target === "liquid" && hasUnsupportedLiquidElse(context.component.root) ? [{
|
|
788
|
+
severity: "warning",
|
|
789
|
+
code: "MITOSIS_CONDITIONAL_ELSE_NOT_PRESERVED",
|
|
790
|
+
message: "The Liquid target cannot safely lower this conditional else expression.",
|
|
791
|
+
path: "root.otherwise"
|
|
792
|
+
}] : [],
|
|
793
|
+
...eventlessTargets.has(target) && hasEventHandlers(context.component.root) ? [{
|
|
794
|
+
severity: "warning",
|
|
795
|
+
code: "MITOSIS_EVENT_HANDLER_NOT_PRESERVED",
|
|
796
|
+
message: `The ${target} target has no interactive event runtime and cannot preserve event handler bindings.`,
|
|
797
|
+
path: "root.events"
|
|
798
|
+
}] : []
|
|
799
|
+
];
|
|
800
|
+
return { target: context.target, files: resultFiles(output, target, context.component.name), diagnostics };
|
|
801
|
+
}
|
|
802
|
+
function mitosisNodeHasEventBindings(node) {
|
|
803
|
+
if (Object.entries(node.bindings ?? {}).some(
|
|
804
|
+
([name, binding]) => /^on[A-Z]/.test(name) && binding?.bindingType === "function"
|
|
805
|
+
)) return true;
|
|
806
|
+
if ((node.children ?? []).some((child) => mitosisNodeHasEventBindings(child))) return true;
|
|
807
|
+
return Object.values(node.slots ?? {}).some((children) => Array.isArray(children) && children.some((child) => mitosisNodeHasEventBindings(child)));
|
|
808
|
+
}
|
|
809
|
+
function mitosisNodeHasNamedSlots(node) {
|
|
810
|
+
if (Object.keys(node.slots ?? {}).some((name) => name !== "default")) return true;
|
|
811
|
+
if (typeof node.properties?.slot === "string" && node.properties.slot !== "" && node.properties.slot !== "default") return true;
|
|
812
|
+
if ((node.children ?? []).some((child) => mitosisNodeHasNamedSlots(child))) return true;
|
|
813
|
+
return Object.values(node.slots ?? {}).some((children) => Array.isArray(children) && children.some((child) => mitosisNodeHasNamedSlots(child)));
|
|
814
|
+
}
|
|
815
|
+
function mitosisNodeHasSlotOutlet(node) {
|
|
816
|
+
if (node.name === "Slot") return true;
|
|
817
|
+
if ((node.children ?? []).some((child) => mitosisNodeHasSlotOutlet(child))) return true;
|
|
818
|
+
return Object.values(node.slots ?? {}).some((children) => Array.isArray(children) && children.some((child) => mitosisNodeHasSlotOutlet(child)));
|
|
819
|
+
}
|
|
820
|
+
function generateMitosisSourceComponent(authoredComponent, target, options = {}) {
|
|
821
|
+
if (!(target in generators)) throw new Error(`Unsupported Mitosis target: ${target}`);
|
|
822
|
+
const component = structuredClone(authoredComponent);
|
|
823
|
+
component.children = lowerNamedComponentSlots(component.children ?? [], target);
|
|
824
|
+
if (target === "liquid") component.children = lowerLiquidElseBranches(component.children, component, options);
|
|
825
|
+
if (target === "reactNative") normalizeReactNativeFragmentLinks(component);
|
|
826
|
+
if (siblingElseTargets.has(target)) component.children = lowerElseBranches(component.children);
|
|
827
|
+
if (target === "swift") component.children = normalizeSwiftShowBranches(component.children);
|
|
828
|
+
const output = generators[target](component, options);
|
|
829
|
+
const diagnostics = [{
|
|
830
|
+
severity: "warning",
|
|
831
|
+
code: "MITOSIS_TARGET_SEMANTICS_UNVERIFIED",
|
|
832
|
+
message: `DesignOS has not verified semantic parity for all Mitosis source features on ${target}; output is generated by the upstream Mitosis target emitter.`,
|
|
833
|
+
path: `target.${target}`
|
|
834
|
+
}];
|
|
835
|
+
if (eventlessTargets.has(target) && (component.hooks?.onEvent?.length || component.children.some((node) => mitosisNodeHasEventBindings(node)))) {
|
|
836
|
+
diagnostics.push({
|
|
837
|
+
severity: "warning",
|
|
838
|
+
code: "MITOSIS_EVENT_HANDLER_NOT_PRESERVED",
|
|
839
|
+
message: `The ${target} target has no interactive event runtime and cannot preserve event handler bindings.`,
|
|
840
|
+
path: "source.events"
|
|
841
|
+
});
|
|
842
|
+
}
|
|
843
|
+
if (target === "swift" && component.children.some((node) => mitosisNodeHasNamedSlots(node))) {
|
|
844
|
+
diagnostics.push({
|
|
845
|
+
severity: "warning",
|
|
846
|
+
code: "MITOSIS_NAMED_COMPONENT_SLOT_NOT_PRESERVED",
|
|
847
|
+
message: "The Swift target adapter does not preserve named component slot composition.",
|
|
848
|
+
path: "source.children.slots"
|
|
849
|
+
});
|
|
850
|
+
}
|
|
851
|
+
if (target === "swift" && component.children.some((node) => mitosisNodeHasSlotOutlet(node))) {
|
|
852
|
+
diagnostics.push({
|
|
853
|
+
severity: "warning",
|
|
854
|
+
code: "MITOSIS_SLOT_OUTLET_NOT_PRESERVED",
|
|
855
|
+
message: "The Swift target output does not connect a Mitosis Slot outlet to caller-provided content; only fallback markup may render.",
|
|
856
|
+
path: "source.children.slot"
|
|
857
|
+
});
|
|
858
|
+
}
|
|
859
|
+
return { target, files: resultFiles(output, target, component.name), diagnostics };
|
|
860
|
+
}
|
|
861
|
+
function generateProjectRegistry(target, entries) {
|
|
862
|
+
const imports = entries.map((entry, index) => {
|
|
863
|
+
const modulePath = target === "vue" ? entry.modulePath : entry.modulePath.replace(/\.(?:tsx?|jsx?)$/, "");
|
|
864
|
+
return `import DesignOSComponent${index} from ${JSON.stringify(`./${modulePath}`)};`;
|
|
865
|
+
});
|
|
866
|
+
const registrations = entries.map((entry, index) => ` ${JSON.stringify(entry.type)}: DesignOSComponent${index},`);
|
|
867
|
+
return {
|
|
868
|
+
path: "components.ts",
|
|
869
|
+
kind: "metadata",
|
|
870
|
+
contents: [
|
|
871
|
+
...imports,
|
|
872
|
+
"",
|
|
873
|
+
"export const components = {",
|
|
874
|
+
...registrations,
|
|
875
|
+
"};",
|
|
876
|
+
"",
|
|
877
|
+
"export default components;",
|
|
878
|
+
""
|
|
879
|
+
].join("\n")
|
|
880
|
+
};
|
|
881
|
+
}
|
|
882
|
+
function createMitosisTarget(target) {
|
|
883
|
+
return {
|
|
884
|
+
name: target,
|
|
885
|
+
generate: (context) => generateWithMitosis(context),
|
|
886
|
+
generateMitosis: (component, options) => generateMitosisSourceComponent(component, target, options),
|
|
887
|
+
...target === "react" || target === "vue" ? { generateProjectRegistry: (entries) => generateProjectRegistry(target, entries) } : {}
|
|
888
|
+
};
|
|
889
|
+
}
|
|
890
|
+
function createMitosisCompiler() {
|
|
891
|
+
const registry = new TargetRegistry();
|
|
892
|
+
for (const target of mitosisTargets) registry.register(createMitosisTarget(target));
|
|
893
|
+
return registry;
|
|
894
|
+
}
|
|
895
|
+
function parseLiteral(value) {
|
|
896
|
+
try {
|
|
897
|
+
return JSON.parse(value.trim().replace(/'/g, '"'));
|
|
898
|
+
} catch {
|
|
899
|
+
return void 0;
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
function findTypeDeclarationBody(source, propsTypeRef) {
|
|
903
|
+
const declaration = source.match(new RegExp(`(?:interface|type)\\s+${propsTypeRef}\\s*(?:=)?\\s*\\{`));
|
|
904
|
+
if (!declaration || declaration.index === void 0) return void 0;
|
|
905
|
+
const start = declaration.index + declaration[0].length - 1;
|
|
906
|
+
let depth = 0;
|
|
907
|
+
let quote;
|
|
908
|
+
let escaped = false;
|
|
909
|
+
for (let index = start; index < source.length; index += 1) {
|
|
910
|
+
const character = source[index];
|
|
911
|
+
if (quote) {
|
|
912
|
+
if (escaped) escaped = false;
|
|
913
|
+
else if (character === "\\") escaped = true;
|
|
914
|
+
else if (character === quote) quote = void 0;
|
|
915
|
+
continue;
|
|
916
|
+
}
|
|
917
|
+
if (character === "'" || character === '"' || character === "`") {
|
|
918
|
+
quote = character;
|
|
919
|
+
continue;
|
|
920
|
+
}
|
|
921
|
+
if (character === "{") depth += 1;
|
|
922
|
+
else if (character === "}" && --depth === 0) return source.slice(start + 1, index);
|
|
923
|
+
}
|
|
924
|
+
return void 0;
|
|
925
|
+
}
|
|
926
|
+
function splitTopLevelFields(body) {
|
|
927
|
+
const fields = [];
|
|
928
|
+
let start = 0;
|
|
929
|
+
let depth = 0;
|
|
930
|
+
for (let index = 0; index < body.length; index += 1) {
|
|
931
|
+
if (body[index] === "{" || body[index] === "[" || body[index] === "<") depth += 1;
|
|
932
|
+
else if (body[index] === "}" || body[index] === "]" || body[index] === ">") depth = Math.max(0, depth - 1);
|
|
933
|
+
else if (body[index] === ";" && depth === 0) {
|
|
934
|
+
fields.push(body.slice(start, index));
|
|
935
|
+
start = index + 1;
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
fields.push(body.slice(start));
|
|
939
|
+
return fields;
|
|
940
|
+
}
|
|
941
|
+
function extractDesignOSSourceProps(source, propsTypeRef) {
|
|
942
|
+
if (!propsTypeRef) return [];
|
|
943
|
+
const body = findTypeDeclarationBody(source, propsTypeRef);
|
|
944
|
+
if (body === void 0) return [];
|
|
945
|
+
const props = /* @__PURE__ */ new Map();
|
|
946
|
+
for (const field of splitTopLevelFields(body)) {
|
|
947
|
+
const match = field.trim().match(/^([A-Za-z_$][\w$]*)\s*(\?)?\s*:\s*([^\n]+)$/);
|
|
948
|
+
if (!match) continue;
|
|
949
|
+
props.set(match[1], { name: match[1], optional: Boolean(match[2]) });
|
|
950
|
+
}
|
|
951
|
+
const destructured = source.match(/function\s+\w+\s*\(\s*\{([\s\S]*?)\}\s*(?::[^)]*)?\)/);
|
|
952
|
+
if (destructured) {
|
|
953
|
+
for (const part of destructured[1].split(",")) {
|
|
954
|
+
const match = part.trim().match(/^([A-Za-z_$][\w$]*)\s*=\s*(.+)$/);
|
|
955
|
+
if (!match || !props.has(match[1])) continue;
|
|
956
|
+
const value = parseLiteral(match[2]);
|
|
957
|
+
if (value !== void 0) props.get(match[1]).defaultValue = value;
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
return [...props.values()];
|
|
961
|
+
}
|
|
962
|
+
function parseMitosisSource(source, options = {}) {
|
|
963
|
+
if (typeof source !== "string") throw new TypeError("Mitosis source must be a string");
|
|
964
|
+
try {
|
|
965
|
+
const component = parseJsx(source, {
|
|
966
|
+
typescript: true,
|
|
967
|
+
enableBlocksSlots: options.enableBlocksSlots ?? true,
|
|
968
|
+
...options.filePath ? { filePath: options.filePath } : {}
|
|
969
|
+
});
|
|
970
|
+
const designosProps = extractDesignOSSourceProps(source, component.propsTypeRef);
|
|
971
|
+
if (designosProps.length > 0) component.meta = { ...component.meta, designosProps };
|
|
972
|
+
return component;
|
|
973
|
+
} catch (cause) {
|
|
974
|
+
const message = cause instanceof Error ? cause.message : String(cause);
|
|
975
|
+
throw new Error(`Unable to parse DesignOS TSX${options.filePath ? ` at ${options.filePath}` : ""}: ${message}`, { cause });
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
var TargetRegistry = class {
|
|
979
|
+
targets = /* @__PURE__ */ new Map();
|
|
980
|
+
register(target) {
|
|
981
|
+
if (this.targets.has(target.name)) throw new Error(`Compiler target already registered: ${target.name}`);
|
|
982
|
+
this.targets.set(target.name, target);
|
|
983
|
+
}
|
|
984
|
+
get(target) {
|
|
985
|
+
const definition = this.targets.get(target);
|
|
986
|
+
if (!definition) throw new Error(`Compiler target not registered: ${target}`);
|
|
987
|
+
return definition;
|
|
988
|
+
}
|
|
989
|
+
names() {
|
|
990
|
+
return [...this.targets.keys()];
|
|
991
|
+
}
|
|
992
|
+
};
|
|
993
|
+
function normalizeComponent(component) {
|
|
994
|
+
return structuredClone(component);
|
|
995
|
+
}
|
|
996
|
+
function validateComponentIR(component) {
|
|
997
|
+
const diagnostics = [];
|
|
998
|
+
if (!component || typeof component !== "object") {
|
|
999
|
+
return [{ severity: "error", code: "COMPONENT_IR_REQUIRED", message: "ComponentIR must be an object", path: "component" }];
|
|
1000
|
+
}
|
|
1001
|
+
if (typeof component.name !== "string" || !component.name.trim()) diagnostics.push({ severity: "error", code: "COMPONENT_NAME_REQUIRED", message: "ComponentIR.name is required", path: "name" });
|
|
1002
|
+
if (!component.root || typeof component.root !== "object") diagnostics.push({ severity: "error", code: "COMPONENT_ROOT_REQUIRED", message: "ComponentIR.root is required", path: "root" });
|
|
1003
|
+
if (!Array.isArray(component.imports)) diagnostics.push({ severity: "error", code: "COMPONENT_IMPORTS_INVALID", message: "ComponentIR.imports must be an array", path: "imports" });
|
|
1004
|
+
if (!Array.isArray(component.state)) diagnostics.push({ severity: "error", code: "COMPONENT_STATE_INVALID", message: "ComponentIR.state must be an array", path: "state" });
|
|
1005
|
+
if (!Array.isArray(component.props)) {
|
|
1006
|
+
diagnostics.push({ severity: "error", code: "COMPONENT_PROPS_INVALID", message: "ComponentIR.props must be an array", path: "props" });
|
|
1007
|
+
return diagnostics;
|
|
1008
|
+
}
|
|
1009
|
+
const names = /* @__PURE__ */ new Set();
|
|
1010
|
+
for (const prop of component.props) {
|
|
1011
|
+
if (names.has(prop.name)) diagnostics.push({ severity: "error", code: "DUPLICATE_PROP", message: `Duplicate prop: ${prop.name}`, path: "props" });
|
|
1012
|
+
names.add(prop.name);
|
|
1013
|
+
}
|
|
1014
|
+
return diagnostics;
|
|
1015
|
+
}
|
|
1016
|
+
function serializedValue(value) {
|
|
1017
|
+
if (value === void 0) return "undefined";
|
|
1018
|
+
return JSON.stringify(value, (_key, nested) => {
|
|
1019
|
+
if (!nested || typeof nested !== "object" || Array.isArray(nested)) return nested;
|
|
1020
|
+
return Object.fromEntries(Object.entries(nested).sort(([left], [right]) => left.localeCompare(right)));
|
|
1021
|
+
});
|
|
1022
|
+
}
|
|
1023
|
+
function validateManifestImplementationContract(manifest, implementation, path = "component") {
|
|
1024
|
+
const diagnostics = [];
|
|
1025
|
+
const sourceProps = implementation.kind === "ir" ? new Map(implementation.component.props.map((prop) => [prop.name, prop])) : new Map(
|
|
1026
|
+
(implementation.component.meta?.designosProps ?? []).map((prop) => [prop.name, prop])
|
|
1027
|
+
);
|
|
1028
|
+
const manifestFields = new Map(manifest.fields.map((field) => [field.name, field]));
|
|
1029
|
+
const supportsChildren = Boolean(
|
|
1030
|
+
manifest.capabilities?.canHaveChildren || manifest.slots?.some((slot) => slot.name === "default" || slot.name === "children")
|
|
1031
|
+
);
|
|
1032
|
+
for (const prop of sourceProps.values()) {
|
|
1033
|
+
if (prop.name === "children" && supportsChildren) continue;
|
|
1034
|
+
if (!manifestFields.has(prop.name)) diagnostics.push({
|
|
1035
|
+
severity: "warning",
|
|
1036
|
+
code: "COMPILER_PROJECT_SOURCE_PROP_NOT_IN_MANIFEST",
|
|
1037
|
+
message: `Source prop "${prop.name}" is not editable through manifest "${manifest.type}".`,
|
|
1038
|
+
path: `${path}.implementation.component.props.${prop.name}`
|
|
1039
|
+
});
|
|
1040
|
+
}
|
|
1041
|
+
for (const field of manifest.fields) {
|
|
1042
|
+
const prop = sourceProps.get(field.name);
|
|
1043
|
+
if (!prop) {
|
|
1044
|
+
if (field.required) diagnostics.push({
|
|
1045
|
+
severity: "error",
|
|
1046
|
+
code: "COMPILER_PROJECT_REQUIRED_FIELD_NOT_IN_SOURCE",
|
|
1047
|
+
message: `Required manifest field "${field.name}" is not declared by the source component.`,
|
|
1048
|
+
path: `${path}.manifest.fields.${field.name}`
|
|
1049
|
+
});
|
|
1050
|
+
continue;
|
|
1051
|
+
}
|
|
1052
|
+
if (field.defaultValue !== void 0 && prop.defaultValue !== void 0 && serializedValue(field.defaultValue) !== serializedValue(prop.defaultValue)) diagnostics.push({
|
|
1053
|
+
severity: "error",
|
|
1054
|
+
code: "COMPILER_PROJECT_DEFAULT_MISMATCH",
|
|
1055
|
+
message: `Manifest default for "${field.name}" differs from the source runtime default; manifest defaults win for authored page data and source defaults remain runtime fallbacks.`,
|
|
1056
|
+
path: `${path}.manifest.fields.${field.name}.defaultValue`
|
|
1057
|
+
});
|
|
1058
|
+
}
|
|
1059
|
+
return diagnostics;
|
|
1060
|
+
}
|
|
1061
|
+
function isSafeRelativePath(value) {
|
|
1062
|
+
return typeof value === "string" && value.length > 0 && !value.startsWith("/") && !value.includes("\\") && !/^[A-Za-z]:/.test(value) && value.split("/").every((part) => part.length > 0 && part !== "." && part !== "..");
|
|
1063
|
+
}
|
|
1064
|
+
function validateCompilerProject(project) {
|
|
1065
|
+
const diagnostics = [];
|
|
1066
|
+
if (!project || typeof project !== "object" || project.schemaVersion !== "1") {
|
|
1067
|
+
return [{ severity: "error", code: "COMPILER_PROJECT_SCHEMA_VERSION_UNSUPPORTED", message: 'CompilerProject.schemaVersion must be "1"', path: "schemaVersion" }];
|
|
1068
|
+
}
|
|
1069
|
+
if (!Array.isArray(project.components)) {
|
|
1070
|
+
return [{ severity: "error", code: "COMPILER_PROJECT_COMPONENTS_REQUIRED", message: "CompilerProject.components must be an array", path: "components" }];
|
|
1071
|
+
}
|
|
1072
|
+
const componentTypes = /* @__PURE__ */ new Set();
|
|
1073
|
+
const componentNames = /* @__PURE__ */ new Set();
|
|
1074
|
+
const assetOutputs = /* @__PURE__ */ new Map();
|
|
1075
|
+
project.components.forEach((definition, index) => {
|
|
1076
|
+
const prefix = `components[${index}]`;
|
|
1077
|
+
const manifest = definition?.manifest;
|
|
1078
|
+
const implementation = definition?.implementation;
|
|
1079
|
+
const type = manifest?.type;
|
|
1080
|
+
if (typeof type !== "string" || !type.trim()) {
|
|
1081
|
+
diagnostics.push({ severity: "error", code: "COMPILER_PROJECT_COMPONENT_TYPE_REQUIRED", message: "Component manifest type must be a non-empty string", path: `${prefix}.manifest.type` });
|
|
1082
|
+
} else if (componentTypes.has(type)) {
|
|
1083
|
+
diagnostics.push({ severity: "error", code: "COMPILER_PROJECT_DUPLICATE_COMPONENT_TYPE", message: `Duplicate component manifest type: ${type}`, path: `${prefix}.manifest.type` });
|
|
1084
|
+
} else {
|
|
1085
|
+
componentTypes.add(type);
|
|
1086
|
+
}
|
|
1087
|
+
if (!manifest || typeof manifest.displayName !== "string" || !manifest.displayName.trim() || !Array.isArray(manifest.fields)) {
|
|
1088
|
+
diagnostics.push({ severity: "error", code: "COMPILER_PROJECT_COMPONENT_MANIFEST_INVALID", message: "Component manifest requires a displayName and fields array", path: `${prefix}.manifest` });
|
|
1089
|
+
}
|
|
1090
|
+
if (!implementation || implementation.kind !== "ir" && implementation.kind !== "mitosis" || !implementation.component) {
|
|
1091
|
+
diagnostics.push({ severity: "error", code: "COMPILER_PROJECT_IMPLEMENTATION_INVALID", message: "Project compilation requires a DesignOS IR or parsed Mitosis component implementation", path: `${prefix}.implementation` });
|
|
1092
|
+
} else {
|
|
1093
|
+
const name = implementation.component.name;
|
|
1094
|
+
if (typeof name !== "string" || !/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name)) {
|
|
1095
|
+
diagnostics.push({ severity: "error", code: "COMPILER_PROJECT_COMPONENT_NAME_INVALID", message: `Component name must be a valid identifier for generated framework components: ${name}`, path: `${prefix}.implementation.component.name` });
|
|
1096
|
+
} else if (componentNames.has(name)) {
|
|
1097
|
+
diagnostics.push({ severity: "error", code: "COMPILER_PROJECT_DUPLICATE_COMPONENT_NAME", message: `Duplicate component implementation name: ${name}`, path: `${prefix}.implementation.component.name` });
|
|
1098
|
+
} else {
|
|
1099
|
+
componentNames.add(name);
|
|
1100
|
+
}
|
|
1101
|
+
if (implementation.kind === "ir") {
|
|
1102
|
+
diagnostics.push(...validateComponentIR(implementation.component).map((diagnostic) => ({
|
|
1103
|
+
...diagnostic,
|
|
1104
|
+
path: diagnostic.path ? `${prefix}.implementation.component.${diagnostic.path}` : `${prefix}.implementation.component`
|
|
1105
|
+
})));
|
|
1106
|
+
} else if (implementation.component["@type"] !== "@builder.io/mitosis/component") {
|
|
1107
|
+
diagnostics.push({ severity: "error", code: "COMPILER_PROJECT_MITOSIS_COMPONENT_INVALID", message: "Parsed Mitosis implementation has an invalid component discriminator", path: `${prefix}.implementation.component.@type` });
|
|
1108
|
+
}
|
|
1109
|
+
if (manifest && Array.isArray(manifest.fields)) diagnostics.push(...validateManifestImplementationContract(manifest, implementation, prefix));
|
|
1110
|
+
}
|
|
1111
|
+
const outputDirectory = definition?.outputDirectory ?? "components";
|
|
1112
|
+
if (!isSafeRelativePath(outputDirectory)) {
|
|
1113
|
+
diagnostics.push({ severity: "error", code: "COMPILER_PROJECT_OUTPUT_DIRECTORY_INVALID", message: "outputDirectory must be a safe path relative to the target output directory", path: `${prefix}.outputDirectory` });
|
|
1114
|
+
}
|
|
1115
|
+
for (const collection of ["styles", "assets"]) {
|
|
1116
|
+
const references = definition?.[collection];
|
|
1117
|
+
if (references !== void 0 && !Array.isArray(references)) {
|
|
1118
|
+
diagnostics.push({ severity: "error", code: `COMPILER_PROJECT_${collection.toUpperCase()}_INVALID`, message: `${collection} must be an array`, path: `${prefix}.${collection}` });
|
|
1119
|
+
}
|
|
1120
|
+
for (const [assetIndex, asset] of (Array.isArray(references) ? references : []).entries()) {
|
|
1121
|
+
const assetPath = `${prefix}.${collection}[${assetIndex}]`;
|
|
1122
|
+
if (!isSafeRelativePath(asset.source)) {
|
|
1123
|
+
diagnostics.push({ severity: "error", code: "COMPILER_PROJECT_ASSET_SOURCE_PATH_INVALID", message: "Asset source must be a safe path relative to the project root", path: `${assetPath}.source` });
|
|
1124
|
+
continue;
|
|
1125
|
+
}
|
|
1126
|
+
const outputPath = asset.outputPath ?? asset.source;
|
|
1127
|
+
if (!isSafeRelativePath(outputPath)) {
|
|
1128
|
+
diagnostics.push({ severity: "error", code: "COMPILER_PROJECT_ASSET_OUTPUT_PATH_INVALID", message: "Asset outputPath must be a safe path relative to the generated output directory", path: `${assetPath}.outputPath` });
|
|
1129
|
+
continue;
|
|
1130
|
+
}
|
|
1131
|
+
const normalizedOutputPath = outputPath.toLowerCase();
|
|
1132
|
+
const existingSource = assetOutputs.get(normalizedOutputPath);
|
|
1133
|
+
if (existingSource && existingSource !== asset.source) {
|
|
1134
|
+
diagnostics.push({ severity: "error", code: "COMPILER_PROJECT_ASSET_OUTPUT_COLLISION", message: `Different assets target the same output path: ${outputPath}`, path: `${assetPath}.outputPath` });
|
|
1135
|
+
} else {
|
|
1136
|
+
assetOutputs.set(normalizedOutputPath, asset.source);
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
});
|
|
1141
|
+
return diagnostics;
|
|
1142
|
+
}
|
|
1143
|
+
async function compileComponent(component, registry, options) {
|
|
1144
|
+
const plugins = [...options.plugins ?? []].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
|
|
1145
|
+
let normalized = normalizeComponent(component);
|
|
1146
|
+
for (const plugin of plugins) normalized = plugin.beforeNormalize?.(normalized) ?? normalized;
|
|
1147
|
+
for (const plugin of plugins) normalized = plugin.afterNormalize?.(normalized) ?? normalized;
|
|
1148
|
+
const diagnostics = validateComponentIR(normalized);
|
|
1149
|
+
if (diagnostics.some((diagnostic) => diagnostic.severity === "error")) {
|
|
1150
|
+
return { target: options.target, files: [], diagnostics };
|
|
1151
|
+
}
|
|
1152
|
+
const context = { target: options.target, component: normalized, options: options.targetOptions ?? {} };
|
|
1153
|
+
for (const plugin of plugins) await plugin.beforeGenerate?.(context);
|
|
1154
|
+
let result = registry.get(options.target).generate(context);
|
|
1155
|
+
result = { ...result, diagnostics: [...diagnostics, ...result.diagnostics] };
|
|
1156
|
+
for (const plugin of plugins) result = await plugin.afterGenerate?.(result) ?? result;
|
|
1157
|
+
return result;
|
|
1158
|
+
}
|
|
1159
|
+
function relativeModulePath(fromFile, toFile) {
|
|
1160
|
+
const fromDirectory = fromFile.split("/").slice(0, -1);
|
|
1161
|
+
const toParts = toFile.split("/");
|
|
1162
|
+
let shared = 0;
|
|
1163
|
+
while (shared < fromDirectory.length && shared < toParts.length && fromDirectory[shared] === toParts[shared]) shared++;
|
|
1164
|
+
const path = [
|
|
1165
|
+
...Array.from({ length: fromDirectory.length - shared }, () => ".."),
|
|
1166
|
+
...toParts.slice(shared)
|
|
1167
|
+
].join("/");
|
|
1168
|
+
return path.startsWith(".") ? path : `./${path}`;
|
|
1169
|
+
}
|
|
1170
|
+
function addStyleImports(contents, moduleOutputPath, styles) {
|
|
1171
|
+
const statements = [...new Set(styles.map(
|
|
1172
|
+
(style) => `import ${JSON.stringify(relativeModulePath(moduleOutputPath, style.outputPath ?? style.source))};`
|
|
1173
|
+
))].filter((statement) => !contents.includes(statement));
|
|
1174
|
+
if (statements.length === 0) return contents;
|
|
1175
|
+
const firstLineEnd = contents.indexOf("\n");
|
|
1176
|
+
if (contents.startsWith("// @ts-nocheck") && firstLineEnd >= 0) {
|
|
1177
|
+
return `${contents.slice(0, firstLineEnd + 1)}${statements.join("\n")}
|
|
1178
|
+
${contents.slice(firstLineEnd + 1)}`;
|
|
1179
|
+
}
|
|
1180
|
+
return `${statements.join("\n")}
|
|
1181
|
+
${contents}`;
|
|
1182
|
+
}
|
|
1183
|
+
async function compileProject(project, registry, options) {
|
|
1184
|
+
const diagnostics = validateCompilerProject(project);
|
|
1185
|
+
if (diagnostics.some((diagnostic) => diagnostic.severity === "error")) {
|
|
1186
|
+
return { target: options.target, files: [], assets: [], diagnostics };
|
|
1187
|
+
}
|
|
1188
|
+
const files = [];
|
|
1189
|
+
const assets = /* @__PURE__ */ new Map();
|
|
1190
|
+
const generatedPaths = /* @__PURE__ */ new Set();
|
|
1191
|
+
const registryEntries = [];
|
|
1192
|
+
const targetDefinition = registry.get(options.target);
|
|
1193
|
+
for (const [index, definition] of project.components.entries()) {
|
|
1194
|
+
let result;
|
|
1195
|
+
if (definition.implementation.kind === "ir") {
|
|
1196
|
+
result = await compileComponent(definition.implementation.component, registry, options);
|
|
1197
|
+
} else if (targetDefinition.generateMitosis) {
|
|
1198
|
+
result = targetDefinition.generateMitosis(definition.implementation.component, options.targetOptions ?? {});
|
|
1199
|
+
} else {
|
|
1200
|
+
result = {
|
|
1201
|
+
target: options.target,
|
|
1202
|
+
files: [],
|
|
1203
|
+
diagnostics: [{
|
|
1204
|
+
severity: "error",
|
|
1205
|
+
code: "COMPILER_TARGET_MITOSIS_SOURCE_UNSUPPORTED",
|
|
1206
|
+
message: `Target ${options.target} does not provide a Mitosis source generator.`,
|
|
1207
|
+
path: `components[${index}].implementation`
|
|
1208
|
+
}]
|
|
1209
|
+
};
|
|
1210
|
+
}
|
|
1211
|
+
diagnostics.push(...result.diagnostics.map((diagnostic) => ({
|
|
1212
|
+
...diagnostic,
|
|
1213
|
+
path: diagnostic.path ? `components[${index}].${diagnostic.path}` : `components[${index}]`
|
|
1214
|
+
})));
|
|
1215
|
+
const componentName = definition.implementation.component.name;
|
|
1216
|
+
for (const file of result.files) {
|
|
1217
|
+
if (!isSafeRelativePath(file.path)) {
|
|
1218
|
+
diagnostics.push({ severity: "error", code: "COMPILER_PROJECT_GENERATED_PATH_INVALID", message: `Target generated an unsafe relative file path: ${file.path}`, path: `components[${index}].output` });
|
|
1219
|
+
continue;
|
|
1220
|
+
}
|
|
1221
|
+
const outputPath = `${definition.outputDirectory ?? "components"}/${file.path}`;
|
|
1222
|
+
const normalizedPath = outputPath.toLowerCase();
|
|
1223
|
+
if (generatedPaths.has(normalizedPath)) {
|
|
1224
|
+
diagnostics.push({ severity: "error", code: "COMPILER_PROJECT_GENERATED_PATH_COLLISION", message: `Multiple components generated the same output path: ${outputPath}`, path: `components[${index}].output` });
|
|
1225
|
+
continue;
|
|
1226
|
+
}
|
|
1227
|
+
generatedPaths.add(normalizedPath);
|
|
1228
|
+
const isEntryModule = file.kind === "component" && file.path.split("/").pop()?.startsWith(`${componentName}.`);
|
|
1229
|
+
files.push({
|
|
1230
|
+
...file,
|
|
1231
|
+
path: outputPath,
|
|
1232
|
+
contents: isEntryModule && definition.styles?.length ? addStyleImports(file.contents, outputPath, definition.styles) : file.contents
|
|
1233
|
+
});
|
|
1234
|
+
}
|
|
1235
|
+
if (targetDefinition.generateProjectRegistry) {
|
|
1236
|
+
const entryFiles = result.files.filter((file) => file.kind === "component" && file.path.split("/").pop()?.startsWith(`${componentName}.`));
|
|
1237
|
+
if (entryFiles.length !== 1) {
|
|
1238
|
+
diagnostics.push({ severity: "error", code: "COMPILER_PROJECT_REGISTRY_ENTRY_AMBIGUOUS", message: `Expected one generated entry module for ${componentName}; found ${entryFiles.length}`, path: `components[${index}].output` });
|
|
1239
|
+
} else {
|
|
1240
|
+
registryEntries.push({
|
|
1241
|
+
type: definition.manifest.type,
|
|
1242
|
+
modulePath: `${definition.outputDirectory ?? "components"}/${entryFiles[0].path}`
|
|
1243
|
+
});
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
for (const asset of [...definition.styles ?? [], ...definition.assets ?? []]) {
|
|
1247
|
+
assets.set(asset.outputPath ?? asset.source, asset.source);
|
|
1248
|
+
}
|
|
1249
|
+
}
|
|
1250
|
+
if (targetDefinition.generateProjectRegistry) {
|
|
1251
|
+
const registryFile = targetDefinition.generateProjectRegistry(registryEntries);
|
|
1252
|
+
if (!isSafeRelativePath(registryFile.path)) {
|
|
1253
|
+
diagnostics.push({ severity: "error", code: "COMPILER_PROJECT_REGISTRY_PATH_INVALID", message: `Target generated an unsafe registry path: ${registryFile.path}`, path: "target.registry" });
|
|
1254
|
+
} else if (generatedPaths.has(registryFile.path.toLowerCase())) {
|
|
1255
|
+
diagnostics.push({ severity: "error", code: "COMPILER_PROJECT_REGISTRY_PATH_COLLISION", message: `Registry output collides with a generated component file: ${registryFile.path}`, path: "target.registry" });
|
|
1256
|
+
} else {
|
|
1257
|
+
generatedPaths.add(registryFile.path.toLowerCase());
|
|
1258
|
+
files.push(registryFile);
|
|
1259
|
+
}
|
|
1260
|
+
} else {
|
|
1261
|
+
diagnostics.push({ severity: "info", code: "COMPILER_PROJECT_REGISTRY_NOT_REGISTERED", message: `Target ${options.target} has no verified project component registry emitter; generated files are emitted without components.ts.`, path: `target.${options.target}` });
|
|
1262
|
+
}
|
|
1263
|
+
for (const outputPath of assets.keys()) {
|
|
1264
|
+
if (generatedPaths.has(outputPath.toLowerCase())) {
|
|
1265
|
+
diagnostics.push({ severity: "error", code: "COMPILER_PROJECT_ASSET_GENERATED_PATH_COLLISION", message: `Asset output collides with a generated file: ${outputPath}`, path: "assets" });
|
|
1266
|
+
}
|
|
1267
|
+
}
|
|
1268
|
+
if (diagnostics.some((diagnostic) => diagnostic.severity === "error")) {
|
|
1269
|
+
return { target: options.target, files: [], assets: [], diagnostics };
|
|
1270
|
+
}
|
|
1271
|
+
return {
|
|
1272
|
+
target: options.target,
|
|
1273
|
+
files,
|
|
1274
|
+
assets: [...assets.entries()].map(([outputPath, source]) => ({ source, outputPath })),
|
|
1275
|
+
diagnostics
|
|
1276
|
+
};
|
|
1277
|
+
}
|
|
1278
|
+
|
|
1279
|
+
// src/run.ts
|
|
1280
|
+
import { bladeTarget } from "@designos/compiler-blade";
|
|
1281
|
+
var HELP = `DesignOS compiler CLI
|
|
1282
|
+
|
|
1283
|
+
Usage:
|
|
1284
|
+
designos compile --target <target> [options]
|
|
1285
|
+
|
|
1286
|
+
Options:
|
|
1287
|
+
--target <target> Registered target name (for example react or vue)
|
|
1288
|
+
--config <file> Project JSON file (default: designos.project.json)
|
|
1289
|
+
--project-root <directory> Root for config asset paths (default: current directory)
|
|
1290
|
+
--out-dir <directory> Output directory inside dist (default: dist/designos/<target>)
|
|
1291
|
+
--target-option key=value Pass a target-specific option; repeatable, values parse as JSON
|
|
1292
|
+
--help Show this help
|
|
1293
|
+
`;
|
|
1294
|
+
function parseTargetOption(value) {
|
|
1295
|
+
const separator = value.indexOf("=");
|
|
1296
|
+
if (separator < 1) throw new Error(`Invalid --target-option ${JSON.stringify(value)}; expected key=value`);
|
|
1297
|
+
const key = value.slice(0, separator).trim();
|
|
1298
|
+
if (!key) throw new Error("--target-option key must not be empty");
|
|
1299
|
+
const raw = value.slice(separator + 1);
|
|
1300
|
+
try {
|
|
1301
|
+
return [key, JSON.parse(raw)];
|
|
1302
|
+
} catch {
|
|
1303
|
+
return [key, raw];
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
function parseArguments(args) {
|
|
1307
|
+
if (args.length === 0 || args[0] === "--help" || args[0] === "help") return { help: true };
|
|
1308
|
+
if (args[0] !== "compile") throw new Error(`Unknown command: ${args[0]}
|
|
1309
|
+
|
|
1310
|
+
${HELP}`);
|
|
1311
|
+
const options = {
|
|
1312
|
+
config: "designos.project.json",
|
|
1313
|
+
targetOptions: {}
|
|
1314
|
+
};
|
|
1315
|
+
for (let index = 1; index < args.length; index += 1) {
|
|
1316
|
+
const flag = args[index];
|
|
1317
|
+
if (flag === "--help") return { help: true };
|
|
1318
|
+
if (!["--target", "--config", "--out-dir", "--project-root", "--target-option"].includes(flag)) {
|
|
1319
|
+
throw new Error(`Unknown option: ${flag}
|
|
1320
|
+
|
|
1321
|
+
${HELP}`);
|
|
1322
|
+
}
|
|
1323
|
+
const value = args[index + 1];
|
|
1324
|
+
if (!value || value.startsWith("--")) throw new Error(`Missing value for ${flag}`);
|
|
1325
|
+
index += 1;
|
|
1326
|
+
if (flag === "--target") options.target = value;
|
|
1327
|
+
else if (flag === "--config") options.config = value;
|
|
1328
|
+
else if (flag === "--out-dir") options.outDir = value;
|
|
1329
|
+
else if (flag === "--project-root") options.projectRoot = value;
|
|
1330
|
+
else {
|
|
1331
|
+
const [key, targetValue] = parseTargetOption(value);
|
|
1332
|
+
options.targetOptions[key] = targetValue;
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
if (!options.target) throw new Error("Missing required --target option");
|
|
1336
|
+
return options;
|
|
1337
|
+
}
|
|
1338
|
+
function isWithin(root, candidate) {
|
|
1339
|
+
const pathFromRoot = relative(root, candidate);
|
|
1340
|
+
return pathFromRoot === "" || pathFromRoot !== ".." && !pathFromRoot.startsWith(`..${sep}`) && !isAbsolute(pathFromRoot);
|
|
1341
|
+
}
|
|
1342
|
+
function isSafeRelativePath2(value) {
|
|
1343
|
+
return value.length > 0 && !value.startsWith("/") && !value.includes("\\") && !/^[A-Za-z]:/.test(value) && value.split("/").every((segment) => segment.length > 0 && segment !== "." && segment !== "..");
|
|
1344
|
+
}
|
|
1345
|
+
async function ensureDirectoryWithoutSymlinks(root, relativeDirectory) {
|
|
1346
|
+
let current = root;
|
|
1347
|
+
for (const segment of relativeDirectory ? relativeDirectory.split(sep).filter(Boolean) : []) {
|
|
1348
|
+
current = join(current, segment);
|
|
1349
|
+
try {
|
|
1350
|
+
const entry = await lstat(current);
|
|
1351
|
+
if (entry.isSymbolicLink() || !entry.isDirectory()) {
|
|
1352
|
+
throw new Error(`Output path contains a non-directory or symbolic link: ${current}`);
|
|
1353
|
+
}
|
|
1354
|
+
} catch (cause) {
|
|
1355
|
+
if (cause.code !== "ENOENT") throw cause;
|
|
1356
|
+
await mkdir(current);
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
return current;
|
|
1360
|
+
}
|
|
1361
|
+
async function prepareOutputRoot(projectRoot, outputArgument) {
|
|
1362
|
+
const distPath = resolve(projectRoot, "dist");
|
|
1363
|
+
const requestedOutput = resolve(projectRoot, outputArgument);
|
|
1364
|
+
if (requestedOutput === distPath || !isWithin(distPath, requestedOutput)) {
|
|
1365
|
+
throw new Error("--out-dir must be a dedicated subdirectory inside the project dist directory");
|
|
1366
|
+
}
|
|
1367
|
+
await mkdir(distPath, { recursive: true });
|
|
1368
|
+
const rootRealPath = await realpath(projectRoot);
|
|
1369
|
+
const distRealPath = await realpath(distPath);
|
|
1370
|
+
if (!isWithin(rootRealPath, distRealPath)) throw new Error("The project dist directory resolves outside the project root");
|
|
1371
|
+
const relativeOutput = relative(distPath, requestedOutput);
|
|
1372
|
+
if (!relativeOutput || relativeOutput === ".." || relativeOutput.startsWith(`..${sep}`) || isAbsolute(relativeOutput)) {
|
|
1373
|
+
throw new Error("--out-dir must resolve to a subdirectory inside dist");
|
|
1374
|
+
}
|
|
1375
|
+
return ensureDirectoryWithoutSymlinks(distRealPath, relativeOutput);
|
|
1376
|
+
}
|
|
1377
|
+
async function resolveProjectAsset(projectRoot, projectRootReal, source) {
|
|
1378
|
+
if (!isSafeRelativePath2(source)) throw new Error(`Asset source is not a safe project-relative path: ${source}`);
|
|
1379
|
+
const candidate = resolve(projectRoot, source);
|
|
1380
|
+
if (!isWithin(projectRoot, candidate)) throw new Error(`Asset source escapes project root: ${source}`);
|
|
1381
|
+
const sourceRealPath = await realpath(candidate);
|
|
1382
|
+
if (!isWithin(projectRootReal, sourceRealPath)) throw new Error(`Asset source resolves outside project root: ${source}`);
|
|
1383
|
+
const info = await stat(sourceRealPath);
|
|
1384
|
+
if (!info.isFile()) throw new Error(`Asset source is not a file: ${source}`);
|
|
1385
|
+
return sourceRealPath;
|
|
1386
|
+
}
|
|
1387
|
+
async function loadCompilerProject(config, projectRoot, projectRootReal) {
|
|
1388
|
+
if (!config || typeof config !== "object") throw new Error("Compiler project config must be a JSON object");
|
|
1389
|
+
const schemaVersion = config.schemaVersion;
|
|
1390
|
+
if (schemaVersion === "1") return config;
|
|
1391
|
+
if (schemaVersion !== "2") throw new Error(`Unsupported project schemaVersion ${JSON.stringify(schemaVersion)}; expected "1" (IR) or "2" (TSX source)`);
|
|
1392
|
+
const sourceProject = config;
|
|
1393
|
+
if (!Array.isArray(sourceProject.components)) throw new Error("Source project components must be an array");
|
|
1394
|
+
const components = await Promise.all(sourceProject.components.map(async (entry, index) => {
|
|
1395
|
+
const prefix = `components[${index}]`;
|
|
1396
|
+
if (!entry || typeof entry.source !== "string" || typeof entry.manifest !== "string") {
|
|
1397
|
+
throw new Error(`${prefix} requires project-relative source and manifest paths`);
|
|
1398
|
+
}
|
|
1399
|
+
if (!entry.source.endsWith(".lite.tsx")) {
|
|
1400
|
+
throw new Error(`${prefix}.source must reference a .lite.tsx authoring file`);
|
|
1401
|
+
}
|
|
1402
|
+
const sourcePath = await resolveProjectAsset(projectRoot, projectRootReal, entry.source);
|
|
1403
|
+
const manifestPath = await resolveProjectAsset(projectRoot, projectRootReal, entry.manifest);
|
|
1404
|
+
let manifest;
|
|
1405
|
+
try {
|
|
1406
|
+
manifest = JSON.parse(await readFile(manifestPath, "utf8"));
|
|
1407
|
+
} catch (cause) {
|
|
1408
|
+
throw new Error(`Unable to read JSON manifest ${entry.manifest}: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
|
|
1409
|
+
}
|
|
1410
|
+
const source = await readFile(sourcePath, "utf8");
|
|
1411
|
+
const implementation = parseMitosisSource(source, { filePath: entry.source, enableBlocksSlots: true });
|
|
1412
|
+
if (entry.exportName && implementation.name !== entry.exportName) {
|
|
1413
|
+
throw new Error(`${prefix}.exportName is ${JSON.stringify(entry.exportName)}, but Mitosis parsed ${JSON.stringify(implementation.name)} from ${entry.source}`);
|
|
1414
|
+
}
|
|
1415
|
+
if (!Array.isArray(entry.styles ?? []) || !Array.isArray(entry.assets ?? [])) {
|
|
1416
|
+
throw new Error(`${prefix}.styles and ${prefix}.assets must be arrays of project-relative file references`);
|
|
1417
|
+
}
|
|
1418
|
+
const sourceDirectory = dirname(entry.source).split(sep).join("/");
|
|
1419
|
+
return {
|
|
1420
|
+
manifest,
|
|
1421
|
+
implementation: { kind: "mitosis", component: implementation },
|
|
1422
|
+
outputDirectory: entry.outputDirectory ?? (sourceDirectory === "." ? "components" : sourceDirectory),
|
|
1423
|
+
styles: entry.styles ?? [],
|
|
1424
|
+
assets: entry.assets ?? []
|
|
1425
|
+
};
|
|
1426
|
+
}));
|
|
1427
|
+
return { schemaVersion: "1", components };
|
|
1428
|
+
}
|
|
1429
|
+
async function writeArtifact(outputRoot, relativePath, contents) {
|
|
1430
|
+
if (!isSafeRelativePath2(relativePath)) throw new Error(`Unsafe generated output path: ${relativePath}`);
|
|
1431
|
+
const parts = relativePath.split("/");
|
|
1432
|
+
const directory = parts.slice(0, -1).join(sep);
|
|
1433
|
+
const parent = await ensureDirectoryWithoutSymlinks(outputRoot, directory);
|
|
1434
|
+
const destination = join(parent, parts.at(-1));
|
|
1435
|
+
try {
|
|
1436
|
+
const existing = await lstat(destination);
|
|
1437
|
+
if (existing.isSymbolicLink() || !existing.isFile()) throw new Error(`Generated output is not a regular file: ${relativePath}`);
|
|
1438
|
+
} catch (cause) {
|
|
1439
|
+
if (cause.code !== "ENOENT") throw cause;
|
|
1440
|
+
}
|
|
1441
|
+
const temporary = `${destination}.designos-${randomUUID()}.tmp`;
|
|
1442
|
+
try {
|
|
1443
|
+
const output = typeof contents === "string" && relativePath.endsWith(".tsx") ? `// @ts-nocheck -- generated Mitosis output; target prop types are not yet preserved.
|
|
1444
|
+
${contents}` : contents;
|
|
1445
|
+
await writeFile(temporary, output);
|
|
1446
|
+
await rename(temporary, destination);
|
|
1447
|
+
} catch (cause) {
|
|
1448
|
+
await rm(temporary, { force: true });
|
|
1449
|
+
throw cause;
|
|
1450
|
+
}
|
|
1451
|
+
}
|
|
1452
|
+
function printDiagnostics(output, diagnostics) {
|
|
1453
|
+
for (const diagnostic of diagnostics) {
|
|
1454
|
+
const formatted = `${diagnostic.severity.toUpperCase()} ${diagnostic.code}${diagnostic.path ? ` (${diagnostic.path})` : ""}: ${diagnostic.message}`;
|
|
1455
|
+
if (diagnostic.severity === "error") output.error(formatted);
|
|
1456
|
+
else output.log(formatted);
|
|
1457
|
+
}
|
|
1458
|
+
}
|
|
1459
|
+
async function runCli(args, output = console, cwd = process.cwd()) {
|
|
1460
|
+
try {
|
|
1461
|
+
const parsed = parseArguments(args);
|
|
1462
|
+
if ("help" in parsed) {
|
|
1463
|
+
output.log(HELP);
|
|
1464
|
+
return 0;
|
|
1465
|
+
}
|
|
1466
|
+
const projectRoot = resolve(cwd, parsed.projectRoot ?? ".");
|
|
1467
|
+
const projectRootReal = await realpath(projectRoot);
|
|
1468
|
+
const configPath = resolve(projectRoot, parsed.config);
|
|
1469
|
+
const configText = await readFile(configPath, "utf8");
|
|
1470
|
+
const projectConfig = JSON.parse(configText);
|
|
1471
|
+
const project = await loadCompilerProject(projectConfig, projectRoot, projectRootReal);
|
|
1472
|
+
const registry = createMitosisCompiler();
|
|
1473
|
+
registry.register(bladeTarget);
|
|
1474
|
+
if (!registry.names().includes(parsed.target)) {
|
|
1475
|
+
throw new Error(`Unknown compiler target ${JSON.stringify(parsed.target)}. Registered targets: ${registry.names().join(", ")}`);
|
|
1476
|
+
}
|
|
1477
|
+
const target = parsed.target;
|
|
1478
|
+
const targetProject = target === "blade" ? {
|
|
1479
|
+
...project,
|
|
1480
|
+
components: project.components.map((component) => ({ ...component, outputDirectory: "components" }))
|
|
1481
|
+
} : project;
|
|
1482
|
+
const validation = validateCompilerProject(targetProject);
|
|
1483
|
+
printDiagnostics(output, validation);
|
|
1484
|
+
if (validation.some((diagnostic) => diagnostic.severity === "error")) return 1;
|
|
1485
|
+
const result = await compileProject(targetProject, registry, { target, targetOptions: parsed.targetOptions });
|
|
1486
|
+
printDiagnostics(output, result.diagnostics);
|
|
1487
|
+
if (result.diagnostics.some((diagnostic) => diagnostic.severity === "error")) return 1;
|
|
1488
|
+
const manifests = Object.fromEntries(targetProject.components.map(({ manifest }) => [manifest.type, manifest]));
|
|
1489
|
+
const manifestRegistryFile = {
|
|
1490
|
+
kind: "registry",
|
|
1491
|
+
path: target === "blade" ? "registry.json" : "manifests.json",
|
|
1492
|
+
contents: `${JSON.stringify(manifests, null, 2)}
|
|
1493
|
+
`
|
|
1494
|
+
};
|
|
1495
|
+
const outputFiles = [...result.files, manifestRegistryFile];
|
|
1496
|
+
const outputArgument = parsed.outDir ?? `dist/designos/${target}`;
|
|
1497
|
+
const outputRoot = await prepareOutputRoot(projectRoot, outputArgument);
|
|
1498
|
+
const outputPaths = /* @__PURE__ */ new Set();
|
|
1499
|
+
for (const file of outputFiles) {
|
|
1500
|
+
const pathKey = file.path.toLowerCase();
|
|
1501
|
+
if (outputPaths.has(pathKey)) throw new Error(`Generated output path collision: ${file.path}`);
|
|
1502
|
+
outputPaths.add(pathKey);
|
|
1503
|
+
}
|
|
1504
|
+
for (const asset of result.assets) {
|
|
1505
|
+
const pathKey = asset.outputPath.toLowerCase();
|
|
1506
|
+
if (outputPaths.has(pathKey)) throw new Error(`Asset output collides with a generated file: ${asset.outputPath}`);
|
|
1507
|
+
outputPaths.add(pathKey);
|
|
1508
|
+
}
|
|
1509
|
+
for (const outputPath of outputPaths) {
|
|
1510
|
+
for (const otherPath of outputPaths) {
|
|
1511
|
+
if (outputPath !== otherPath && otherPath.startsWith(`${outputPath}/`)) {
|
|
1512
|
+
throw new Error(`Generated output path is both a file and a directory: ${outputPath}`);
|
|
1513
|
+
}
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1516
|
+
const assetSources = /* @__PURE__ */ new Map();
|
|
1517
|
+
for (const asset of result.assets) {
|
|
1518
|
+
assetSources.set(asset.outputPath, await resolveProjectAsset(projectRoot, projectRootReal, asset.source));
|
|
1519
|
+
}
|
|
1520
|
+
for (const file of outputFiles) await writeArtifact(outputRoot, file.path, file.contents);
|
|
1521
|
+
for (const [outputPath, sourcePath] of assetSources) {
|
|
1522
|
+
let temporary = "";
|
|
1523
|
+
try {
|
|
1524
|
+
if (!isSafeRelativePath2(outputPath)) throw new Error(`Unsafe asset output path: ${outputPath}`);
|
|
1525
|
+
const relativeParent = dirname(outputPath).split(sep).join("/");
|
|
1526
|
+
const parent = await ensureDirectoryWithoutSymlinks(outputRoot, relativeParent === "." ? "" : relativeParent);
|
|
1527
|
+
const destination = join(parent, outputPath.split("/").at(-1));
|
|
1528
|
+
try {
|
|
1529
|
+
const existing = await lstat(destination);
|
|
1530
|
+
if (existing.isSymbolicLink() || !existing.isFile()) throw new Error(`Asset output is not a regular file: ${outputPath}`);
|
|
1531
|
+
} catch (cause) {
|
|
1532
|
+
if (cause.code !== "ENOENT") throw cause;
|
|
1533
|
+
}
|
|
1534
|
+
temporary = `${destination}.designos-${randomUUID()}.tmp`;
|
|
1535
|
+
await copyFile(sourcePath, temporary);
|
|
1536
|
+
await rename(temporary, destination);
|
|
1537
|
+
} catch (cause) {
|
|
1538
|
+
if (temporary) await rm(temporary, { force: true });
|
|
1539
|
+
throw cause;
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
1542
|
+
output.log(`Compiled ${project.components.length} components for ${target}; wrote ${outputFiles.length} generated files and ${result.assets.length} assets to ${relative(projectRoot, outputRoot)}.`);
|
|
1543
|
+
return 0;
|
|
1544
|
+
} catch (cause) {
|
|
1545
|
+
output.error(cause instanceof Error ? cause.message : String(cause));
|
|
1546
|
+
return 1;
|
|
1547
|
+
}
|
|
1548
|
+
}
|
|
1549
|
+
|
|
1550
|
+
// src/cli.ts
|
|
1551
|
+
void runCli(process.argv.slice(2)).then((exitCode) => {
|
|
1552
|
+
process.exitCode = exitCode;
|
|
1553
|
+
});
|
|
1554
|
+
//# sourceMappingURL=cli.js.map
|