@kohryan/moodui 0.0.12 → 0.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,572 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- // src/validate.ts
4
- function validateMoodUISpec(input) {
5
- const errors = [];
6
- if (!isObject(input)) {
7
- return { ok: false, errors: ["spec must be an object"] };
8
- }
9
- const version = input.version;
10
- if (version !== 1) errors.push("spec.version must be 1");
11
- const root = input.root;
12
- const rootResult = validateNode(root, "spec.root");
13
- if (!rootResult.ok) errors.push(...rootResult.errors);
14
- if (errors.length > 0) return { ok: false, errors };
15
- return { ok: true, value: input };
16
- }
17
- function assertMoodUISpec(input) {
18
- const result = validateMoodUISpec(input);
19
- if (!result.ok) {
20
- const message = ["Invalid MoodUI spec:", ...result.errors.map((e) => `- ${e}`)].join("\n");
21
- throw new Error(message);
22
- }
23
- return result.value;
24
- }
25
- function validateNode(input, path) {
26
- const errors = [];
27
- if (!isObject(input)) return { ok: false, errors: [`${path} must be an object`] };
28
- const type = input.type;
29
- if (!isString(type)) return { ok: false, errors: [`${path}.type must be a string`] };
30
- switch (type) {
31
- case "box": {
32
- const children = input.children;
33
- if (children != null) {
34
- if (!Array.isArray(children)) {
35
- errors.push(`${path}.children must be an array`);
36
- } else {
37
- for (let i = 0; i < children.length; i += 1) {
38
- const child = children[i];
39
- const childResult = validateNode(child, `${path}.children[${i}]`);
40
- if (!childResult.ok) errors.push(...childResult.errors);
41
- }
42
- }
43
- }
44
- break;
45
- }
46
- case "text": {
47
- const props = input.props;
48
- if (!isObject(props)) errors.push(`${path}.props must be an object`);
49
- else if (!isString(props.value)) errors.push(`${path}.props.value must be a string`);
50
- break;
51
- }
52
- case "button": {
53
- const props = input.props;
54
- if (!isObject(props)) errors.push(`${path}.props must be an object`);
55
- else if (!isString(props.label)) errors.push(`${path}.props.label must be a string`);
56
- break;
57
- }
58
- case "input": {
59
- const props = input.props;
60
- if (props != null && !isObject(props)) errors.push(`${path}.props must be an object if provided`);
61
- break;
62
- }
63
- case "image": {
64
- const props = input.props;
65
- if (!isObject(props)) errors.push(`${path}.props must be an object`);
66
- else if (!isString(props.src)) errors.push(`${path}.props.src must be a string`);
67
- break;
68
- }
69
- case "spacer": {
70
- const props = input.props;
71
- if (props != null && !isObject(props)) errors.push(`${path}.props must be an object if provided`);
72
- break;
73
- }
74
- default:
75
- errors.push(`${path}.type must be one of: box | text | button | input | image | spacer`);
76
- }
77
- if (errors.length > 0) return { ok: false, errors };
78
- return { ok: true, value: input };
79
- }
80
- function isObject(value) {
81
- return typeof value === "object" && value !== null && !Array.isArray(value);
82
- }
83
- function isString(value) {
84
- return typeof value === "string";
85
- }
86
-
87
- // src/ai/generateSpec.ts
88
- async function generateMoodUISpec(llm, options) {
89
- const maxAttempts = options.maxAttempts ?? 2;
90
- if (maxAttempts < 1) throw new Error("maxAttempts must be >= 1");
91
- const system = buildSystemPrompt();
92
- const user = buildUserPrompt(options.prompt);
93
- let lastRaw = "";
94
- let lastError = void 0;
95
- for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
96
- const messages = [
97
- { role: "system", content: system },
98
- { role: "user", content: user }
99
- ];
100
- if (attempt > 1) {
101
- messages.push({
102
- role: "user",
103
- content: "Perbaiki output kamu supaya valid JSON dan valid MoodUISpec. Output hanya JSON."
104
- });
105
- }
106
- const raw = await llm.chat({
107
- model: options.model,
108
- temperature: options.temperature,
109
- messages
110
- });
111
- lastRaw = raw;
112
- try {
113
- const json = parseFirstJsonObject(raw);
114
- const spec = assertMoodUISpec(json);
115
- return { spec, raw };
116
- } catch (e) {
117
- lastError = e;
118
- }
119
- }
120
- const message = lastError instanceof Error ? lastError.message : String(lastError);
121
- throw new Error(`Failed to generate valid MoodUISpec. Last error: ${message}
122
-
123
- Raw:
124
- ${lastRaw}`);
125
- }
126
- function buildSystemPrompt() {
127
- return [
128
- "Kamu adalah generator JSON untuk MoodUI.",
129
- "TUGAS: keluarkan 1 objek JSON yang valid, sesuai schema MoodUISpec versi 1.",
130
- "JANGAN keluarkan markdown, JANGAN ada penjelasan, JANGAN pakai backticks.",
131
- "",
132
- "MoodUISpec shape:",
133
- "{",
134
- ' "version": 1,',
135
- ' "root": MoodUINode',
136
- "}",
137
- "",
138
- "MoodUINode union:",
139
- "- box: { type:'box', props?: { direction?, gap?, align?, justify?, wrap?, ...common }, children?: MoodUINode[] }",
140
- "- text: { type:'text', props: { value: string, as?, color?, fontSize?, fontWeight?, textAlign?, ...common } }",
141
- "- button: { type:'button', props: { label: string, variant?, actionId?, disabled?, ...common } }",
142
- "- input: { type:'input', props?: { name?, placeholder?, defaultValue?, ...common } }",
143
- "- image: { type:'image', props: { src: string, alt?, fit?, ...common } }",
144
- "- spacer: { type:'spacer', props?: { size? } }",
145
- "",
146
- "common props:",
147
- "- id, testId, className, style(object), padding, margin, background, borderRadius, width, height",
148
- "",
149
- "Rules:",
150
- "- root wajib ada",
151
- "- minimal pakai box sebagai container utama",
152
- "- semua string pakai double quotes (JSON standard)",
153
- "- jangan pakai function / JS expression apa pun"
154
- ].join("\n");
155
- }
156
- function buildUserPrompt(prompt) {
157
- return ["Buat UI dari request ini:", prompt].join("\n");
158
- }
159
- function parseFirstJsonObject(text) {
160
- const start = text.indexOf("{");
161
- if (start < 0) throw new Error("No JSON object found");
162
- let depth = 0;
163
- let inString = false;
164
- let escaped = false;
165
- for (let i = start; i < text.length; i += 1) {
166
- const ch = text[i];
167
- if (inString) {
168
- if (escaped) {
169
- escaped = false;
170
- } else if (ch === "\\") {
171
- escaped = true;
172
- } else if (ch === '"') {
173
- inString = false;
174
- }
175
- continue;
176
- }
177
- if (ch === '"') {
178
- inString = true;
179
- continue;
180
- }
181
- if (ch === "{") depth += 1;
182
- else if (ch === "}") depth -= 1;
183
- if (depth === 0) {
184
- const candidate = text.slice(start, i + 1);
185
- return JSON.parse(candidate);
186
- }
187
- }
188
- throw new Error("Unterminated JSON object");
189
- }
190
-
191
- // src/react/renderReact.ts
192
- function renderReact(specInput, options = {}) {
193
- const spec = assertMoodUISpec(specInput);
194
- const componentName = options.componentName ?? "MoodUIScreen";
195
- const jsx = renderNode(spec.root, { indent: 2, onActionProp: "onAction" });
196
- return [
197
- 'import * as React from "react";',
198
- "",
199
- "export type MoodUIScreenActionHandler = (actionId: string) => void;",
200
- "",
201
- "export type MoodUIScreenProps = {",
202
- " onAction?: MoodUIScreenActionHandler;",
203
- "};",
204
- "",
205
- `export function ${componentName}(props: MoodUIScreenProps) {`,
206
- " const { onAction } = props;",
207
- " return (",
208
- jsx,
209
- " );",
210
- "}",
211
- ""
212
- ].join("\n");
213
- }
214
- function renderReactJSX(node) {
215
- return renderNode(node, { indent: 0, onActionProp: "onAction" }).trimEnd();
216
- }
217
- function renderNode(node, ctx) {
218
- switch (node.type) {
219
- case "box":
220
- return renderElement("div", node, ctx, () => {
221
- const children = node.children ?? [];
222
- if (children.length === 0) return [];
223
- return children.map((child) => renderNode(child, { ...ctx, indent: ctx.indent + 2 }));
224
- });
225
- case "text": {
226
- const as = node.props?.as ?? "p";
227
- const text = escapeText(node.props?.value ?? "");
228
- return renderElement(as, node, ctx, () => [indent(ctx.indent + 2) + text]);
229
- }
230
- case "button": {
231
- const label = escapeText(node.props?.label ?? "");
232
- const actionId = node.props?.actionId;
233
- return renderElement(
234
- "button",
235
- node,
236
- ctx,
237
- () => [indent(ctx.indent + 2) + label],
238
- actionId ? { onClick: `() => ${ctx.onActionProp}?.(${serializeJsValue(actionId)})` } : void 0
239
- );
240
- }
241
- case "input":
242
- return renderSelfClosingElement("input", node, ctx);
243
- case "image":
244
- return renderSelfClosingElement("img", node, ctx);
245
- case "spacer": {
246
- const size = node.props?.size ?? 8;
247
- const style = { width: normalizeCssValue(size), height: normalizeCssValue(size) };
248
- return renderElement(
249
- "div",
250
- { type: "box", props: { style }, children: [] },
251
- ctx,
252
- () => []
253
- );
254
- }
255
- }
256
- }
257
- function renderElement(tag, node, ctx, renderChildren, extraProps) {
258
- const children = renderChildren();
259
- const propParts = buildProps(tag, node, extraProps);
260
- const open = `<${tag}${propParts.length ? " " + propParts.join(" ") : ""}>`;
261
- const close = `</${tag}>`;
262
- if (children.length === 0) return indent(ctx.indent) + open + close;
263
- return [
264
- indent(ctx.indent) + open,
265
- ...children,
266
- indent(ctx.indent) + close
267
- ].join("\n");
268
- }
269
- function renderSelfClosingElement(tag, node, ctx) {
270
- const propParts = buildProps(tag, node);
271
- return indent(ctx.indent) + `<${tag}${propParts.length ? " " + propParts.join(" ") : ""} />`;
272
- }
273
- function buildProps(tag, node, extraProps) {
274
- const props = node.props ?? {};
275
- const out = [];
276
- if (props.id) out.push(`id=${serializeJsxAttrValue(props.id)}`);
277
- if (props.testId) out.push(`data-testid=${serializeJsxAttrValue(props.testId)}`);
278
- if (props.className) out.push(`className=${serializeJsxAttrValue(props.className)}`);
279
- const computedStyle = computeStyle(tag, node);
280
- const mergedStyle = mergeStyle(computedStyle, props.style) ?? {};
281
- if (tag === "input") {
282
- if (props.name) out.push(`name=${serializeJsxAttrValue(props.name)}`);
283
- if (props.placeholder) out.push(`placeholder=${serializeJsxAttrValue(props.placeholder)}`);
284
- if (props.defaultValue) out.push(`defaultValue=${serializeJsxAttrValue(props.defaultValue)}`);
285
- }
286
- if (tag === "img") {
287
- if (props.src) out.push(`src=${serializeJsxAttrValue(props.src)}`);
288
- if (props.alt) out.push(`alt=${serializeJsxAttrValue(props.alt)}`);
289
- if (props.fit) mergedStyle.objectFit = props.fit;
290
- }
291
- if (Object.keys(mergedStyle).length > 0) {
292
- out.push(`style={(${serializeJsValue(mergedStyle)} as React.CSSProperties)}`);
293
- }
294
- if (extraProps) {
295
- for (const [k, v] of Object.entries(extraProps)) out.push(`${k}={${v}}`);
296
- }
297
- return out;
298
- }
299
- function computeStyle(tag, node) {
300
- const props = node.props ?? {};
301
- const style = {};
302
- if (props.width != null) style.width = normalizeCssValue(props.width);
303
- if (props.height != null) style.height = normalizeCssValue(props.height);
304
- if (props.background != null) style.background = props.background;
305
- if (props.borderRadius != null) style.borderRadius = normalizeCssValue(props.borderRadius);
306
- applySpacing(style, "margin", props.margin);
307
- applySpacing(style, "padding", props.padding);
308
- if (node.type === "box") {
309
- style.display = "flex";
310
- style.flexDirection = normalizeFlexDirection(props.direction) ?? "column";
311
- if (props.gap != null) style.gap = normalizeCssValue(props.gap);
312
- if (props.align != null) style.alignItems = props.align;
313
- if (props.justify != null) style.justifyContent = props.justify;
314
- if (props.wrap != null) style.flexWrap = props.wrap;
315
- }
316
- if (node.type === "text") {
317
- if (props.color != null) style.color = props.color;
318
- if (props.fontSize != null) style.fontSize = normalizeCssValue(props.fontSize);
319
- if (props.fontWeight != null) style.fontWeight = props.fontWeight;
320
- if (props.textAlign != null) style.textAlign = props.textAlign;
321
- if (tag.startsWith("h")) style.margin = 0;
322
- }
323
- if (node.type === "button") {
324
- style.cursor = "pointer";
325
- style.border = "none";
326
- style.padding = "10px 14px";
327
- style.borderRadius = 10;
328
- const variant = props.variant ?? "primary";
329
- if (variant === "primary") {
330
- style.background = "#111827";
331
- style.color = "#ffffff";
332
- } else if (variant === "secondary") {
333
- style.background = "#e5e7eb";
334
- style.color = "#111827";
335
- } else {
336
- style.background = "transparent";
337
- style.color = "#111827";
338
- }
339
- if (props.disabled) {
340
- style.opacity = 0.6;
341
- style.cursor = "not-allowed";
342
- }
343
- }
344
- if (node.type === "input") {
345
- style.padding = "10px 12px";
346
- style.borderRadius = 10;
347
- style.border = "1px solid #d1d5db";
348
- style.outline = "none";
349
- }
350
- if (node.type === "image") {
351
- if (props.fit != null) style.objectFit = props.fit;
352
- style.maxWidth = "100%";
353
- }
354
- return style;
355
- }
356
- function applySpacing(style, kind, value) {
357
- if (value == null) return;
358
- if (typeof value === "number" || typeof value === "string") {
359
- style[kind] = normalizeCssValue(value);
360
- return;
361
- }
362
- if (typeof value !== "object" || Array.isArray(value)) return;
363
- const v = value;
364
- const all = v.all;
365
- const x = v.x;
366
- const y = v.y;
367
- if (all != null) style[kind] = normalizeCssValue(all);
368
- if (x != null) {
369
- style[`${kind}Left`] = normalizeCssValue(x);
370
- style[`${kind}Right`] = normalizeCssValue(x);
371
- }
372
- if (y != null) {
373
- style[`${kind}Top`] = normalizeCssValue(y);
374
- style[`${kind}Bottom`] = normalizeCssValue(y);
375
- }
376
- if (v.top != null) style[`${kind}Top`] = normalizeCssValue(v.top);
377
- if (v.right != null) style[`${kind}Right`] = normalizeCssValue(v.right);
378
- if (v.bottom != null) style[`${kind}Bottom`] = normalizeCssValue(v.bottom);
379
- if (v.left != null) style[`${kind}Left`] = normalizeCssValue(v.left);
380
- }
381
- function mergeStyle(a, b) {
382
- if (!a && !b) return void 0;
383
- if (!a) return b;
384
- if (!b) return a;
385
- return { ...a, ...b };
386
- }
387
- function normalizeCssValue(value) {
388
- if (typeof value === "number") return value;
389
- if (typeof value === "string") return value;
390
- return value;
391
- }
392
- function normalizeFlexDirection(value) {
393
- if (value === "row" || value === "column") return value;
394
- if (value === "horizontal") return "row";
395
- if (value === "vertical") return "column";
396
- return void 0;
397
- }
398
- function serializeJsxAttrValue(value) {
399
- return `{${serializeJsValue(value)}}`;
400
- }
401
- function serializeJsValue(value) {
402
- if (value === null) return "null";
403
- if (value === void 0) return "undefined";
404
- if (typeof value === "string") return JSON.stringify(value);
405
- if (typeof value === "number" || typeof value === "boolean") return String(value);
406
- if (Array.isArray(value)) return `[${value.map(serializeJsValue).join(", ")}]`;
407
- if (typeof value === "object") {
408
- const entries = Object.entries(value).filter(([, v]) => v !== void 0).map(([k, v]) => `${safeObjectKey(k)}: ${serializeJsValue(v)}`);
409
- return `{ ${entries.join(", ")} }`;
410
- }
411
- return "undefined";
412
- }
413
- function safeObjectKey(key) {
414
- if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key)) return key;
415
- return JSON.stringify(key);
416
- }
417
- function escapeText(value) {
418
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
419
- }
420
- function indent(spaces) {
421
- return " ".repeat(spaces);
422
- }
423
-
424
- // src/llm/gemini.ts
425
- function createGeminiClient(options) {
426
- const baseUrl = (options.baseUrl ?? "https://generativelanguage.googleapis.com").replace(/\/+$/, "");
427
- const fetchFn = options.fetchFn ?? fetch;
428
- const apiKey = options.apiKey;
429
- return {
430
- async chat(req) {
431
- const { systemInstruction, contents } = toGeminiContents(req.messages);
432
- const url = `${baseUrl}/v1beta/models/${encodeURIComponent(req.model)}:generateContent?key=${encodeURIComponent(apiKey)}`;
433
- const res = await fetchFn(url, {
434
- method: "POST",
435
- headers: { "content-type": "application/json" },
436
- body: JSON.stringify({
437
- ...systemInstruction ? { systemInstruction } : {},
438
- contents,
439
- generationConfig: req.temperature == null ? void 0 : { temperature: req.temperature }
440
- })
441
- });
442
- if (!res.ok) {
443
- const text2 = await safeReadText(res);
444
- throw new Error(`Gemini generateContent failed (${res.status}): ${text2}`);
445
- }
446
- const json = await res.json();
447
- const parts = json?.candidates?.[0]?.content?.parts;
448
- const text = Array.isArray(parts) ? parts.map((p) => typeof p?.text === "string" ? p.text : "").join("") : void 0;
449
- if (typeof text !== "string" || text.length === 0) throw new Error("Gemini response missing candidates[0].content.parts[].text");
450
- return text;
451
- }
452
- };
453
- }
454
- function toGeminiContents(messages) {
455
- const systemTexts = messages.filter((m) => m.role === "system").map((m) => m.content).filter((t) => t.trim().length > 0);
456
- const systemInstruction = systemTexts.length > 0 ? { role: "system", parts: [{ text: systemTexts.join("\n") }] } : void 0;
457
- const contents = messages.filter((m) => m.role !== "system").map((m) => ({
458
- role: m.role === "assistant" ? "model" : "user",
459
- parts: [{ text: m.content }]
460
- }));
461
- if (contents.length === 0) {
462
- contents.push({ role: "user", parts: [{ text: "" }] });
463
- }
464
- return { systemInstruction, contents };
465
- }
466
- async function safeReadText(res) {
467
- try {
468
- return await res.text();
469
- } catch {
470
- return "";
471
- }
472
- }
473
-
474
- // src/llm/ollama.ts
475
- function createOllamaClient(options = {}) {
476
- const baseUrl = options.baseUrl ?? "http://localhost:11434";
477
- const fetchFn = options.fetchFn ?? fetch;
478
- return {
479
- async chat(req) {
480
- const res = await fetchFn(`${baseUrl}/api/chat`, {
481
- method: "POST",
482
- headers: { "content-type": "application/json" },
483
- body: JSON.stringify({
484
- model: req.model,
485
- messages: req.messages,
486
- stream: false,
487
- options: req.temperature == null ? void 0 : { temperature: req.temperature }
488
- })
489
- });
490
- if (!res.ok) {
491
- const text = await safeReadText2(res);
492
- throw new Error(`Ollama chat failed (${res.status}): ${text}`);
493
- }
494
- const json = await res.json();
495
- const content = json?.message?.content;
496
- if (typeof content !== "string") throw new Error("Ollama response missing message.content");
497
- return content;
498
- }
499
- };
500
- }
501
- async function safeReadText2(res) {
502
- try {
503
- return await res.text();
504
- } catch {
505
- return "";
506
- }
507
- }
508
-
509
- // src/llm/openaiCompatible.ts
510
- function createOpenAICompatibleClient(options) {
511
- const fetchFn = options.fetchFn ?? fetch;
512
- const baseUrl = options.baseUrl.replace(/\/+$/, "");
513
- const apiKey = options.apiKey;
514
- const defaultHeaders = options.defaultHeaders ?? {};
515
- return {
516
- async chat(req) {
517
- const res = await fetchFn(`${baseUrl}/v1/chat/completions`, {
518
- method: "POST",
519
- headers: {
520
- "content-type": "application/json",
521
- authorization: `Bearer ${apiKey}`,
522
- ...defaultHeaders
523
- },
524
- body: JSON.stringify({
525
- model: req.model,
526
- messages: req.messages,
527
- temperature: req.temperature
528
- })
529
- });
530
- if (!res.ok) {
531
- const text = await safeReadText3(res);
532
- throw new Error(`Chat completion failed (${res.status}): ${text}`);
533
- }
534
- const json = await res.json();
535
- const content = json?.choices?.[0]?.message?.content;
536
- if (typeof content !== "string") throw new Error("Response missing choices[0].message.content");
537
- return content;
538
- }
539
- };
540
- }
541
- async function safeReadText3(res) {
542
- try {
543
- return await res.text();
544
- } catch {
545
- return "";
546
- }
547
- }
548
-
549
- // src/ai/generateReactFromPrompt.ts
550
- async function generateReactFromPrompt(options) {
551
- const llm = options.provider === "gemini" ? createGeminiClient({ apiKey: options.apiKey, baseUrl: options.baseUrl }) : options.provider === "ollama" ? createOllamaClient({ baseUrl: options.baseUrl }) : createOpenAICompatibleClient({ apiKey: options.apiKey, baseUrl: options.baseUrl });
552
- const { spec, raw } = await generateMoodUISpec(llm, {
553
- model: options.model,
554
- prompt: options.prompt,
555
- temperature: options.temperature,
556
- maxAttempts: options.maxAttempts
557
- });
558
- const code = renderReact(spec, { componentName: options.componentName });
559
- return { spec, raw, code };
560
- }
561
-
562
- export {
563
- validateMoodUISpec,
564
- assertMoodUISpec,
565
- generateMoodUISpec,
566
- renderReact,
567
- renderReactJSX,
568
- createGeminiClient,
569
- createOllamaClient,
570
- createOpenAICompatibleClient,
571
- generateReactFromPrompt
572
- };
package/dist/cli.d.ts DELETED
@@ -1 +0,0 @@
1
- #!/usr/bin/env node