@hugex/artifact 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +18 -0
- package/README.md +104 -2
- package/dist/catalog.d.ts +49 -0
- package/dist/dev-prefix.d.ts +5 -0
- package/dist/do/ArtifactDO.d.ts +98 -0
- package/dist/do/ArtifactIndexDO.d.ts +18 -0
- package/dist/do/index-upsert.d.ts +6 -0
- package/dist/do/meta-migrate.d.ts +12 -0
- package/dist/do/ora-index.d.ts +17 -0
- package/dist/hash.d.ts +36 -0
- package/dist/host-route.d.ts +40 -0
- package/dist/host.d.ts +9 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +875 -0
- package/dist/inject.d.ts +29 -0
- package/dist/internal.d.ts +10 -0
- package/dist/limits.d.ts +20 -0
- package/dist/mcp/access.d.ts +18 -0
- package/dist/mcp/auth.d.ts +32 -0
- package/dist/mcp/authz.d.ts +50 -0
- package/dist/mcp/index.d.ts +12 -0
- package/dist/mcp/tools.d.ts +43 -0
- package/dist/rpc.d.ts +5 -0
- package/dist/runtime/artifact-app-source.d.ts +7 -0
- package/dist/sql.d.ts +17 -0
- package/dist/templates.d.ts +7 -0
- package/dist/types.d.ts +209 -0
- package/dist/url.d.ts +8 -0
- package/dist/validate.d.ts +21 -0
- package/dist/version.d.ts +2 -0
- package/package.json +26 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,875 @@
|
|
|
1
|
+
import{DurableObject as wt}from"cloudflare:workers";var ut=[{name:"preact",version:"10.26.9",url:"https://cdn.jsdelivr.net/npm/preact@10.26.9/dist/preact.module.js",integrity:"sha384-bfDY8fBZIvxiN2bm+Hfu4kLhDIK6bILDXuJyNbRH9vBOppbq9Y34RpdsuTqBRrBY",kind:"module",specifiers:{preact:{url:"https://cdn.jsdelivr.net/npm/preact@10.26.9/dist/preact.module.js",integrity:"sha384-bfDY8fBZIvxiN2bm+Hfu4kLhDIK6bILDXuJyNbRH9vBOppbq9Y34RpdsuTqBRrBY"}}},{name:"preact/hooks",version:"10.26.9",url:"https://cdn.jsdelivr.net/npm/preact@10.26.9/hooks/dist/hooks.module.js",integrity:"sha384-/u2Sb+nVb2XqG9qrJYekxbyFs0/bsv7pKBkIOJph+3oLPojhunv0x6HB7s9CX6qY",kind:"module",needs:["preact"],specifiers:{"preact/hooks":{url:"https://cdn.jsdelivr.net/npm/preact@10.26.9/hooks/dist/hooks.module.js",integrity:"sha384-/u2Sb+nVb2XqG9qrJYekxbyFs0/bsv7pKBkIOJph+3oLPojhunv0x6HB7s9CX6qY"}}},{name:"htm",version:"3.1.1",url:"https://cdn.jsdelivr.net/npm/htm@3.1.1/dist/htm.mjs",integrity:"sha384-k7/PyxcXOQ/zfJq1v0TM/CcBLQ2m2NzGg2tfHehdgJGqcY7RBwIP4Ye+ssG+QK1I",kind:"module",specifiers:{htm:{url:"https://cdn.jsdelivr.net/npm/htm@3.1.1/dist/htm.mjs",integrity:"sha384-k7/PyxcXOQ/zfJq1v0TM/CcBLQ2m2NzGg2tfHehdgJGqcY7RBwIP4Ye+ssG+QK1I"}}},{name:"chart.js",version:"4.5.0",url:"https://cdn.jsdelivr.net/npm/chart.js@4.5.0/auto/auto.js",integrity:"sha384-SPJMGfZhNscpRQiHkalYnhScM+JCCM3NtTgy+jN+/+M92LMBNsvgOQvzwUPACEZp",kind:"module",needs:["@kurkle/color"],specifiers:{"chart.js":{url:"https://cdn.jsdelivr.net/npm/chart.js@4.5.0/auto/auto.js",integrity:"sha384-SPJMGfZhNscpRQiHkalYnhScM+JCCM3NtTgy+jN+/+M92LMBNsvgOQvzwUPACEZp"},"chart.js/auto":{url:"https://cdn.jsdelivr.net/npm/chart.js@4.5.0/auto/auto.js",integrity:"sha384-SPJMGfZhNscpRQiHkalYnhScM+JCCM3NtTgy+jN+/+M92LMBNsvgOQvzwUPACEZp"}}},{name:"@kurkle/color",version:"0.3.4",url:"https://cdn.jsdelivr.net/npm/@kurkle/color@0.3.4/dist/color.esm.js",integrity:"sha384-kK5x4nQngGCMIIrcv6LmSK5ba7lpydhAr3wZ9V6bc3fRupiPKsUaVqGc7JJcvBLO",kind:"module",specifiers:{"@kurkle/color":{url:"https://cdn.jsdelivr.net/npm/@kurkle/color@0.3.4/dist/color.esm.js",integrity:"sha384-kK5x4nQngGCMIIrcv6LmSK5ba7lpydhAr3wZ9V6bc3fRupiPKsUaVqGc7JJcvBLO"}}},{name:"@tanstack/table-core",version:"8.21.3",url:"https://cdn.jsdelivr.net/npm/@tanstack/table-core@8.21.3/build/lib/index.mjs",integrity:"sha384-Oeyk4Vy5JibRgD5ZDBROMna6z5cNEBh0cp/UmLxitQdY/fIzg4AqHmo5e/UbTMEs",kind:"module",specifiers:{"@tanstack/table-core":{url:"https://cdn.jsdelivr.net/npm/@tanstack/table-core@8.21.3/build/lib/index.mjs",integrity:"sha384-Oeyk4Vy5JibRgD5ZDBROMna6z5cNEBh0cp/UmLxitQdY/fIzg4AqHmo5e/UbTMEs"}}},{name:"@tailwindcss/browser",version:"4.1.16",url:"https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4.1.16/dist/index.global.js",integrity:"sha384-CupcnpRPGKuEGGXTLCJOB/LtgZz1+ak44ldRJNT1XaLZdfrrG9MHDos5mKjLZx32",kind:"classic",specifiers:{}}],xe=new Map(ut.map(t=>[t.name,t]));function ke(){let t=xe.get("@tailwindcss/browser");if(!t)throw new Error("catalog missing @tailwindcss/browser");return{url:t.url,integrity:t.integrity}}function M(t){let e=[],r=[],n=new Set,s=(a,u)=>{if(n.has(a))return;let l=xe.get(a);if(!l){u&&e.push(`unknown lib: ${a}`),n.add(a);return}n.add(a),r.push(l);for(let f of l.needs??[])s(f,!1)};for(let a of t)s(a,!0);let o={},i={};for(let a of r)for(let[u,l]of Object.entries(a.specifiers))o[u]=l.url,i[l.url]=l.integrity;return{imports:o,integrity:i,warnings:e}}var g={fileBytes:1e6,versionBytes:5e6,supervisorBytes:2e8,logRows:1e3,logMessageBytes:2048,browserLogsPerSecond:20,pathMaxChars:200,healthTimeoutMs:5e3},V="2025-05-15";async function T(t){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return[...new Uint8Array(e)].map(r=>r.toString(16).padStart(2,"0")).join("")}function B(t,e){let r=new TextEncoder,n=r.encode(t),s=r.encode(e),o=Math.max(n.length,s.length),i=n.length^s.length;for(let a=0;a<o;a++)i|=(n[a]??0)^(s[a]??0);return i===0}function x(t){return new TextEncoder().encode(t).length}var dt=/\/k\/[^/]+\//g;function R(t){return t.replace(dt,"/k/***/")}function oe(t,e){if(e<=0)return"";let r=new TextEncoder().encode(t);if(r.length<=e)return t;let n=e;for(;n>0&&(r[n]&192)===128;)n-=1;let s=new TextDecoder().decode(r.subarray(0,n));for(;x(s)>e&&s.length>0;)s=s.slice(0,-1);return s}async function we(t){let e=t instanceof Map?[...t.entries()]:Object.entries(t);e.sort((n,s)=>n[0]<s[0]?-1:n[0]>s[0]?1:0);let r=[];for(let[n,s]of e)r.push([n,await T(s)]);return T(JSON.stringify(r))}function ie(t,e){if(t.size!==e.size)return!1;for(let[r,n]of t)if(e.get(r)!==n)return!1;return!0}function ae(t=V){return{compatibilityDate:t,mainModule:"server.js",globalOutbound:null,env:{}}}async function Se(t){let e=["artifact-app.js",t.appSource,"server.js",t.serverJs,t.pkgVersion,t.compatibilityDate,JSON.stringify(t.config)].join("\0");return T(e)}function ce(){let t=new Uint8Array(18);crypto.getRandomValues(t);let e="";for(let r of t)e+=String.fromCharCode(r);return btoa(e).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}function h(t){if(!t)return"unknown error";if(typeof t=="string")return t;if(t instanceof Error)return(t.message||t.stack||String(t)).slice(0,2e3);let e=t,r=e.message||e.stack||String(t);return String(r).slice(0,2e3)}function X(t){return/SQLITE_FULL|database or disk is full/i.test(h(t))}function le(t,e){let r=Promise.resolve(t);r.catch(()=>{});let n,s=new Promise((o,i)=>{n=setTimeout(()=>i(new Error("timeout")),e)});return Promise.race([r,s]).finally(()=>{n!==void 0&&clearTimeout(n)})}var ft=["default-src 'none'","script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net https://esm.sh https://unpkg.com","style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://esm.sh https://unpkg.com","img-src 'self' data: blob:","font-src 'self' data:","connect-src 'self'","base-uri 'self'","form-action 'self'"],pt=/^(?:https?:\/\/)(?:\[[0-9a-fA-F:.]+\]|[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*)(?::\d{1,5})?$/;function gt(t){let e=(t??"").split(/\s+/).filter(r=>pt.test(r));return e.length===0?"frame-ancestors 'none'":`frame-ancestors ${e.join(" ")}`}function Le(t){return[...ft,gt(t)].join("; ")}var an=Le(),mt=`@theme {
|
|
2
|
+
--font-sans: "PolySans", ui-sans-serif, system-ui, sans-serif;
|
|
3
|
+
--font-inter: "Inter", ui-sans-serif, system-ui, sans-serif;
|
|
4
|
+
|
|
5
|
+
--color-primary-50: var(--theme-primary-50);
|
|
6
|
+
--color-primary-100: var(--theme-primary-100);
|
|
7
|
+
--color-primary-200: var(--theme-primary-200);
|
|
8
|
+
--color-primary-300: var(--theme-primary-300);
|
|
9
|
+
--color-primary-400: var(--theme-primary-400);
|
|
10
|
+
--color-primary-500: var(--theme-primary-500);
|
|
11
|
+
--color-primary-600: var(--theme-primary-600);
|
|
12
|
+
--color-primary-700: var(--theme-primary-700);
|
|
13
|
+
--color-primary-800: var(--theme-primary-800);
|
|
14
|
+
--color-primary-900: var(--theme-primary-900);
|
|
15
|
+
|
|
16
|
+
--color-secondary-50: var(--theme-secondary-50);
|
|
17
|
+
--color-secondary-100: var(--theme-secondary-100);
|
|
18
|
+
--color-secondary-200: var(--theme-secondary-200);
|
|
19
|
+
--color-secondary-300: var(--theme-secondary-300);
|
|
20
|
+
--color-secondary-400: var(--theme-secondary-400);
|
|
21
|
+
--color-secondary-500: var(--theme-secondary-500);
|
|
22
|
+
--color-secondary-600: var(--theme-secondary-600);
|
|
23
|
+
--color-secondary-700: var(--theme-secondary-700);
|
|
24
|
+
--color-secondary-800: var(--theme-secondary-800);
|
|
25
|
+
--color-secondary-900: var(--theme-secondary-900);
|
|
26
|
+
|
|
27
|
+
--color-warning-50: var(--theme-warning-50);
|
|
28
|
+
--color-warning-100: var(--theme-warning-100);
|
|
29
|
+
--color-warning-200: var(--theme-warning-200);
|
|
30
|
+
--color-warning-300: var(--theme-warning-300);
|
|
31
|
+
--color-warning-400: var(--theme-warning-400);
|
|
32
|
+
--color-warning-500: var(--theme-warning-500);
|
|
33
|
+
--color-warning-600: var(--theme-warning-600);
|
|
34
|
+
--color-warning-700: var(--theme-warning-700);
|
|
35
|
+
--color-warning-800: var(--theme-warning-800);
|
|
36
|
+
--color-warning-900: var(--theme-warning-900);
|
|
37
|
+
|
|
38
|
+
--color-danger-50: var(--theme-danger-50);
|
|
39
|
+
--color-danger-100: var(--theme-danger-100);
|
|
40
|
+
--color-danger-200: var(--theme-danger-200);
|
|
41
|
+
--color-danger-300: var(--theme-danger-300);
|
|
42
|
+
--color-danger-400: var(--theme-danger-400);
|
|
43
|
+
--color-danger-500: var(--theme-danger-500);
|
|
44
|
+
--color-danger-600: var(--theme-danger-600);
|
|
45
|
+
--color-danger-700: var(--theme-danger-700);
|
|
46
|
+
--color-danger-800: var(--theme-danger-800);
|
|
47
|
+
--color-danger-900: var(--theme-danger-900);
|
|
48
|
+
|
|
49
|
+
--color-bg-base: var(--theme-bg-base);
|
|
50
|
+
--color-bg-surface: var(--theme-bg-surface);
|
|
51
|
+
--color-border-subtle: var(--theme-border-subtle);
|
|
52
|
+
--color-text-base: var(--theme-text-base);
|
|
53
|
+
--color-text-muted: var(--theme-text-muted);
|
|
54
|
+
}`,ht=`:root,
|
|
55
|
+
[data-theme="light"] {
|
|
56
|
+
--theme-primary-50: #FAF5FF;
|
|
57
|
+
--theme-primary-100: #F0E0FF;
|
|
58
|
+
--theme-primary-200: #E2C2FF;
|
|
59
|
+
--theme-primary-300: #D4A3FF;
|
|
60
|
+
--theme-primary-400: #C27DFF;
|
|
61
|
+
--theme-primary-500: #AB63FF;
|
|
62
|
+
--theme-primary-600: #944FE0;
|
|
63
|
+
--theme-primary-700: #7A3BC2;
|
|
64
|
+
--theme-primary-800: #5F2D99;
|
|
65
|
+
--theme-primary-900: #452070;
|
|
66
|
+
|
|
67
|
+
--theme-secondary-50: #EFF6FF;
|
|
68
|
+
--theme-secondary-100: #DBEAFE;
|
|
69
|
+
--theme-secondary-200: #BFDBFE;
|
|
70
|
+
--theme-secondary-300: #93C5FD;
|
|
71
|
+
--theme-secondary-400: #60A5FA;
|
|
72
|
+
--theme-secondary-500: #3B82F6;
|
|
73
|
+
--theme-secondary-600: #2563EB;
|
|
74
|
+
--theme-secondary-700: #1D4ED8;
|
|
75
|
+
--theme-secondary-800: #1E40AF;
|
|
76
|
+
--theme-secondary-900: #1E3A8A;
|
|
77
|
+
|
|
78
|
+
--theme-warning-50: #FEFCE8;
|
|
79
|
+
--theme-warning-100: #FEF9C3;
|
|
80
|
+
--theme-warning-200: #FEF08A;
|
|
81
|
+
--theme-warning-300: #FDE047;
|
|
82
|
+
--theme-warning-400: #FACC15;
|
|
83
|
+
--theme-warning-500: #EAB308;
|
|
84
|
+
--theme-warning-600: #CA8A04;
|
|
85
|
+
--theme-warning-700: #A16207;
|
|
86
|
+
--theme-warning-800: #854D0E;
|
|
87
|
+
--theme-warning-900: #713F12;
|
|
88
|
+
|
|
89
|
+
--theme-danger-50: #FEF2F2;
|
|
90
|
+
--theme-danger-100: #FEE2E2;
|
|
91
|
+
--theme-danger-200: #FECACA;
|
|
92
|
+
--theme-danger-300: #FCA5A5;
|
|
93
|
+
--theme-danger-400: #F87171;
|
|
94
|
+
--theme-danger-500: #EF4444;
|
|
95
|
+
--theme-danger-600: #DC2626;
|
|
96
|
+
--theme-danger-700: #B91C1C;
|
|
97
|
+
--theme-danger-800: #991B1B;
|
|
98
|
+
--theme-danger-900: #7F1D1D;
|
|
99
|
+
|
|
100
|
+
--theme-bg-base: #EFEBF5;
|
|
101
|
+
--theme-bg-surface: #F9F8FC;
|
|
102
|
+
--theme-border-subtle: #dad3ed;
|
|
103
|
+
--theme-text-base: #2A2438;
|
|
104
|
+
--theme-text-muted: #7E7492;
|
|
105
|
+
}`,yt=`<script type="module">
|
|
106
|
+
const baseHref = document.querySelector("base")?.href || location.href;
|
|
107
|
+
const wsUrl = new URL("__hx/ws", baseHref);
|
|
108
|
+
wsUrl.protocol = location.protocol === "https:" ? "wss:" : "ws:";
|
|
109
|
+
const ws = new WebSocket(wsUrl.href);
|
|
110
|
+
ws.onmessage = (ev) => {
|
|
111
|
+
try {
|
|
112
|
+
const msg = JSON.parse(ev.data);
|
|
113
|
+
if (msg && msg.type === "reload") location.reload();
|
|
114
|
+
} catch (e) {}
|
|
115
|
+
};
|
|
116
|
+
function redact(text) {
|
|
117
|
+
return String(text == null ? "" : text).replace(/\\/k\\/[^/]+\\//g, "/k/***/");
|
|
118
|
+
}
|
|
119
|
+
function report(message) {
|
|
120
|
+
try {
|
|
121
|
+
if (ws.readyState === WebSocket.OPEN) {
|
|
122
|
+
ws.send(JSON.stringify({ type: "log", level: "error", message: redact(message).slice(0, 2000) }));
|
|
123
|
+
}
|
|
124
|
+
} catch (e) {}
|
|
125
|
+
}
|
|
126
|
+
window.onerror = (message, source, lineno, colno) => {
|
|
127
|
+
report([redact(message), redact(source), lineno, colno].join(":"));
|
|
128
|
+
};
|
|
129
|
+
window.addEventListener("unhandledrejection", (ev) => {
|
|
130
|
+
const reason = ev.reason;
|
|
131
|
+
const text = reason && reason.stack ? reason.stack : (reason && reason.message ? reason.message : String(reason));
|
|
132
|
+
report(redact(text));
|
|
133
|
+
});
|
|
134
|
+
</script>`;function ue(t){return t.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<")}function bt(t,e){let r=e.baseHref.endsWith("/")?e.baseHref:`${e.baseHref}/`,n=JSON.stringify({imports:e.imports,integrity:e.integrity},null,2).replaceAll("<","\\u003c"),s=`<base href="${ue(r)}">
|
|
135
|
+
<script>globalThis.process={env:{NODE_ENV:"production"}};</script>
|
|
136
|
+
<script type="importmap">
|
|
137
|
+
${n}
|
|
138
|
+
</script>
|
|
139
|
+
<script src="${ue(e.tailwindUrl)}" integrity="${ue(e.tailwindIntegrity)}" crossorigin="anonymous"></script>
|
|
140
|
+
<style>
|
|
141
|
+
${ht}
|
|
142
|
+
</style>
|
|
143
|
+
<style type="text/tailwindcss">
|
|
144
|
+
${mt}
|
|
145
|
+
</style>
|
|
146
|
+
${yt}`,o=/<head[^>]*>/i;return o.test(t)?t.replace(o,i=>`${i}
|
|
147
|
+
${s}`):t.includes("</head>")?t.replace("</head>",`${s}
|
|
148
|
+
</head>`):s+t}function Ie(t,e,r){let n=M(r),s=ke();return bt(t,{baseHref:e,imports:n.imports,integrity:n.integrity,tailwindUrl:s.url,tailwindIntegrity:s.integrity})}function _e(t){switch(t.includes(".")?t.slice(t.lastIndexOf(".")+1).toLowerCase():""){case"html":return"text/html; charset=utf-8";case"js":case"mjs":return"text/javascript; charset=utf-8";case"css":return"text/css; charset=utf-8";case"json":case"map":return"application/json; charset=utf-8";case"svg":return"image/svg+xml";case"xhtml":case"xht":return"application/xhtml+xml";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"gif":return"image/gif";case"webp":return"image/webp";case"wasm":return"application/wasm";case"woff2":return"font/woff2";case"txt":return"text/plain; charset=utf-8";default:return"application/octet-stream"}}var vt=["image/svg+xml","application/xhtml+xml"];function At(t){let e=t.toLowerCase();return vt.some(r=>e.includes(r))}function k(t,e){let r=new Headers(t.headers);r.set("Referrer-Policy","no-referrer"),r.set("Cache-Control","no-store"),r.set("X-Content-Type-Options","nosniff"),r.delete("Set-Cookie");let n=r.get("content-type")??"",s=Le(e);At(n)&&(s+="; sandbox"),r.set("Content-Security-Policy",s);let o="webSocket"in t?t.webSocket??void 0:void 0;return new Response(t.body,{status:t.status,statusText:t.statusText,headers:r,webSocket:o})}var Et=`function isSingleSelect(input) {
|
|
149
|
+
if (typeof input !== "string") return false;
|
|
150
|
+
const sql = input;
|
|
151
|
+
let i = 0;
|
|
152
|
+
const n = sql.length;
|
|
153
|
+
|
|
154
|
+
function skipWsAndComments() {
|
|
155
|
+
while (i < n) {
|
|
156
|
+
const c = sql[i];
|
|
157
|
+
if (c === " " || c === "\\t" || c === "\\n" || c === "\\r" || c === "\\f") {
|
|
158
|
+
i += 1;
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
if (c === "-" && sql[i + 1] === "-") {
|
|
162
|
+
i += 2;
|
|
163
|
+
while (i < n && sql[i] !== "\\n") i += 1;
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
if (c === "/" && sql[i + 1] === "*") {
|
|
167
|
+
const end = sql.indexOf("*/", i + 2);
|
|
168
|
+
if (end < 0) return false;
|
|
169
|
+
i = end + 2;
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
return true;
|
|
173
|
+
}
|
|
174
|
+
return true;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
if (!skipWsAndComments()) return false;
|
|
178
|
+
if (i >= n || !/^select\\b/i.test(sql.slice(i))) return false;
|
|
179
|
+
i += 6;
|
|
180
|
+
|
|
181
|
+
let sawSemicolon = false;
|
|
182
|
+
while (i < n) {
|
|
183
|
+
if (sawSemicolon) {
|
|
184
|
+
if (!skipWsAndComments()) return false;
|
|
185
|
+
return i >= n;
|
|
186
|
+
}
|
|
187
|
+
const c = sql[i];
|
|
188
|
+
if (c === "'" || c === "\\"" || c === "\`") {
|
|
189
|
+
const quote = c;
|
|
190
|
+
i += 1;
|
|
191
|
+
let closed = false;
|
|
192
|
+
while (i < n) {
|
|
193
|
+
if (sql[i] === quote) {
|
|
194
|
+
if (sql[i + 1] === quote) {
|
|
195
|
+
i += 2;
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
i += 1;
|
|
199
|
+
closed = true;
|
|
200
|
+
break;
|
|
201
|
+
}
|
|
202
|
+
i += 1;
|
|
203
|
+
}
|
|
204
|
+
if (!closed) return false;
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
if (c === "-" && sql[i + 1] === "-") {
|
|
208
|
+
i += 2;
|
|
209
|
+
while (i < n && sql[i] !== "\\n") i += 1;
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
if (c === "/" && sql[i + 1] === "*") {
|
|
213
|
+
const end = sql.indexOf("*/", i + 2);
|
|
214
|
+
if (end < 0) return false;
|
|
215
|
+
i = end + 2;
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
if (c === ";") {
|
|
219
|
+
sawSemicolon = true;
|
|
220
|
+
i += 1;
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
223
|
+
i += 1;
|
|
224
|
+
}
|
|
225
|
+
return true;
|
|
226
|
+
}`;function Ne(t){if(typeof t!="string")return!1;let e=t,r=0,n=e.length;function s(){for(;r<n;){let i=e[r];if(i===" "||i===" "||i===`
|
|
227
|
+
`||i==="\r"||i==="\f"){r+=1;continue}if(i==="-"&&e[r+1]==="-"){for(r+=2;r<n&&e[r]!==`
|
|
228
|
+
`;)r+=1;continue}if(i==="/"&&e[r+1]==="*"){let a=e.indexOf("*/",r+2);if(a<0)return!1;r=a+2;continue}return!0}return!0}if(!s()||r>=n||!/^select\b/i.test(e.slice(r)))return!1;r+=6;let o=!1;for(;r<n;){if(o)return s()?r>=n:!1;let i=e[r];if(i==="'"||i==='"'||i==="`"){let a=i;r+=1;let u=!1;for(;r<n;){if(e[r]===a){if(e[r+1]===a){r+=2;continue}r+=1,u=!0;break}r+=1}if(!u)return!1;continue}if(i==="-"&&e[r+1]==="-"){for(r+=2;r<n&&e[r]!==`
|
|
229
|
+
`;)r+=1;continue}if(i==="/"&&e[r+1]==="*"){let a=e.indexOf("*/",r+2);if(a<0)return!1;r=a+2;continue}if(i===";"){o=!0,r+=1;continue}r+=1}return!0}function Oe(){return`export ${Et}`}var de=`import { DurableObject } from "cloudflare:workers";
|
|
230
|
+
|
|
231
|
+
${Oe()}
|
|
232
|
+
|
|
233
|
+
function plainRows(rows) {
|
|
234
|
+
return rows.map((row) => {
|
|
235
|
+
const out = {};
|
|
236
|
+
for (const [key, value] of Object.entries(row)) {
|
|
237
|
+
out[key] = typeof value === "bigint" ? Number(value) : value;
|
|
238
|
+
}
|
|
239
|
+
return out;
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export class ArtifactApp extends DurableObject {
|
|
244
|
+
async __hxHealth() {
|
|
245
|
+
this.ctx.storage.sql.exec("SELECT 1");
|
|
246
|
+
return { ok: true };
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
async __hxQuery(sql) {
|
|
250
|
+
if (!isSingleSelect(sql)) {
|
|
251
|
+
throw new Error("only a single SELECT statement is allowed");
|
|
252
|
+
}
|
|
253
|
+
return plainRows(this.ctx.storage.sql.exec(sql).toArray());
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
`;var N="x-hx-artifact-key",O="x-hx-artifact-base";var Tt=[{name:"index_dirty",ddl:"ALTER TABLE meta ADD COLUMN index_dirty INTEGER NOT NULL DEFAULT 0"},{name:"index_retry",ddl:"ALTER TABLE meta ADD COLUMN index_retry INTEGER NOT NULL DEFAULT 0"},{name:"ora_dirty",ddl:"ALTER TABLE meta ADD COLUMN ora_dirty INTEGER NOT NULL DEFAULT 0"},{name:"ora_retry",ddl:"ALTER TABLE meta ADD COLUMN ora_retry INTEGER NOT NULL DEFAULT 0"},{name:"revision",ddl:"ALTER TABLE meta ADD COLUMN revision INTEGER NOT NULL DEFAULT 0"}];function Rt(t){return t.length===0?null:t.includes("revision")?"UPDATE meta SET revision = 1, index_dirty = 1, ora_dirty = 1 WHERE id = 1":"UPDATE meta SET index_dirty = 1, ora_dirty = 1 WHERE id = 1"}function Ce(t,e){let r=[];for(let s of Tt)e.includes(s.name)||(t(s.ddl),r.push(s.name));let n=Rt(r);return n&&t(n),r}async function Pe(t,e,r=fetch,n=5e3){var a,u;let s=(a=t.HX_ORA_URL)==null?void 0:a.trim().replace(/\/$/,"");if(!s)return{ok:!1,error:"HX_ORA_URL missing"};let o=new AbortController,i=setTimeout(()=>o.abort(),n);try{let l=await r(`${s}/internal/artifacts/${encodeURIComponent(e.uuid)}`,{method:"PUT",headers:{Authorization:((u=t.HX_API_KEY)==null?void 0:u.trim())??"","Content-Type":"application/json"},body:JSON.stringify(e),signal:o.signal});if(!l.ok)return{ok:!1,error:`hx-ora ${l.status}`};let f;try{f=await l.json()}catch{return{ok:!1,error:"invalid json"}}return!f||typeof f!="object"||f.ok!==!0?{ok:!1,error:"hx-ora rejected index"}:{ok:!0}}catch(l){return{ok:!1,error:l instanceof Error?l.message:"fetch failed"}}finally{clearTimeout(i)}}var xt=/^[a-z0-9][a-z0-9-]{1,47}$/,kt=new Set(["mcp","k","api","app","index","assets","static"]);function I(t){return typeof t!="string"||!xt.test(t)?"invalid slug":kt.has(t)?"reserved slug":null}function U(t){return typeof t!="string"||t.length===0||t.length>g.pathMaxChars||t.startsWith("/")||t.includes("\\")||t.includes("\0")||t.split("/").some(r=>r===""||r==="."||r==="..")?"invalid path":null}function W(t){let e;try{e=JSON.parse(t)}catch{return{ok:!1,error:"artifact.json is not json"}}if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,error:"artifact.json must be an object"};let r=e;return typeof r.title!="string"?{ok:!1,error:"artifact.json title must be a string"}:!Array.isArray(r.libs)||r.libs.some(n=>typeof n!="string")?{ok:!1,error:"artifact.json libs must be a string array"}:{ok:!0,manifest:{title:r.title,libs:r.libs}}}var fe="0.1.0";var St=/not found|does not exist|no facet|unknown facet|not currently/i,pe=class extends wt{activationGen=0;constructor(e,r){super(e,r),e.blockConcurrencyWhile(()=>this.boot())}async alarm(){await this.flushIndex()}async create(e){let r=await this.ctx.blockConcurrencyWhile(async()=>{if(this.readMeta())return null;let n=I(e.slug);if(n)throw new Error(n);let s=ce(),o=new Date().toISOString();this.ctx.storage.sql.exec(`INSERT INTO meta (
|
|
257
|
+
id, uuid, slug, title, tenant, org, owner, grp, public,
|
|
258
|
+
key_plain, key_hash, key_gen, active_version, created_at, updated_at, revision,
|
|
259
|
+
index_dirty, index_retry, ora_dirty, ora_retry
|
|
260
|
+
) VALUES (1, ?, ?, ?, ?, ?, ?, 'none', 0, ?, ?, 1, NULL, ?, ?, 1, 1, 0, 1, 0)`,crypto.randomUUID(),e.slug,e.title,e.tenant,e.org,e.owner,s,await T(s),o,o);let i=this.readMeta();if(!i)throw new Error("create failed");return{meta:this.toPublic(i),key:s}});return await this.flushIndex(),r}async getMeta(){let e=this.readMeta();return e?this.toPublic(e):null}async getAccess(){let e=this.readMeta();return e?{public:e.public,key:e.public?null:e.keyPlain}:null}async readFiles(e){let r=this.readMeta();if(!r)return null;let n=(e==null?void 0:e.version)??r.activeVersion;if(!n||!this.rows("SELECT id FROM version WHERE id = ?",n)[0])return null;if(e!=null&&e.path){let o=this.readFile(n,e.path);return o==null?[]:[{path:e.path,content:o}]}return this.rows("SELECT path, content FROM file WHERE version = ? ORDER BY path",n).map(o=>({path:String(o.path),content:String(o.content)}))}async write(e){let r;try{r=await this.ctx.blockConcurrencyWhile(()=>this.writeLocked(e))}catch(n){X(n)?r={ok:!1,code:"limit",error:"SQLITE_FULL"}:r={ok:!1,code:"invalid",error:R(h(n))}}return await this.flushIndex(),r}async rollback(e){let r;try{r=await this.ctx.blockConcurrencyWhile(()=>this.rollbackLocked(e))}catch(n){X(n)?r={ok:!1,code:"limit",error:"SQLITE_FULL"}:r={ok:!1,code:"invalid",error:R(h(n))}}return await this.flushIndex(),r}async settings(e){let r=await this.ctx.blockConcurrencyWhile(async()=>{let n=this.readMeta();if(!n)return null;let s=n.keyPlain,o=n.keyHash,i=n.keyGen,a=n.group,u=n.public;typeof e.group=="string"&&(a=e.group),typeof e.public=="boolean"&&(u=e.public);let l=e.rotateKey===!0;l&&(s=ce(),o=await T(s),i+=1);let f=new Date().toISOString();this.ctx.storage.sql.exec("UPDATE meta SET grp = ?, public = ?, key_plain = ?, key_hash = ?, key_gen = ?, updated_at = ?, revision = revision + 1, index_dirty = 1, index_retry = 0, ora_dirty = 1, ora_retry = 0 WHERE id = 1",a,u?1:0,s,o,i,f),l&&this.closeStaleSockets(i);let p=this.readMeta();if(!p)return null;let m=l||!p.public;return{meta:this.toPublic(p),key:m?p.keyPlain:null}});return await this.flushIndex(),r}async versions(e){if(!this.readMeta())return null;let r=Fe(e==null?void 0:e.limit,100);return this.rows("SELECT id, runtime_id, author, message, state, created_at, error FROM version ORDER BY created_at DESC, id DESC LIMIT ?",r).map(n=>this.toVersion(n))}async logs(e){if(!this.readMeta())return null;let r=Fe(e==null?void 0:e.limit,100);return(e!=null&&e.source?this.rows("SELECT ts, source, level, message, version FROM log WHERE source = ? ORDER BY id DESC LIMIT ?",e.source,r):this.rows("SELECT ts, source, level, message, version FROM log ORDER BY id DESC LIMIT ?",r)).map(s=>({ts:String(s.ts),source:String(s.source),level:String(s.level),message:String(s.message),version:s.version==null?null:String(s.version)}))}async query(e){let r=this.readMeta();if(!r)return{ok:!1,error:"not found"};if(!r.activeVersion)return{ok:!1,error:"no active version"};let n=this.readFile(r.activeVersion,"server.js");if(n==null)return{ok:!1,error:"no server"};let s=await this.ensureFacet(n);if(!s.ok)return{ok:!1,error:R(s.error)};try{return{ok:!0,rows:await s.facet.__hxQuery(e)}}catch(o){return{ok:!1,error:R(h(o))}}}async fetch(e){try{let r=this.readMeta();if(!r)return this.notFound();let n=e.headers.get(N)??"";if(!await this.allow(r,n))return this.notFound();let s=new URL(e.url),o=s.pathname;try{o=decodeURIComponent(o)}catch{return this.notFound()}if(o.includes("\\")||o.split("/").includes(".."))return this.notFound();let i=o.replace(/^\/+/,"");return i==="__hx/ws"?this.acceptReload(e,r.keyGen):r.activeVersion?i==="api"||i.startsWith("api/")?await this.forwardApi(e,s,i,r):i===""||i==="index.html"?this.serveHtml(e,r):i==="server.js"||i==="artifact.json"?this.notFound():U(i)?this.notFound():this.serveFile(r,i):this.notFound()}catch(r){let n=this.readMeta(),s=R(h(r));return this.writeLog("server","error",s,(n==null?void 0:n.activeVersion)??null),this.plain(s,500)}}async webSocketMessage(e,r){let n=typeof r=="string"?r:new TextDecoder().decode(r),s;try{s=JSON.parse(n)}catch{return}if(!s||typeof s!="object")return;let o=s;if(o.type!=="log")return;let i=o.level==="debug"||o.level==="info"||o.level==="warn"||o.level==="error"?o.level:"error";if(!this.browserLogAllowed())return;let a=this.readMeta();this.writeLog("browser",i,String(o.message??""),(a==null?void 0:a.activeVersion)??null)}async webSocketClose(e,r,n,s){}async webSocketError(e,r){}async boot(){this.migrate(),this.recoverProvisional(),await this.flushIndex();let e=this.readMeta();if(!(e!=null&&e.activeVersion))return;let r=this.readFile(e.activeVersion,"server.js");if(r==null)return;let n=await this.ensureFacet(r);n.ok||this.writeLog("server","error",`boot failed: ${n.error}`,e.activeVersion)}migrate(){this.ctx.storage.sql.exec(`CREATE TABLE IF NOT EXISTS meta (
|
|
261
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
262
|
+
uuid TEXT NOT NULL,
|
|
263
|
+
slug TEXT NOT NULL,
|
|
264
|
+
title TEXT NOT NULL,
|
|
265
|
+
tenant TEXT NOT NULL,
|
|
266
|
+
org TEXT NOT NULL,
|
|
267
|
+
owner TEXT NOT NULL,
|
|
268
|
+
grp TEXT NOT NULL,
|
|
269
|
+
public INTEGER NOT NULL DEFAULT 0,
|
|
270
|
+
key_plain TEXT NOT NULL,
|
|
271
|
+
key_hash TEXT NOT NULL,
|
|
272
|
+
key_gen INTEGER NOT NULL DEFAULT 1,
|
|
273
|
+
active_version TEXT,
|
|
274
|
+
created_at TEXT NOT NULL,
|
|
275
|
+
updated_at TEXT NOT NULL,
|
|
276
|
+
revision INTEGER NOT NULL DEFAULT 0,
|
|
277
|
+
index_dirty INTEGER NOT NULL DEFAULT 0,
|
|
278
|
+
index_retry INTEGER NOT NULL DEFAULT 0,
|
|
279
|
+
ora_dirty INTEGER NOT NULL DEFAULT 0,
|
|
280
|
+
ora_retry INTEGER NOT NULL DEFAULT 0
|
|
281
|
+
)`);let e=this.rows("PRAGMA table_info(meta)").map(r=>String(r.name));Ce(r=>{this.ctx.storage.sql.exec(r)},e),this.ctx.storage.sql.exec(`CREATE TABLE IF NOT EXISTS file (
|
|
282
|
+
version TEXT NOT NULL,
|
|
283
|
+
path TEXT NOT NULL,
|
|
284
|
+
content TEXT NOT NULL,
|
|
285
|
+
hash TEXT NOT NULL,
|
|
286
|
+
PRIMARY KEY (version, path)
|
|
287
|
+
)`),this.ctx.storage.sql.exec(`CREATE TABLE IF NOT EXISTS version (
|
|
288
|
+
id TEXT PRIMARY KEY,
|
|
289
|
+
runtime_id TEXT,
|
|
290
|
+
author TEXT,
|
|
291
|
+
message TEXT,
|
|
292
|
+
created_at TEXT NOT NULL,
|
|
293
|
+
state TEXT NOT NULL,
|
|
294
|
+
error TEXT
|
|
295
|
+
)`),this.ctx.storage.sql.exec(`CREATE TABLE IF NOT EXISTS log (
|
|
296
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
297
|
+
ts TEXT NOT NULL,
|
|
298
|
+
source TEXT NOT NULL,
|
|
299
|
+
level TEXT NOT NULL,
|
|
300
|
+
message TEXT NOT NULL,
|
|
301
|
+
version TEXT
|
|
302
|
+
)`)}recoverProvisional(){let e=this.rows("SELECT id FROM version WHERE state = 'provisional'");for(let r of e)this.ctx.storage.sql.exec("UPDATE version SET state = 'fallida', error = ? WHERE id = ?","provisional marked fallida on startup",r.id),this.writeLog("system","error","provisional marked fallida on startup",String(r.id))}async writeLocked(e){let r=this.readMeta();if(!r)return{ok:!1,code:"invalid",error:"not found"};let n=r.activeVersion;if((e.baseVersion??null)!==n)return{ok:!1,code:"conflict",activeVersion:n};if(!Array.isArray(e.changes))return{ok:!1,code:"invalid",error:"changes must be an array"};if(typeof e.message!="string")return{ok:!1,code:"invalid",error:"message must be a string"};if(typeof e.author!="string")return{ok:!1,code:"invalid",error:"author must be a string"};let s=n?this.filesFor(n):new Map,o=_t(s,e.changes);if(!o.ok)return{ok:!1,code:o.code,error:o.error};let i=o.files;if(It(i)>g.versionBytes)return{ok:!1,code:"limit",error:"version exceeds 5 MB"};if(ie(i,s))return{ok:!1,code:"invalid",error:"no changes"};let u=i.get("artifact.json");if(u==null)return{ok:!1,code:"invalid",error:"artifact.json is required"};let l=W(u);if(!l.ok)return{ok:!1,code:"invalid",error:l.error};if(!i.has("index.html"))return{ok:!1,code:"invalid",error:"index.html is required"};let f=M(l.manifest.libs).warnings,p=await we(i),m=this.rows("SELECT id FROM version WHERE id = ?",p)[0],E=i.get("server.js")??null,at=E==null?null:await this.runtimeId(E);if(m){if(!ie(this.filesFor(p),i))return{ok:!1,code:"invalid",error:"version id already exists with different files"}}else{let _=new Map;for(let[F,lt]of i)_.set(F,await T(lt));try{this.persistNewVersion(p,at,e.author,e.message,i,_)}catch(F){if(X(F))return{ok:!1,code:"limit",error:"SQLITE_FULL"};if(/storage limit exceeded/i.test(h(F)))return{ok:!1,code:"limit",error:"storage limit exceeded"};throw F}}let se=this.beginActivation(),H;try{H=await this.activateCode(E,n,se)}finally{se.stop()}if(!this.activationLive(se)||!H.ok){let _=R(H.ok?"timeout":H.error);return m||this.markFailed(p,_),this.writeLog("server","error",_,p),{ok:!1,code:"failed",version:p,state:"fallida",error:_}}this.promote(p,n,l.manifest.title);let ct=this.readMeta()??r;return this.broadcastReload(p,ct.keyGen),{ok:!0,version:p,state:"activa",warnings:f}}async rollbackLocked(e){let r=this.readMeta();if(!r)return{ok:!1,code:"invalid",error:"not found"};if(typeof e.version!="string"||e.version==="")return{ok:!1,code:"invalid",error:"version is required"};let n=this.rows("SELECT id, state FROM version WHERE id = ?",e.version)[0];if(!n)return{ok:!1,code:"invalid",error:"version not found"};let s=String(n.state);if(s==="fallida"||s==="provisional")return{ok:!1,code:"invalid",error:"cannot activate that version"};if(e.version===r.activeVersion)return{ok:!1,code:"invalid",error:"no changes"};let o=this.filesFor(e.version),i=o.get("artifact.json");if(i==null)return{ok:!1,code:"invalid",error:"artifact.json is required"};let a=W(i);if(!a.ok)return{ok:!1,code:"invalid",error:a.error};if(!o.has("index.html"))return{ok:!1,code:"invalid",error:"index.html is required"};let u=o.get("server.js")??null,l=this.beginActivation(),f;try{f=await this.activateCode(u,r.activeVersion,l)}finally{l.stop()}if(!this.activationLive(l)||!f.ok){let E=R(f.ok?"timeout":f.error);return this.writeLog("server","error",E,e.version),{ok:!1,code:"failed",version:e.version,state:"fallida",error:E}}this.promote(e.version,r.activeVersion,a.manifest.title);let p=this.readMeta()??r;this.broadcastReload(e.version,p.keyGen);let m=M(a.manifest.libs).warnings;return{ok:!0,version:e.version,state:"activa",warnings:m}}beginActivation(){let e=++this.activationGen,r=Date.now()+g.healthTimeoutMs,n=setTimeout(()=>{this.activationGen===e&&(this.activationGen+=1)},g.healthTimeoutMs);return{gen:e,deadline:r,stop:()=>clearTimeout(n)}}activationLive(e){return this.activationGen===e.gen&&Date.now()<=e.deadline}async activateCode(e,r,n){if(!this.activationLive(n))return{ok:!1,error:"timeout"};if(e==null){let o=this.abortFacet();return o.ok?this.activationLive(n)?{ok:!0}:{ok:!1,error:"timeout"}:o}let s=await this.swapFacet(e,n);if(s.ok)return this.activationLive(n)?{ok:!0}:{ok:!1,error:"timeout"};if(r&&this.activationLive(n)){let o=this.readFile(r,"server.js");if(o!=null){let i=await this.swapFacet(o,n);i.ok||this.writeLog("server","error",`restore failed: ${i.error}`,r)}else this.activationLive(n)&&this.abortFacet()}return s}persistNewVersion(e,r,n,s,o,i){let a=new Date().toISOString(),u=Lt(o,i),l=n.slice(0,320),f=s.slice(0,2e3);this.ctx.storage.transactionSync(()=>{if(this.ctx.storage.sql.databaseSize+u>g.supervisorBytes)throw new Error("storage limit exceeded");this.ctx.storage.sql.exec(`INSERT INTO version (id, runtime_id, author, message, created_at, state, error)
|
|
303
|
+
VALUES (?, ?, ?, ?, ?, 'provisional', NULL)`,e,r,l,f,a);for(let[m,E]of o)this.ctx.storage.sql.exec("INSERT INTO file (version, path, content, hash) VALUES (?, ?, ?, ?)",e,m,E,i.get(m)??"")})}markFailed(e,r){this.ctx.storage.sql.exec("UPDATE version SET state = 'fallida', error = ? WHERE id = ?",oe(R(r),g.logMessageBytes),e)}promote(e,r,n){let s=new Date().toISOString();this.ctx.storage.transactionSync(()=>{r&&r!==e&&this.ctx.storage.sql.exec("UPDATE version SET state = 'anterior' WHERE id = ? AND state = 'activa'",r),this.ctx.storage.sql.exec("UPDATE version SET state = 'activa', error = NULL WHERE id = ?",e),this.ctx.storage.sql.exec("UPDATE meta SET active_version = ?, title = ?, updated_at = ?, revision = revision + 1, index_dirty = 1, index_retry = 0, ora_dirty = 1, ora_retry = 0 WHERE id = 1",e,n,s)})}async runtimeId(e){let r=ae();return Se({appSource:de,serverJs:e,pkgVersion:fe,compatibilityDate:V,config:r})}async loadApp(e){if(!this.env.LOADER||typeof this.env.LOADER.get!="function")return{ok:!1,error:"LOADER unavailable"};let r=this.readMeta();if(!r)return{ok:!1,error:"not found"};let n=ae(),s=await this.runtimeId(e),o={compatibilityDate:n.compatibilityDate,mainModule:n.mainModule,modules:{"server.js":e,"artifact-app.js":de},globalOutbound:null,env:{}};try{return{ok:!0,appClass:this.env.LOADER.get(`artifact:${r.uuid}:${s}`,()=>o).getDurableObjectClass("App")}}catch(i){return{ok:!1,error:h(i)}}}facetOf(e){return this.ctx.facets.get("app",()=>({class:e}))}async ensureFacet(e){if(!this.ctx.facets||typeof this.ctx.facets.get!="function")return{ok:!1,error:"ctx.facets unavailable"};let r=await this.loadApp(e);if(!r.ok)return r;try{let n=this.facetOf(r.appClass);return await le(n.__hxHealth(),g.healthTimeoutMs),{ok:!0,facet:n}}catch(n){return{ok:!1,error:h(n)}}}async swapFacet(e,r){if(!this.activationLive(r))return{ok:!1,error:"timeout"};if(!this.ctx.facets||typeof this.ctx.facets.get!="function")return{ok:!1,error:"ctx.facets unavailable"};let n=await this.loadApp(e);if(!n.ok)return n;if(!this.activationLive(r))return{ok:!1,error:"timeout"};let s=this.abortFacet();if(!s.ok)return s;let o=r.deadline-Date.now();if(o<=0||!this.activationLive(r))return{ok:!1,error:"timeout"};try{let i=this.facetOf(n.appClass);return await le(i.__hxHealth(),o),this.activationLive(r)?{ok:!0}:{ok:!1,error:"timeout"}}catch(i){return{ok:!1,error:h(i)}}}abortFacet(){try{return this.ctx.facets.abort("app",new Error("swap")),{ok:!0}}catch(e){return St.test(h(e))?{ok:!0}:{ok:!1,error:`abort: ${h(e)}`}}}async allow(e,r){if(!r)return e.public;let n=await T(r);return B(n,e.keyHash)}acceptReload(e,r){var i;if(((i=e.headers.get("Upgrade"))==null?void 0:i.toLowerCase())!=="websocket")return this.notFound();let n=new WebSocketPair,s=n[0],o=n[1];return o.serializeAttachment({keyGen:r}),this.ctx.acceptWebSocket(o),this.secure(new Response(null,{status:101,webSocket:s}))}serveHtml(e,r){if(!r.activeVersion)return this.notFound();let n=this.readFile(r.activeVersion,"index.html");if(n==null)return this.notFound();let s=this.readFile(r.activeVersion,"artifact.json"),o=[];if(s!=null){let l=W(s);l.ok&&(o=l.manifest.libs)}let i=e.headers.get(O)||"/",a=i.endsWith("/")?i:`${i}/`,u=Ie(n,a,o);return this.secure(new Response(u,{status:200,headers:{"content-type":"text/html; charset=utf-8"}}))}serveFile(e,r){if(!e.activeVersion)return this.notFound();let n=this.readFile(e.activeVersion,r);return n==null?this.notFound():this.secure(new Response(n,{status:200,headers:{"content-type":_e(r)}}))}async forwardApi(e,r,n,s){if(!s.activeVersion)return this.notFound();let o=this.readFile(s.activeVersion,"server.js");if(o==null)return this.notFound();let i=await this.ensureFacet(o);if(!i.ok)return this.plain("facet unavailable",502);let a=new Headers(e.headers);a.delete("cookie"),a.delete(N),a.delete(O);let u=e.method!=="GET"&&e.method!=="HEAD",l=await i.facet.fetch(new Request(`http://artifact.local/${n}${r.search}`,{method:e.method,headers:a,body:u?e.body:void 0}));return this.secure(new Response(l.body,{status:l.status,statusText:l.statusText,headers:l.headers}))}broadcastReload(e,r){let n=JSON.stringify({type:"reload",version:e});for(let s of this.ctx.getWebSockets()){let o=s.deserializeAttachment();if(!(!o||Number(o.keyGen)!==r))try{s.send(n)}catch{}}}closeStaleSockets(e){for(let r of this.ctx.getWebSockets()){let n=r.deserializeAttachment();if(!(n&&Number(n.keyGen)===e))try{r.close(1e3,"key rotated")}catch{}}}browserLogAllowed(){let e=new Date(Date.now()-1e3).toISOString(),r=this.rows("SELECT COUNT(*) AS n FROM log WHERE source = 'browser' AND ts >= ?",e)[0];return Number((r==null?void 0:r.n)??0)<g.browserLogsPerSecond}writeLog(e,r,n,s){try{this.ctx.storage.sql.exec("INSERT INTO log (ts, source, level, message, version) VALUES (?, ?, ?, ?, ?)",new Date().toISOString(),e,r,oe(R(String(n)),g.logMessageBytes),s),this.ctx.storage.sql.exec(`DELETE FROM log WHERE id <= (
|
|
304
|
+
SELECT id FROM log ORDER BY id DESC LIMIT 1 OFFSET ?
|
|
305
|
+
)`,g.logRows)}catch{}}async flushIndex(){await this.flushLocalIndex(),await this.flushOraIndex(),await this.armIndexAlarm()}async flushLocalIndex(){let e=this.readMeta();if(e!=null&&e.indexDirty)try{let r=this.env.ARTIFACT_INDEX;await r.get(r.idFromName("index")).put(this.indexEntry(e)),this.ctx.storage.sql.exec("UPDATE meta SET index_dirty = 0, index_retry = 0 WHERE id = 1 AND revision = ? AND index_dirty = 1",e.revision)}catch(r){this.writeLog("system","error",`index sync failed: ${h(r)}`,e.activeVersion),this.ctx.storage.sql.exec("UPDATE meta SET index_retry = index_retry + 1 WHERE id = 1 AND index_dirty = 1 AND revision = ?",e.revision)}}async flushOraIndex(){var n;let e=this.readMeta();if(!(e!=null&&e.oraDirty)||!((n=this.env.HX_ORA_URL)!=null&&n.trim()))return;let r=await Pe(this.env,this.indexEntry(e));if(r.ok){this.ctx.storage.sql.exec("UPDATE meta SET ora_dirty = 0, ora_retry = 0 WHERE id = 1 AND revision = ? AND ora_dirty = 1",e.revision);return}this.writeLog("system","error",`ora sync failed: ${r.error}`,e.activeVersion),this.ctx.storage.sql.exec("UPDATE meta SET ora_retry = ora_retry + 1 WHERE id = 1 AND ora_dirty = 1 AND revision = ?",e.revision)}async armIndexAlarm(){var i;let e=this.readMeta(),r=!!(e!=null&&e.indexDirty),n=!!(e!=null&&e.oraDirty&&((i=this.env.HX_ORA_URL)!=null&&i.trim()));if(!r&&!n){try{await this.ctx.storage.deleteAlarm()}catch{}return}let s=Math.max(r?e.indexRetry:0,n?e.oraRetry:0),o=Math.min(6e4,1e3*2**Math.max(0,s-1));await this.ctx.storage.setAlarm(Date.now()+o)}indexEntry(e){return{uuid:e.uuid,slug:e.slug,title:e.title,org:e.org,owner:e.owner,group:e.group,public:e.public,activeVersion:e.activeVersion,updatedAt:e.updatedAt,revision:e.revision}}readMeta(){let e=this.rows("SELECT * FROM meta WHERE id = 1")[0];return e?{uuid:String(e.uuid),slug:String(e.slug),title:String(e.title),tenant:String(e.tenant),org:String(e.org),owner:String(e.owner),group:String(e.grp),public:Number(e.public)===1,keyGen:Number(e.key_gen),activeVersion:e.active_version==null?null:String(e.active_version),createdAt:String(e.created_at),updatedAt:String(e.updated_at),revision:Number(e.revision??0),keyPlain:String(e.key_plain),keyHash:String(e.key_hash),indexDirty:Number(e.index_dirty)===1,indexRetry:Number(e.index_retry??0),oraDirty:Number(e.ora_dirty)===1,oraRetry:Number(e.ora_retry??0)}:null}toPublic(e){return{uuid:e.uuid,slug:e.slug,title:e.title,tenant:e.tenant,org:e.org,owner:e.owner,group:e.group,public:e.public,keyGen:e.keyGen,activeVersion:e.activeVersion,createdAt:e.createdAt,updatedAt:e.updatedAt,revision:e.revision}}secure(e){return k(e,this.env.ARTIFACT_FRAME_ANCESTORS)}toVersion(e){return{id:String(e.id),runtimeId:e.runtime_id==null?null:String(e.runtime_id),author:e.author==null?"":String(e.author),message:e.message==null?"":String(e.message),state:String(e.state),createdAt:String(e.created_at),error:e.error==null?null:String(e.error)}}filesFor(e){let r=new Map;for(let n of this.rows("SELECT path, content FROM file WHERE version = ?",e))r.set(String(n.path),String(n.content));return r}readFile(e,r){let n=this.rows("SELECT content FROM file WHERE version = ? AND path = ?",e,r)[0];return n?String(n.content):null}rows(e,...r){return this.ctx.storage.sql.exec(e,...r).toArray()}notFound(){return this.plain("not found",404)}plain(e,r){return this.secure(new Response(e,{status:r,headers:{"content-type":"text/plain; charset=utf-8"}}))}};function Lt(t,e){var n;let r=128;for(let[s,o]of t)r+=x(s)+x(o)+(((n=e.get(s))==null?void 0:n.length)??64)+48;return r}function It(t){let e=0;for(let r of t.values())e+=x(r);return e}function Fe(t,e){return t==null||!Number.isFinite(t)?e:Math.min(g.logRows,Math.max(1,Math.floor(t)))}function _t(t,e){let r=new Map(t);for(let n of e){if(!n||typeof n.path!="string")return{ok:!1,code:"invalid",error:"invalid path"};let s=U(n.path);if(s)return{ok:!1,code:"invalid",error:s};if(n.content===null){r.delete(n.path);continue}if(typeof n.content!="string")return{ok:!1,code:"invalid",error:"content must be a string or null"};if(x(n.content)>g.fileBytes)return{ok:!1,code:"limit",error:`file exceeds 1 MB: ${n.path}`};r.set(n.path,n.content)}return{ok:!0,files:r}}import{DurableObject as Nt}from"cloudflare:workers";var ge=`INSERT INTO artifact (slug, uuid, title, org, owner, grp, public, active_version, updated_at, revision)
|
|
306
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
307
|
+
ON CONFLICT(slug) DO UPDATE SET
|
|
308
|
+
uuid = excluded.uuid,
|
|
309
|
+
title = excluded.title,
|
|
310
|
+
org = excluded.org,
|
|
311
|
+
owner = excluded.owner,
|
|
312
|
+
grp = excluded.grp,
|
|
313
|
+
public = excluded.public,
|
|
314
|
+
active_version = excluded.active_version,
|
|
315
|
+
updated_at = excluded.updated_at,
|
|
316
|
+
revision = excluded.revision
|
|
317
|
+
WHERE excluded.revision > artifact.revision`;var me=class extends Nt{constructor(e,r){super(e,r),e.blockConcurrencyWhile(async()=>{this.ctx.storage.sql.exec(`CREATE TABLE IF NOT EXISTS artifact (
|
|
318
|
+
slug TEXT PRIMARY KEY,
|
|
319
|
+
uuid TEXT NOT NULL,
|
|
320
|
+
title TEXT NOT NULL,
|
|
321
|
+
org TEXT NOT NULL,
|
|
322
|
+
owner TEXT NOT NULL,
|
|
323
|
+
grp TEXT NOT NULL,
|
|
324
|
+
public INTEGER NOT NULL DEFAULT 0,
|
|
325
|
+
active_version TEXT,
|
|
326
|
+
updated_at TEXT NOT NULL,
|
|
327
|
+
revision INTEGER NOT NULL DEFAULT 0
|
|
328
|
+
)`),this.ctx.storage.sql.exec("PRAGMA table_info(artifact)").toArray().some(s=>String(s.name)==="revision")||this.ctx.storage.sql.exec("ALTER TABLE artifact ADD COLUMN revision INTEGER NOT NULL DEFAULT 0")})}async put(e){this.ctx.storage.sql.exec(ge,e.slug,e.uuid,e.title,e.org,e.owner,e.group,e.public?1:0,e.activeVersion,e.updatedAt,e.revision)}async remove(e){this.ctx.storage.sql.exec("DELETE FROM artifact WHERE slug = ?",e)}async get(e){let r=this.rows("SELECT * FROM artifact WHERE slug = ?",e)[0];return r?this.toEntry(r):null}async list(e){let r=(e==null?void 0:e.owner)??null;return(r?this.rows("SELECT * FROM artifact WHERE owner = ? ORDER BY updated_at DESC, slug ASC",r):this.rows("SELECT * FROM artifact ORDER BY updated_at DESC, slug ASC")).map(s=>this.toEntry(s))}rows(e,...r){return this.ctx.storage.sql.exec(e,...r).toArray()}toEntry(e){return{uuid:String(e.uuid),slug:String(e.slug),title:String(e.title),org:String(e.org),owner:String(e.owner),group:String(e.grp),public:Number(e.public)===1,activeVersion:e.active_version==null?null:String(e.active_version),updatedAt:String(e.updated_at),revision:Number(e.revision??0)}}};var Ot=new Set(["localhost","127.0.0.1","[::1]"]);function G(t,e){if(e&&Ot.has(t))return e}function Ct(t){if(!t)return null;let e=t.endsWith("/")?t.slice(0,-1):t;return!e.startsWith("/")||e.includes("//")?null:e}function Me(t){let e=Ct(t.devPrefix),r=t.pathname,n="";if(!t.terminal){if(!e)return{kind:"passthrough"};if(t.pathname!==e&&!t.pathname.startsWith(`${e}/`))return{kind:"passthrough"};n=e,r=t.pathname.slice(e.length)||"/",r.startsWith("/")||(r=`/${r}`)}if(r==="/mcp"||r.startsWith("/mcp/"))return{kind:"mcp"};let s=r.split("/").filter(Boolean),o=s[0];if(!o||I(o))return{kind:"not-found"};let i="",a;if(s[1]==="k"){let p=s[2];if(!p)return{kind:"not-found"};try{i=decodeURIComponent(p)}catch{return{kind:"not-found"}}if(a=s.slice(3),a.length===0&&!t.pathname.endsWith("/"))return{kind:"redirect",location:`${t.pathname}/${t.search}`}}else if(a=s.slice(1),a.length===0&&!t.pathname.endsWith("/"))return{kind:"redirect",location:`${t.pathname}/${t.search}`};let u=a.length===0?"/":`/${a.join("/")}`,l=i?`k/${encodeURIComponent(i)}/`:"",f=`${n}/${o}/${l}`;return{kind:"forward",slug:o,key:i,internalPath:u,basePath:f}}function Ue(t,e){let r=new URL(t.url);r.pathname=e.internalPath;let n=new Request(r.toString(),t);return n.headers.delete(N),n.headers.delete(O),n.headers.delete("cookie"),n.headers.set(N,e.key),n.headers.set(O,e.basePath),n}function C(t,e){return t.ARTIFACT.get(t.ARTIFACT.idFromName(e))}function he(t){return t.ARTIFACT_INDEX.get(t.ARTIFACT_INDEX.idFromName("index"))}var ye=["blank","dashboard","table","process-form"];function K(t){return typeof t=="string"&&ye.includes(t)}function Y(t,e){switch(t){case"blank":return Ft(e);case"dashboard":return Mt(e);case"table":return Ut(e);case"process-form":return Dt(e)}}function J(t,e){return`${JSON.stringify({title:t,libs:e},null,2)}
|
|
329
|
+
`}function z(t){return`<!doctype html>
|
|
330
|
+
<html lang="es">
|
|
331
|
+
<head>
|
|
332
|
+
<meta charset="utf-8" />
|
|
333
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
334
|
+
<title>${Pt(t)}</title>
|
|
335
|
+
</head>
|
|
336
|
+
<body>
|
|
337
|
+
<div id="app"></div>
|
|
338
|
+
<script type="module" src="./app.js"></script>
|
|
339
|
+
</body>
|
|
340
|
+
</html>
|
|
341
|
+
`}function Pt(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Ft(t){let e=`import { h, render } from 'preact';
|
|
342
|
+
import htm from 'htm';
|
|
343
|
+
|
|
344
|
+
const html = htm.bind(h);
|
|
345
|
+
const title = ${JSON.stringify(t)};
|
|
346
|
+
|
|
347
|
+
function App() {
|
|
348
|
+
return html\`<main class="min-h-screen bg-bg-base text-text-base flex items-center justify-center p-8">
|
|
349
|
+
<section class="w-full max-w-md rounded-xl border border-border-subtle bg-bg-surface p-8">
|
|
350
|
+
<h1 class="text-2xl font-semibold text-primary-600">\${title}</h1>
|
|
351
|
+
<p class="mt-2 text-text-muted">Listo para editar.</p>
|
|
352
|
+
<div class="mt-6 flex gap-2" aria-hidden="true">
|
|
353
|
+
<span class="h-2 flex-1 rounded-full bg-primary-500"></span>
|
|
354
|
+
<span class="h-2 flex-1 rounded-full bg-primary-600"></span>
|
|
355
|
+
<span class="h-2 flex-1 rounded-full bg-primary-700"></span>
|
|
356
|
+
<span class="h-2 flex-1 rounded-full bg-primary-800"></span>
|
|
357
|
+
<span class="h-2 flex-1 rounded-full bg-primary-900"></span>
|
|
358
|
+
</div>
|
|
359
|
+
</section>
|
|
360
|
+
</main>\`;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
render(html\`<\${App} />\`, document.getElementById('app'));
|
|
364
|
+
`;return[{path:"artifact.json",content:J(t,["preact","htm"])},{path:"index.html",content:z(t)},{path:"app.js",content:e}]}var be=`function jsonRows(cursor) {
|
|
365
|
+
return cursor.toArray().map((row) => {
|
|
366
|
+
const out = {};
|
|
367
|
+
for (const key of Object.keys(row)) {
|
|
368
|
+
const value = row[key];
|
|
369
|
+
out[key] = typeof value === "bigint" ? Number(value) : value;
|
|
370
|
+
}
|
|
371
|
+
return out;
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
`;function Mt(t){let e=`import { h, render } from "preact";
|
|
375
|
+
import { useEffect, useRef, useState } from "preact/hooks";
|
|
376
|
+
import htm from "htm";
|
|
377
|
+
import Chart from "chart.js/auto";
|
|
378
|
+
|
|
379
|
+
const html = htm.bind(h);
|
|
380
|
+
const title = ${JSON.stringify(t)};
|
|
381
|
+
|
|
382
|
+
function useChart(kind, points, labelKey, valueKey) {
|
|
383
|
+
const ref = useRef(null);
|
|
384
|
+
useEffect(() => {
|
|
385
|
+
const node = ref.current;
|
|
386
|
+
if (!node) return undefined;
|
|
387
|
+
const color = getComputedStyle(document.documentElement).getPropertyValue("--color-primary-600").trim() || "#5b4b8a";
|
|
388
|
+
const chart = new Chart(node, {
|
|
389
|
+
type: kind,
|
|
390
|
+
data: {
|
|
391
|
+
labels: points.map((point) => point[labelKey]),
|
|
392
|
+
datasets: [{
|
|
393
|
+
label: kind === "line" ? "Serie" : "Barras",
|
|
394
|
+
data: points.map((point) => point[valueKey]),
|
|
395
|
+
borderColor: color,
|
|
396
|
+
backgroundColor: color,
|
|
397
|
+
tension: 0.3,
|
|
398
|
+
}],
|
|
399
|
+
},
|
|
400
|
+
options: { responsive: true, plugins: { legend: { display: false } } },
|
|
401
|
+
});
|
|
402
|
+
return () => chart.destroy();
|
|
403
|
+
}, [kind, points, labelKey, valueKey]);
|
|
404
|
+
return ref;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
function App() {
|
|
408
|
+
const [kpis, setKpis] = useState([]);
|
|
409
|
+
const [serie, setSerie] = useState([]);
|
|
410
|
+
const [barras, setBarras] = useState([]);
|
|
411
|
+
const [error, setError] = useState("");
|
|
412
|
+
const lineRef = useChart("line", serie, "mes", "valor");
|
|
413
|
+
const barRef = useChart("bar", barras, "categoria", "valor");
|
|
414
|
+
|
|
415
|
+
useEffect(() => {
|
|
416
|
+
let live = true;
|
|
417
|
+
Promise.all([
|
|
418
|
+
fetch("api/resumen").then((res) => res.json()),
|
|
419
|
+
fetch("api/serie").then((res) => res.json()),
|
|
420
|
+
fetch("api/barras").then((res) => res.json()),
|
|
421
|
+
]).then(([nextKpis, nextSerie, nextBarras]) => {
|
|
422
|
+
if (!live) return;
|
|
423
|
+
setKpis(Array.isArray(nextKpis) ? nextKpis : []);
|
|
424
|
+
setSerie(Array.isArray(nextSerie) ? nextSerie : []);
|
|
425
|
+
setBarras(Array.isArray(nextBarras) ? nextBarras : []);
|
|
426
|
+
}).catch(() => {
|
|
427
|
+
if (live) setError("No se pudieron cargar los datos.");
|
|
428
|
+
});
|
|
429
|
+
return () => { live = false; };
|
|
430
|
+
}, []);
|
|
431
|
+
|
|
432
|
+
return html\`<main class="min-h-screen bg-bg-base p-6 text-text-base font-sans">
|
|
433
|
+
<header class="mb-6">
|
|
434
|
+
<h1 class="text-xl font-semibold">\${title}</h1>
|
|
435
|
+
<p class="text-text-muted">Tablero</p>
|
|
436
|
+
</header>
|
|
437
|
+
\${error ? html\`<p class="mb-4 text-danger-700">\${error}</p>\` : null}
|
|
438
|
+
<section class="grid gap-4 sm:grid-cols-3">
|
|
439
|
+
\${kpis.map((kpi) => html\`<article key=\${kpi.id} class="rounded-lg border border-border-subtle bg-bg-surface p-4">
|
|
440
|
+
<p class="text-sm text-text-muted">\${kpi.label}</p>
|
|
441
|
+
<p class="mt-1 text-2xl font-semibold text-primary-600">\${kpi.value}</p>
|
|
442
|
+
</article>\`)}
|
|
443
|
+
</section>
|
|
444
|
+
<section class="mt-6 grid gap-4 lg:grid-cols-2">
|
|
445
|
+
<article class="rounded-lg border border-border-subtle bg-bg-surface p-4">
|
|
446
|
+
<h2 class="mb-3 text-sm font-medium text-text-muted">Serie</h2>
|
|
447
|
+
<canvas ref=\${lineRef}></canvas>
|
|
448
|
+
</article>
|
|
449
|
+
<article class="rounded-lg border border-border-subtle bg-bg-surface p-4">
|
|
450
|
+
<h2 class="mb-3 text-sm font-medium text-text-muted">Barras</h2>
|
|
451
|
+
<canvas ref=\${barRef}></canvas>
|
|
452
|
+
</article>
|
|
453
|
+
</section>
|
|
454
|
+
</main>\`;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
render(html\`<\${App} />\`, document.getElementById("app"));
|
|
458
|
+
`,r=`import { ArtifactApp } from "./artifact-app.js";
|
|
459
|
+
|
|
460
|
+
${be}
|
|
461
|
+
const MESES = [
|
|
462
|
+
["Ene", 12],
|
|
463
|
+
["Feb", 18],
|
|
464
|
+
["Mar", 15],
|
|
465
|
+
["Abr", 22],
|
|
466
|
+
["May", 27],
|
|
467
|
+
["Jun", 24],
|
|
468
|
+
];
|
|
469
|
+
const CATEGORIAS = [
|
|
470
|
+
["Norte", 40],
|
|
471
|
+
["Sur", 28],
|
|
472
|
+
["Centro", 35],
|
|
473
|
+
["Oriente", 19],
|
|
474
|
+
];
|
|
475
|
+
|
|
476
|
+
export class App extends ArtifactApp {
|
|
477
|
+
constructor(ctx, env) {
|
|
478
|
+
super(ctx, env);
|
|
479
|
+
ctx.storage.sql.exec(\`CREATE TABLE IF NOT EXISTS kpi (
|
|
480
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
481
|
+
label TEXT NOT NULL,
|
|
482
|
+
value REAL NOT NULL,
|
|
483
|
+
unit TEXT NOT NULL DEFAULT ''
|
|
484
|
+
)\`);
|
|
485
|
+
ctx.storage.sql.exec(\`CREATE TABLE IF NOT EXISTS serie (
|
|
486
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
487
|
+
mes TEXT NOT NULL,
|
|
488
|
+
valor REAL NOT NULL
|
|
489
|
+
)\`);
|
|
490
|
+
ctx.storage.sql.exec(\`CREATE TABLE IF NOT EXISTS barra (
|
|
491
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
492
|
+
categoria TEXT NOT NULL,
|
|
493
|
+
valor REAL NOT NULL
|
|
494
|
+
)\`);
|
|
495
|
+
const n = Number(ctx.storage.sql.exec("SELECT COUNT(*) AS n FROM kpi").toArray()[0].n);
|
|
496
|
+
if (n === 0) {
|
|
497
|
+
ctx.storage.sql.exec("INSERT INTO kpi (label, value, unit) VALUES (?, ?, ?)", "Ventas", 128400, "COP");
|
|
498
|
+
ctx.storage.sql.exec("INSERT INTO kpi (label, value, unit) VALUES (?, ?, ?)", "Pedidos", 86, "");
|
|
499
|
+
ctx.storage.sql.exec("INSERT INTO kpi (label, value, unit) VALUES (?, ?, ?)", "Clientes", 34, "");
|
|
500
|
+
for (const [mes, valor] of MESES) {
|
|
501
|
+
ctx.storage.sql.exec("INSERT INTO serie (mes, valor) VALUES (?, ?)", mes, valor);
|
|
502
|
+
}
|
|
503
|
+
for (const [categoria, valor] of CATEGORIAS) {
|
|
504
|
+
ctx.storage.sql.exec("INSERT INTO barra (categoria, valor) VALUES (?, ?)", categoria, valor);
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
async fetch(request) {
|
|
510
|
+
const url = new URL(request.url);
|
|
511
|
+
if (url.pathname === "/api/resumen" && request.method === "GET") {
|
|
512
|
+
return Response.json(jsonRows(this.ctx.storage.sql.exec(
|
|
513
|
+
"SELECT id, label, value, unit FROM kpi ORDER BY id",
|
|
514
|
+
)));
|
|
515
|
+
}
|
|
516
|
+
if (url.pathname === "/api/serie" && request.method === "GET") {
|
|
517
|
+
return Response.json(jsonRows(this.ctx.storage.sql.exec(
|
|
518
|
+
"SELECT mes, valor FROM serie ORDER BY id",
|
|
519
|
+
)));
|
|
520
|
+
}
|
|
521
|
+
if (url.pathname === "/api/barras" && request.method === "GET") {
|
|
522
|
+
return Response.json(jsonRows(this.ctx.storage.sql.exec(
|
|
523
|
+
"SELECT categoria, valor FROM barra ORDER BY id",
|
|
524
|
+
)));
|
|
525
|
+
}
|
|
526
|
+
return new Response("Not found", { status: 404 });
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
`;return[{path:"artifact.json",content:J(t,["preact","preact/hooks","htm","chart.js"])},{path:"index.html",content:z(t)},{path:"app.js",content:e},{path:"server.js",content:r}]}function Ut(t){let e=`import { h, render } from "preact";
|
|
530
|
+
import { useEffect, useState } from "preact/hooks";
|
|
531
|
+
import htm from "htm";
|
|
532
|
+
import { createTable, getCoreRowModel, getFilteredRowModel, getSortedRowModel } from "@tanstack/table-core";
|
|
533
|
+
|
|
534
|
+
const html = htm.bind(h);
|
|
535
|
+
const title = ${JSON.stringify(t)};
|
|
536
|
+
const columns = [
|
|
537
|
+
{ accessorKey: "nombre", header: "Nombre" },
|
|
538
|
+
{ accessorKey: "estado", header: "Estado" },
|
|
539
|
+
{ accessorKey: "notas", header: "Notas" },
|
|
540
|
+
];
|
|
541
|
+
|
|
542
|
+
function App() {
|
|
543
|
+
const [rows, setRows] = useState([]);
|
|
544
|
+
const [state, setState] = useState({ sorting: [], globalFilter: "" });
|
|
545
|
+
const [nombre, setNombre] = useState("");
|
|
546
|
+
const [estado, setEstado] = useState("");
|
|
547
|
+
const [notas, setNotas] = useState("");
|
|
548
|
+
const [error, setError] = useState("");
|
|
549
|
+
|
|
550
|
+
async function load() {
|
|
551
|
+
const res = await fetch("api/filas");
|
|
552
|
+
const data = await res.json();
|
|
553
|
+
setRows(Array.isArray(data) ? data : []);
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
useEffect(() => { load().catch(() => setError("No se pudieron cargar las filas.")); }, []);
|
|
557
|
+
|
|
558
|
+
const table = createTable({
|
|
559
|
+
data: rows,
|
|
560
|
+
columns,
|
|
561
|
+
state,
|
|
562
|
+
onStateChange: (updater) => {
|
|
563
|
+
setState((prev) => (typeof updater === "function" ? updater(prev) : updater));
|
|
564
|
+
},
|
|
565
|
+
getCoreRowModel: getCoreRowModel(),
|
|
566
|
+
getSortedRowModel: getSortedRowModel(),
|
|
567
|
+
getFilteredRowModel: getFilteredRowModel(),
|
|
568
|
+
getRowId: (row) => String(row.id),
|
|
569
|
+
renderFallbackValue: null,
|
|
570
|
+
});
|
|
571
|
+
|
|
572
|
+
async function createRow(event) {
|
|
573
|
+
event.preventDefault();
|
|
574
|
+
setError("");
|
|
575
|
+
const res = await fetch("api/filas", {
|
|
576
|
+
method: "POST",
|
|
577
|
+
headers: { "content-type": "application/json" },
|
|
578
|
+
body: JSON.stringify({ nombre, estado, notas }),
|
|
579
|
+
});
|
|
580
|
+
if (!res.ok) {
|
|
581
|
+
setError("Revisa el nombre.");
|
|
582
|
+
return;
|
|
583
|
+
}
|
|
584
|
+
setNombre("");
|
|
585
|
+
setEstado("");
|
|
586
|
+
setNotas("");
|
|
587
|
+
await load();
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
async function remove(id) {
|
|
591
|
+
await fetch("api/filas/" + id, { method: "DELETE" });
|
|
592
|
+
await load();
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
return html\`<main class="min-h-screen bg-bg-base p-6 text-text-base font-sans">
|
|
596
|
+
<header class="mb-6">
|
|
597
|
+
<h1 class="text-xl font-semibold">\${title}</h1>
|
|
598
|
+
<p class="text-text-muted">Tabla</p>
|
|
599
|
+
</header>
|
|
600
|
+
\${error ? html\`<p class="mb-4 text-danger-700">\${error}</p>\` : null}
|
|
601
|
+
<form class="mb-6 grid gap-3 rounded-lg border border-border-subtle bg-bg-surface p-4 sm:grid-cols-4" onSubmit=\${createRow}>
|
|
602
|
+
<input class="rounded-md border border-border-subtle bg-bg-base px-3 py-2" placeholder="Nombre" value=\${nombre} onInput=\${(event) => setNombre(event.currentTarget.value)} />
|
|
603
|
+
<input class="rounded-md border border-border-subtle bg-bg-base px-3 py-2" placeholder="Estado" value=\${estado} onInput=\${(event) => setEstado(event.currentTarget.value)} />
|
|
604
|
+
<input class="rounded-md border border-border-subtle bg-bg-base px-3 py-2" placeholder="Notas" value=\${notas} onInput=\${(event) => setNotas(event.currentTarget.value)} />
|
|
605
|
+
<button class="rounded-md bg-primary-600 px-3 py-2 text-white hover:bg-primary-700" type="submit">Agregar</button>
|
|
606
|
+
</form>
|
|
607
|
+
<label class="mb-3 block text-sm text-text-muted">
|
|
608
|
+
Filtrar
|
|
609
|
+
<input class="mt-1 block w-full max-w-sm rounded-md border border-border-subtle bg-bg-surface px-3 py-2 text-text-base" value=\${state.globalFilter} onInput=\${(event) => setState((prev) => ({ ...prev, globalFilter: event.currentTarget.value }))} />
|
|
610
|
+
</label>
|
|
611
|
+
<div class="overflow-x-auto rounded-lg border border-border-subtle bg-bg-surface">
|
|
612
|
+
<table class="w-full text-left text-sm">
|
|
613
|
+
<thead>
|
|
614
|
+
\${table.getHeaderGroups().map((group) => html\`<tr key=\${group.id}>
|
|
615
|
+
\${group.headers.map((header) => html\`<th key=\${header.id} class="cursor-pointer border-b border-border-subtle px-3 py-2 text-text-muted" onClick=\${header.column.getToggleSortingHandler()}>
|
|
616
|
+
\${header.column.columnDef.header}\${header.column.getIsSorted() === "asc" ? " \u2191" : header.column.getIsSorted() === "desc" ? " \u2193" : ""}
|
|
617
|
+
</th>\`)}
|
|
618
|
+
<th class="border-b border-border-subtle px-3 py-2"></th>
|
|
619
|
+
</tr>\`)}
|
|
620
|
+
</thead>
|
|
621
|
+
<tbody>
|
|
622
|
+
\${table.getRowModel().rows.map((row) => html\`<tr key=\${row.id}>
|
|
623
|
+
\${row.getVisibleCells().map((cell) => html\`<td key=\${cell.id} class="border-b border-border-subtle px-3 py-2">\${cell.getValue() ?? ""}</td>\`)}
|
|
624
|
+
<td class="border-b border-border-subtle px-3 py-2 text-right">
|
|
625
|
+
<button class="text-primary-600" type="button" onClick=\${() => remove(row.original.id)}>Eliminar</button>
|
|
626
|
+
</td>
|
|
627
|
+
</tr>\`)}
|
|
628
|
+
</tbody>
|
|
629
|
+
</table>
|
|
630
|
+
</div>
|
|
631
|
+
</main>\`;
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
render(html\`<\${App} />\`, document.getElementById("app"));
|
|
635
|
+
`,r=`import { ArtifactApp } from "./artifact-app.js";
|
|
636
|
+
|
|
637
|
+
${be}
|
|
638
|
+
export class App extends ArtifactApp {
|
|
639
|
+
constructor(ctx, env) {
|
|
640
|
+
super(ctx, env);
|
|
641
|
+
ctx.storage.sql.exec(\`CREATE TABLE IF NOT EXISTS fila (
|
|
642
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
643
|
+
nombre TEXT NOT NULL,
|
|
644
|
+
estado TEXT NOT NULL DEFAULT '',
|
|
645
|
+
notas TEXT NOT NULL DEFAULT ''
|
|
646
|
+
)\`);
|
|
647
|
+
const n = Number(ctx.storage.sql.exec("SELECT COUNT(*) AS n FROM fila").toArray()[0].n);
|
|
648
|
+
if (n === 0) {
|
|
649
|
+
ctx.storage.sql.exec(
|
|
650
|
+
"INSERT INTO fila (nombre, estado, notas) VALUES (?, ?, ?)",
|
|
651
|
+
"Pedido de muestra",
|
|
652
|
+
"abierto",
|
|
653
|
+
"Fila de ejemplo",
|
|
654
|
+
);
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
async fetch(request) {
|
|
659
|
+
const url = new URL(request.url);
|
|
660
|
+
const idMatch = /^\\/api\\/filas\\/(\\d+)$/.exec(url.pathname);
|
|
661
|
+
|
|
662
|
+
if (url.pathname === "/api/filas" && request.method === "GET") {
|
|
663
|
+
return Response.json(jsonRows(this.ctx.storage.sql.exec(
|
|
664
|
+
"SELECT id, nombre, estado, notas FROM fila ORDER BY id DESC",
|
|
665
|
+
)));
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
if (url.pathname === "/api/filas" && request.method === "POST") {
|
|
669
|
+
let body;
|
|
670
|
+
try { body = await request.json(); } catch { body = {}; }
|
|
671
|
+
const nombre = typeof body.nombre === "string" ? body.nombre.trim() : "";
|
|
672
|
+
const estado = typeof body.estado === "string" ? body.estado.trim() : "";
|
|
673
|
+
const notas = typeof body.notas === "string" ? body.notas.trim() : "";
|
|
674
|
+
if (!nombre) return Response.json({ error: "nombre" }, { status: 400 });
|
|
675
|
+
this.ctx.storage.sql.exec(
|
|
676
|
+
"INSERT INTO fila (nombre, estado, notas) VALUES (?, ?, ?)",
|
|
677
|
+
nombre,
|
|
678
|
+
estado,
|
|
679
|
+
notas,
|
|
680
|
+
);
|
|
681
|
+
const id = Number(this.ctx.storage.sql.exec("SELECT last_insert_rowid() AS id").toArray()[0].id);
|
|
682
|
+
return Response.json({ ok: true, id });
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
if (idMatch && (request.method === "PATCH" || request.method === "PUT")) {
|
|
686
|
+
const id = Number(idMatch[1]);
|
|
687
|
+
let body;
|
|
688
|
+
try { body = await request.json(); } catch { body = {}; }
|
|
689
|
+
const nombre = typeof body.nombre === "string" ? body.nombre.trim() : "";
|
|
690
|
+
const estado = typeof body.estado === "string" ? body.estado.trim() : "";
|
|
691
|
+
const notas = typeof body.notas === "string" ? body.notas.trim() : "";
|
|
692
|
+
if (!nombre) return Response.json({ error: "nombre" }, { status: 400 });
|
|
693
|
+
this.ctx.storage.sql.exec(
|
|
694
|
+
"UPDATE fila SET nombre = ?, estado = ?, notas = ? WHERE id = ?",
|
|
695
|
+
nombre,
|
|
696
|
+
estado,
|
|
697
|
+
notas,
|
|
698
|
+
id,
|
|
699
|
+
);
|
|
700
|
+
return Response.json({ ok: true });
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
if (idMatch && request.method === "DELETE") {
|
|
704
|
+
this.ctx.storage.sql.exec("DELETE FROM fila WHERE id = ?", Number(idMatch[1]));
|
|
705
|
+
return Response.json({ ok: true });
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
return new Response("Not found", { status: 404 });
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
`;return[{path:"artifact.json",content:J(t,["preact","preact/hooks","htm","@tanstack/table-core"])},{path:"index.html",content:z(t)},{path:"app.js",content:e},{path:"server.js",content:r}]}function Dt(t){let e=`import { h, render } from "preact";
|
|
712
|
+
import { useEffect, useState } from "preact/hooks";
|
|
713
|
+
import htm from "htm";
|
|
714
|
+
|
|
715
|
+
const html = htm.bind(h);
|
|
716
|
+
const title = ${JSON.stringify(t)};
|
|
717
|
+
const ESTADOS = [
|
|
718
|
+
{ value: "pendiente", label: "Pendiente" },
|
|
719
|
+
{ value: "en_curso", label: "En curso" },
|
|
720
|
+
{ value: "cerrado", label: "Cerrado" },
|
|
721
|
+
];
|
|
722
|
+
|
|
723
|
+
function App() {
|
|
724
|
+
const [rows, setRows] = useState([]);
|
|
725
|
+
const [filtro, setFiltro] = useState("");
|
|
726
|
+
const [etapa, setEtapa] = useState("");
|
|
727
|
+
const [responsable, setResponsable] = useState("");
|
|
728
|
+
const [estado, setEstado] = useState("pendiente");
|
|
729
|
+
const [observaciones, setObservaciones] = useState("");
|
|
730
|
+
const [error, setError] = useState("");
|
|
731
|
+
|
|
732
|
+
async function load(nextFiltro) {
|
|
733
|
+
const query = nextFiltro ? "?estado=" + encodeURIComponent(nextFiltro) : "";
|
|
734
|
+
const res = await fetch("api/registros" + query);
|
|
735
|
+
const data = await res.json();
|
|
736
|
+
setRows(Array.isArray(data) ? data : []);
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
useEffect(() => { load(filtro).catch(() => setError("No se pudieron cargar los registros.")); }, [filtro]);
|
|
740
|
+
|
|
741
|
+
async function submit(event) {
|
|
742
|
+
event.preventDefault();
|
|
743
|
+
setError("");
|
|
744
|
+
const res = await fetch("api/registros", {
|
|
745
|
+
method: "POST",
|
|
746
|
+
headers: { "content-type": "application/json" },
|
|
747
|
+
body: JSON.stringify({ etapa, responsable, estado, observaciones }),
|
|
748
|
+
});
|
|
749
|
+
if (!res.ok) {
|
|
750
|
+
setError("Completa etapa, responsable y estado.");
|
|
751
|
+
return;
|
|
752
|
+
}
|
|
753
|
+
setEtapa("");
|
|
754
|
+
setResponsable("");
|
|
755
|
+
setObservaciones("");
|
|
756
|
+
setEstado("pendiente");
|
|
757
|
+
await load(filtro);
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
return html\`<main class="min-h-screen bg-bg-base p-6 text-text-base font-sans">
|
|
761
|
+
<header class="mb-6">
|
|
762
|
+
<h1 class="text-xl font-semibold">\${title}</h1>
|
|
763
|
+
<p class="text-text-muted">Control de procesos</p>
|
|
764
|
+
</header>
|
|
765
|
+
\${error ? html\`<p class="mb-4 text-danger-700">\${error}</p>\` : null}
|
|
766
|
+
<form class="mb-6 grid gap-3 rounded-lg border border-border-subtle bg-bg-surface p-4" onSubmit=\${submit}>
|
|
767
|
+
<label class="block text-sm text-text-muted">Etapa
|
|
768
|
+
<input class="mt-1 block w-full rounded-md border border-border-subtle bg-bg-base px-3 py-2 text-text-base" value=\${etapa} onInput=\${(event) => setEtapa(event.currentTarget.value)} />
|
|
769
|
+
</label>
|
|
770
|
+
<label class="block text-sm text-text-muted">Responsable
|
|
771
|
+
<input class="mt-1 block w-full rounded-md border border-border-subtle bg-bg-base px-3 py-2 text-text-base" value=\${responsable} onInput=\${(event) => setResponsable(event.currentTarget.value)} />
|
|
772
|
+
</label>
|
|
773
|
+
<label class="block text-sm text-text-muted">Estado
|
|
774
|
+
<select class="mt-1 block w-full rounded-md border border-border-subtle bg-bg-base px-3 py-2 text-text-base" value=\${estado} onChange=\${(event) => setEstado(event.currentTarget.value)}>
|
|
775
|
+
\${ESTADOS.map((item) => html\`<option key=\${item.value} value=\${item.value}>\${item.label}</option>\`)}
|
|
776
|
+
</select>
|
|
777
|
+
</label>
|
|
778
|
+
<label class="block text-sm text-text-muted">Observaciones
|
|
779
|
+
<textarea class="mt-1 block w-full rounded-md border border-border-subtle bg-bg-base px-3 py-2 text-text-base" rows="3" value=\${observaciones} onInput=\${(event) => setObservaciones(event.currentTarget.value)}></textarea>
|
|
780
|
+
</label>
|
|
781
|
+
<button class="rounded-md bg-primary-600 px-3 py-2 text-white hover:bg-primary-700" type="submit">Registrar etapa</button>
|
|
782
|
+
</form>
|
|
783
|
+
<label class="mb-3 block text-sm text-text-muted">Filtrar por estado
|
|
784
|
+
<select class="mt-1 block w-full max-w-xs rounded-md border border-border-subtle bg-bg-surface px-3 py-2 text-text-base" value=\${filtro} onChange=\${(event) => setFiltro(event.currentTarget.value)}>
|
|
785
|
+
<option value="">Todos</option>
|
|
786
|
+
\${ESTADOS.map((item) => html\`<option key=\${item.value} value=\${item.value}>\${item.label}</option>\`)}
|
|
787
|
+
</select>
|
|
788
|
+
</label>
|
|
789
|
+
<ul class="grid gap-3">
|
|
790
|
+
\${rows.map((row) => html\`<li key=\${row.id} class="rounded-lg border border-border-subtle bg-bg-surface p-4">
|
|
791
|
+
<div class="flex items-baseline justify-between gap-3">
|
|
792
|
+
<h2 class="font-medium">\${row.etapa}</h2>
|
|
793
|
+
<span class="text-sm text-primary-600">\${labelEstado(row.estado)}</span>
|
|
794
|
+
</div>
|
|
795
|
+
<p class="mt-1 text-sm text-text-muted">\${row.responsable}</p>
|
|
796
|
+
\${row.observaciones ? html\`<p class="mt-2 text-sm">\${row.observaciones}</p>\` : null}
|
|
797
|
+
</li>\`)}
|
|
798
|
+
</ul>
|
|
799
|
+
</main>\`;
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
function labelEstado(value) {
|
|
803
|
+
const found = ESTADOS.find((item) => item.value === value);
|
|
804
|
+
return found ? found.label : value;
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
render(html\`<\${App} />\`, document.getElementById("app"));
|
|
808
|
+
`,r=`import { ArtifactApp } from "./artifact-app.js";
|
|
809
|
+
|
|
810
|
+
${be}
|
|
811
|
+
const ESTADOS = ["pendiente", "en_curso", "cerrado"];
|
|
812
|
+
|
|
813
|
+
export class App extends ArtifactApp {
|
|
814
|
+
constructor(ctx, env) {
|
|
815
|
+
super(ctx, env);
|
|
816
|
+
ctx.storage.sql.exec(\`CREATE TABLE IF NOT EXISTS registro (
|
|
817
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
818
|
+
etapa TEXT NOT NULL,
|
|
819
|
+
responsable TEXT NOT NULL,
|
|
820
|
+
estado TEXT NOT NULL,
|
|
821
|
+
observaciones TEXT NOT NULL DEFAULT '',
|
|
822
|
+
created_at TEXT DEFAULT CURRENT_TIMESTAMP
|
|
823
|
+
)\`);
|
|
824
|
+
const n = Number(ctx.storage.sql.exec("SELECT COUNT(*) AS n FROM registro").toArray()[0].n);
|
|
825
|
+
if (n === 0) {
|
|
826
|
+
ctx.storage.sql.exec(
|
|
827
|
+
"INSERT INTO registro (etapa, responsable, estado, observaciones) VALUES (?, ?, ?, ?)",
|
|
828
|
+
"Recepci\xF3n",
|
|
829
|
+
"Ana Ruiz",
|
|
830
|
+
"pendiente",
|
|
831
|
+
"Lote de ejemplo",
|
|
832
|
+
);
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
async fetch(request) {
|
|
837
|
+
const url = new URL(request.url);
|
|
838
|
+
if (url.pathname === "/api/registros" && request.method === "GET") {
|
|
839
|
+
const estado = url.searchParams.get("estado");
|
|
840
|
+
if (estado) {
|
|
841
|
+
if (!ESTADOS.includes(estado)) return Response.json({ error: "estado" }, { status: 400 });
|
|
842
|
+
return Response.json(jsonRows(this.ctx.storage.sql.exec(
|
|
843
|
+
"SELECT id, etapa, responsable, estado, observaciones, created_at FROM registro WHERE estado = ? ORDER BY id DESC",
|
|
844
|
+
estado,
|
|
845
|
+
)));
|
|
846
|
+
}
|
|
847
|
+
return Response.json(jsonRows(this.ctx.storage.sql.exec(
|
|
848
|
+
"SELECT id, etapa, responsable, estado, observaciones, created_at FROM registro ORDER BY id DESC",
|
|
849
|
+
)));
|
|
850
|
+
}
|
|
851
|
+
if (url.pathname === "/api/registros" && request.method === "POST") {
|
|
852
|
+
let body;
|
|
853
|
+
try { body = await request.json(); } catch { body = {}; }
|
|
854
|
+
const etapa = typeof body.etapa === "string" ? body.etapa.trim() : "";
|
|
855
|
+
const responsable = typeof body.responsable === "string" ? body.responsable.trim() : "";
|
|
856
|
+
const estado = typeof body.estado === "string" ? body.estado.trim() : "";
|
|
857
|
+
const observaciones = typeof body.observaciones === "string" ? body.observaciones.trim() : "";
|
|
858
|
+
if (!etapa || !responsable || !ESTADOS.includes(estado)) {
|
|
859
|
+
return Response.json({ error: "datos" }, { status: 400 });
|
|
860
|
+
}
|
|
861
|
+
this.ctx.storage.sql.exec(
|
|
862
|
+
"INSERT INTO registro (etapa, responsable, estado, observaciones) VALUES (?, ?, ?, ?)",
|
|
863
|
+
etapa,
|
|
864
|
+
responsable,
|
|
865
|
+
estado,
|
|
866
|
+
observaciones,
|
|
867
|
+
);
|
|
868
|
+
return Response.json({ ok: true });
|
|
869
|
+
}
|
|
870
|
+
return new Response("Not found", { status: 404 });
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
`;return[{path:"artifact.json",content:J(t,["preact","preact/hooks","htm"])},{path:"index.html",content:z(t)},{path:"app.js",content:e},{path:"server.js",content:r}]}function P(t){var a,u;if(!t.isPublic&&!t.key)return null;let e=encodeURIComponent(t.slug),r=t.isPublic?`${e}/`:`${e}/k/${encodeURIComponent(t.key)}/`,n=new URL(t.requestUrl),s=(a=t.devPath)==null?void 0:a.trim(),o=G(n.hostname,s);if(o)return`${n.origin}${De(o)}/${r}`;let i=(u=t.host)==null?void 0:u.trim();return i?`https://${i.replace(/^https?:\/\//,"").replace(/\/+$/,"")}/${r}`:s?`${n.origin}${De(s)}/${r}`:null}function De(t){let e=t.startsWith("/")?t:`/${t}`;return e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e==="/"?"":e}var D="/api/internal/artifacts",jt=new Set(["server","browser","system"]),qt=200,q=200,$t=4e3;function je(t){return t===D||t.startsWith(`${D}/`)}function Ht(t,e){let r=e.HX_API_KEY;return r?B(t.headers.get("Authorization")??"",r):!1}async function qe(t,e){if(!Ht(t,e))return d({error:"unauthorized"},401);let r=new URL(t.url),n=Vt(r.pathname);if(n.kind==="missing")return d({error:"not found"},404);if(n.kind==="create")return t.method!=="POST"?w():Bt(t,e);let s=C(e,n.slug),o=await s.getMeta();if(!o)return d({error:"not found"},404);switch(n.kind){case"meta":return t.method!=="GET"?w():Q(r,o.uuid)?d({error:"not found"},404):Xt(t,e,s,o);case"files":return t.method!=="GET"?w():Q(r,o.uuid)?d({error:"not found"},404):Wt(r,s,o);case"versions":return t.method!=="GET"?w():Q(r,o.uuid)?d({error:"not found"},404):Gt(r,s,o);case"logs":return t.method!=="GET"?w():Q(r,o.uuid)?d({error:"not found"},404):Kt(r,s,o);case"write":return t.method!=="POST"?w():Yt(t,s);case"rollback":return t.method!=="POST"?w():Jt(t,s);case"settings":return t.method!=="POST"?w():zt(t,e,n.slug,s);default:return d({error:"not found"},404)}}function Vt(t){let e=t;if(e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e===D)return{kind:"create"};if(!e.startsWith(`${D}/`))return{kind:"missing"};let r;try{r=e.slice(D.length+1).split("/").map(s=>decodeURIComponent(s))}catch{return{kind:"missing"}}if(r.length===0||r.length>2||r.some(s=>s===""))return{kind:"missing"};let n=r[0]??"";if(I(n))return{kind:"missing"};if(r.length===1)return{kind:"meta",slug:n};switch(r[1]){case"files":case"versions":case"logs":case"write":case"rollback":case"settings":return{kind:r[1],slug:n};default:return{kind:"missing"}}}async function Bt(t,e){let r=await Z(t);if(!r.ok)return d({error:"invalid json"},400);if(typeof r.value.slug!="string")return d({error:"slug is required"},400);let n=I(r.value.slug);if(n)return d({error:n},400);let s=j(r.value.title,qt);if(!s)return d({error:"title must be 1..200 characters"},400);let o=j(r.value.org,q);if(!o)return d({error:"org is required"},400);let i=j(r.value.owner,q);if(!i)return d({error:"owner is required"},400);let a="blank";if(r.value.template!==void 0){if(!K(r.value.template))return d({error:"template must be blank, dashboard, table, or process-form"},400);a=r.value.template}let u=C(e,r.value.slug),l=await u.create({slug:r.value.slug,title:s,tenant:e.TENANT,org:o,owner:i});if(!l)return d({error:"slug already exists"},409);let f=await u.write({changes:Y(a,s),message:"create",baseVersion:null,author:i});if(!f.ok)return d(f,ve(f));let p=await u.getMeta()??{...l.meta,activeVersion:f.version},m=await u.getAccess(),E=Ae(t,e,p.slug,p.public,p.public?null:(m==null?void 0:m.key)??l.key);return d({meta:p,version:f.version,url:E},200)}function Q(t,e){return t.searchParams.has("expectUuid")?t.searchParams.get("expectUuid")!==e:!1}async function Xt(t,e,r,n){let s=await r.getAccess();if(!s)return d({error:"not found"},404);let o=Ae(t,e,n.slug,s.public,s.key);return d({meta:n,url:o},200)}async function Wt(t,e,r){let n=t.searchParams.get("version"),s=n||r.activeVersion;if(!s)return d({error:"not found"},404);let o=await e.readFiles({version:s});return o?d({meta:r,version:s,files:o},200):d({error:"not found"},404)}async function Gt(t,e,r){let n=$e(t.searchParams.get("limit"));if(n===null)return d({error:"limit must be an integer from 1 to 1000"},400);let s=await e.versions(n!==void 0?{limit:n}:void 0);return s?d({meta:r,activeVersion:r.activeVersion,versions:s},200):d({error:"not found"},404)}async function Kt(t,e,r){let n=$e(t.searchParams.get("limit"));if(n===null)return d({error:"limit must be an integer from 1 to 1000"},400);let s=t.searchParams.get("source");if(s&&!jt.has(s))return d({error:"source must be server, browser, or system"},400);let o=await e.logs({...n!==void 0?{limit:n}:{},...s?{source:s}:{}});return o?d({meta:r,logs:o},200):d({error:"not found"},404)}async function Yt(t,e){let r=await Z(t);if(!r.ok)return y("invalid json");let n=Qt(r.value.changes);if(!Array.isArray(n))return n;if(typeof r.value.message!="string"||!r.value.message.trim()||r.value.message.length>$t)return y("message must be a non-empty string up to 4000 characters");if(r.value.baseVersion!==null&&(typeof r.value.baseVersion!="string"||!r.value.baseVersion))return y("baseVersion is required");let s=j(r.value.author,q);if(!s)return y("author is required");let o=await e.write({changes:n,message:r.value.message,baseVersion:r.value.baseVersion,author:s});return d(o,ve(o))}async function Jt(t,e){let r=await Z(t);if(!r.ok)return y("invalid json");if(typeof r.value.version!="string"||!r.value.version)return y("version is required");let n=j(r.value.author,q);if(!n)return y("author is required");let s=await e.rollback({version:r.value.version,author:n});return d(s,ve(s))}async function zt(t,e,r,n){let s=await Z(t);if(!s.ok)return d({error:"invalid json"},400);let o={};if(s.value.group!==void 0){if(typeof s.value.group!="string"||!s.value.group.trim()||s.value.group.length>q)return d({error:"group must be a non-empty string"},400);o.group=s.value.group}if(s.value.public!==void 0){if(typeof s.value.public!="boolean")return d({error:"public must be a boolean"},400);o.public=s.value.public}if(s.value.rotateKey!==void 0){if(typeof s.value.rotateKey!="boolean")return d({error:"rotateKey must be a boolean"},400);o.rotateKey=s.value.rotateKey}if(o.group===void 0&&o.public===void 0&&o.rotateKey===void 0)return d({error:"settings requires group, public, or rotateKey"},400);let i=await n.settings(o);if(!i)return d({error:"not found"},404);let a=Ae(t,e,r,i.meta.public,i.meta.public?null:i.key);return d({meta:i.meta,url:a},200)}function ve(t){return t.ok?200:t.code==="conflict"?409:422}function Ae(t,e,r,n,s){return P({requestUrl:t.url,host:e.ARTIFACT_HOST,devPath:e.ARTIFACT_DEV_PATH,slug:r,isPublic:n,key:s})}function Qt(t){if(!Array.isArray(t)||t.length===0)return y("changes must be a non-empty array");let e=new Set,r=[];for(let n of t){if(!n||typeof n!="object"||Array.isArray(n))return y("each change must be an object");let s=n;if(typeof s.path!="string")return y("change path is required");let o=U(s.path);if(o)return y(o);if(e.has(s.path))return y(`duplicate path: ${s.path}`);if(e.add(s.path),s.content!==null&&typeof s.content!="string")return y("content must be a string or null");if(typeof s.content=="string"&&x(s.content)>g.fileBytes)return d({ok:!1,code:"limit",error:`file exceeds 1 MB: ${s.path}`},422);r.push({path:s.path,content:s.content})}return r}function $e(t){if(t==null||t==="")return;if(!/^\d+$/.test(t))return null;let e=Number(t);return e<1||e>1e3?null:e}function j(t,e){if(typeof t!="string")return null;let r=t.trim();return!r||r.length>e?null:r}async function Z(t){let e;try{e=await t.json()}catch{return{ok:!1}}return!e||typeof e!="object"||Array.isArray(e)?{ok:!1}:{ok:!0,value:e}}function y(t){return d({ok:!1,code:"invalid",error:t},422)}function w(){return d({error:"method not allowed"},405)}function d(t,e){return Response.json(t,{status:e})}var Zt=5e3,er=6e4,He=new Map;function tr(t){var e,r;return!!((e=t.HX_ORA_URL)!=null&&e.trim()&&((r=t.HX_API_KEY)!=null&&r.trim()))}async function Xe(t,e,r=fetch,n=Zt){if(!tr(t))return{ok:!0,mode:"phase1"};let s=await T(e),o=He.get(s);if(o&&Date.now()-o.at<er)return Be(o.value);let i=await rr(t,e,r,n);return He.set(s,{at:Date.now(),value:i}),Be(i)}async function rr(t,e,r,n){let s=t.HX_ORA_URL.trim().replace(/\/$/,""),o=new AbortController,i=setTimeout(()=>o.abort(),n);try{let a=await r(`${s}/internal/artifacts/access`,{method:"POST",headers:{Authorization:t.HX_API_KEY.trim(),"Content-Type":"application/json"},body:JSON.stringify({token:e}),signal:o.signal});if(a.status===401)return{ok:!1,status:401};if(!a.ok)return{ok:!1,status:403};let u;try{u=await a.json()}catch{return{ok:!1,status:403}}let l=nr(u);return l?{ok:!0,mode:"rbac",access:l}:{ok:!1,status:403}}catch{return{ok:!1,status:403}}finally{clearTimeout(i)}}function nr(t){if(!t||typeof t!="object")return null;let e=t;if(e.ok!==!0||!e.access||typeof e.access!="object")return null;let r=e.access;return typeof r.userId!="string"||!r.userId.trim()||typeof r.org!="string"||typeof r.isAdmin!="boolean"||typeof r.isSuperAdmin!="boolean"||!Ve(r.roleIds)||!Ve(r.modules)?null:{userId:r.userId,org:r.org,roleIds:r.roleIds,isAdmin:r.isAdmin,isSuperAdmin:r.isSuperAdmin,modules:r.modules}}function Ve(t){return Array.isArray(t)&&t.every(e=>typeof e=="string")}function Be(t){return t.ok?{ok:!0,mode:"rbac",access:{...t.access,roleIds:[...t.access.roleIds],modules:[...t.access.modules]}}:t}import{importSPKI as sr,jwtVerify as or}from"jose";var ir=/^Bearer ([A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)$/,ar='Bearer realm="hugex-artifact"',ee=new Map;function Ee(t){if(typeof t!="string")return null;let e=ir.exec(t);return e?e[1]:null}function cr(t){let e=t.trim();return e.includes("BEGIN PUBLIC KEY")?e:`-----BEGIN PUBLIC KEY-----
|
|
874
|
+
${e}
|
|
875
|
+
-----END PUBLIC KEY-----`}function lr(t){let e=ee.get(t);if(e)return e;let r=sr(cr(t),"RS256");return ee.set(t,r),r.catch(()=>{ee.get(t)===r&&ee.delete(t)}),r}function $(){return new Response(JSON.stringify({error:"unauthorized"}),{status:401,headers:{"Content-Type":"application/json","WWW-Authenticate":ar,"Referrer-Policy":"no-referrer"}})}function ur(t){return(typeof t.email=="string"?t.email.trim():"")||null}async function dr(t,e,r){try{let n=typeof e=="string"?await lr(e):e,{payload:s}=await or(t,n,{algorithms:["RS256"]}),o=ur(s);if(!o||s.tenant!==r)return null;let i=typeof s.org=="string"&&s.org?s.org:"default";return{email:o,org:i,tenant:r}}catch{return null}}async function We(t,e){let r=Ee(t.headers.get("authorization"));if(!r)return{ok:!1,response:$()};if(!e.KC_RS256_PK||!e.KC_RS256_PK.trim())return{ok:!1,response:new Response("PK is not defined",{status:500,headers:{"Referrer-Policy":"no-referrer"}})};let n=await dr(r,e.KC_RS256_PK,e.TENANT);return n?{ok:!0,identity:n}:{ok:!1,response:$()}}var fr="artifacts",pr={artifact_list:"module",artifact_create:"module",artifact_read:"use",artifact_logs:"use",artifact_query:"use",artifact_url:"use",artifact_write:"manage",artifact_rollback:"manage",artifact_settings:"manage",artifact_versions:"use"};function Ge(t){return Object.prototype.hasOwnProperty.call(pr,t)}function Ke(t){return t.modules.includes(fr)}function Te(t,e){if(e.isSuperAdmin)return!0;let r=e.org||"default",n=t.org||"default";return e.isAdmin?n===r:t.owner===e.userId?!0:t.group==="all"?n===r:!t.group||t.group==="none"?!1:e.roleIds.includes(t.group)}function gr(t,e){if(e.isSuperAdmin)return!0;let r=e.org||"default",n=t.org||"default";return e.isAdmin?n===r:!!t.owner&&t.owner===e.userId}function Ye(t,e,r,n){if(t!=="use"&&t!=="manage")return!1;if(!n)return e.owner===r.email;let s={owner:e.owner,group:e.group??"none",org:e.org};return t==="manage"?gr(s,n):Te(s,n)}var mr=/^[a-z0-9][a-z0-9-]{1,47}$/,hr=new Set(["mcp","k","api","app","index","assets","static"]),yr=new Set(["server","browser","system"]),br=1024*1024,vr=200,Ar=200,Er=4e3,Tr=1e5,Re='Contrato de archivos: artifact.json es obligatorio y vale { "title": string, "libs": string[] } con nombres del cat\xE1logo (por ejemplo "preact", "htm", "chart.js", "@tanstack/table-core"). index.html es obligatorio. El resto es libre (app.js, style.css, \u2026). server.js es opcional y, si existe, debe hacer `import { ArtifactApp } from "./artifact-app.js"` y `export class App extends ArtifactApp`. El HTTP p\xFAblico nunca sirve server.js ni artifact.json; este MCP s\xED los devuelve para poder editarlos. No uses localStorage ni sessionStorage: todos los artifacts del tenant comparten origen; el estado persistente va en la SQLite del facet (v\xEDa server.js). El tema de @hugex/ui no tiene bg-background ni text-foreground: usa bg-bg-base, bg-bg-surface, text-text-base, text-text-muted, border-border-subtle, bg-primary-500, bg-primary-600, bg-primary-700, bg-primary-800, bg-primary-900 y text-primary-600.',Rr={type:"object",additionalProperties:!1,required:["path","content"],properties:{path:{type:"string",description:'Ruta relativa del archivo. Sin "/" inicial, sin "\\" y sin segmentos "." o "..". M\xE1ximo 200 caracteres.'},content:{type:["string","null"],description:"Contenido de texto del archivo (m\xE1ximo 1 MB). null borra esa ruta."}}},ze=[{name:"artifact_list",description:'Lista los artifacts de este tenant que el llamante puede usar. En modo Fase 1 (sin HX_ORA_URL o sin HX_API_KEY) solo los del owner. Con RBAC: el owner, un admin de la misma org, un superadmin, group "all" de su org, o group igual a uno de sus roles. No recibe argumentos. Cada fila trae uuid, slug, title, org, owner, group, public, activeVersion, updatedAt y revision.',inputSchema:{type:"object",properties:{},additionalProperties:!1}},{name:"artifact_create",description:"Crea un artifact y publica una versi\xF3n inicial. El llamante queda como owner. La org guardada es la del AccessContext de hx-ora cuando el RBAC est\xE1 activo, y el claim org del JWT en modo Fase 1. slug es inmutable: debe cumplir ^[a-z0-9][a-z0-9-]{1,47}$ y no puede ser mcp, k, api, app, index, assets ni static. title es el t\xEDtulo visible. template es opcional: blank (defecto, saludo con preact y htm), dashboard (KPIs y gr\xE1ficas), table (tabla ordenable y filtrable) o process-form (formulario de control de procesos). blank escribe artifact.json (libs: preact y htm), index.html y app.js (Preact + htm, clases del tema @hugex/ui: bg-bg-base, bg-bg-surface, text-text-base, text-text-muted, border-border-subtle, bg-primary-500 a bg-primary-900 y text-primary-600). Devuelve { slug, uuid, version, url }. "+Re,inputSchema:{type:"object",additionalProperties:!1,required:["slug","title"],properties:{slug:{type:"string",description:"Identificador inmutable en la URL. Min\xFAsculas, d\xEDgitos y guiones; 2 a 48 caracteres; no reservado."},title:{type:"string",description:"T\xEDtulo del artifact. Se guarda en artifact.json y en la plantilla inicial."},template:{type:"string",enum:[...ye],description:"Plantilla inicial. blank (defecto): saludo. dashboard: KPIs y gr\xE1ficas. table: tabla ordenable. process-form: control de procesos."}}}},{name:"artifact_read",description:"Lee archivos de un artifact. Sin path devuelve todos los de la versi\xF3n pedida (por defecto la activa), incluido artifact.json y server.js. Con path devuelve solo ese archivo. La respuesta incluye siempre activeVersion: ese valor es el baseVersion que hay que pasar a artifact_write. "+Re,inputSchema:{type:"object",additionalProperties:!1,required:["slug"],properties:{slug:{type:"string",description:"Slug del artifact."},path:{type:"string",description:"Si se indica, solo ese archivo. Si se omite, todos los de la versi\xF3n."},version:{type:"string",description:"Id de versi\xF3n (sha256). Si se omite, se lee la versi\xF3n activa."}}}},{name:"artifact_logs",description:'Mensajes del artifact: source "server" (facet), "browser" (cliente) o "system". Sirve para depurar un server.js que no arranc\xF3 o un error de publicaci\xF3n. limit es opcional (1 a 1000).',inputSchema:{type:"object",additionalProperties:!1,required:["slug"],properties:{slug:{type:"string",description:"Slug del artifact."},limit:{type:"integer",minimum:1,maximum:1e3,description:"M\xE1ximo de filas, las m\xE1s recientes."},source:{type:"string",enum:["server","browser","system"],description:"Filtra por origen. Si se omite, devuelve todos."}}}},{name:"artifact_query",description:"Lee la SQLite del facet con una sola sentencia SELECT. No se admite WITH (en SQLite un WITH puede terminar en DELETE, UPDATE o INSERT), ni m\xE1s de una sentencia, ni INSERT, UPDATE o DELETE. Si no hay server.js o la versi\xF3n no arranc\xF3, la llamada falla y el detalle queda en artifact_logs. No uses esta tool para escribir datos.",inputSchema:{type:"object",additionalProperties:!1,required:["slug","sql"],properties:{slug:{type:"string",description:"Slug del artifact."},sql:{type:"string",description:"Una sola sentencia SELECT. Sin WITH y sin otra sentencia despu\xE9s."}}}},{name:"artifact_url",description:"URL para abrir el artifact en el navegador. Si no es p\xFAblico incluye /k/<llave>/ y siempre termina en /. Rotar la llave invalida la URL anterior. No expone el c\xF3digo: para leer archivos usa artifact_read.",inputSchema:{type:"object",additionalProperties:!1,required:["slug"],properties:{slug:{type:"string",description:"Slug del artifact."}}}},{name:"artifact_write",description:'Publica cambios sobre la versi\xF3n activa. files es una lista de { path, content }; content null borra el archivo. message describe el cambio y queda firmado con el email del JWT. baseVersion es obligatorio y tiene que ser exactamente la versi\xF3n activa que devuelven artifact_read (campo activeVersion) o artifact_versions. Si no coincide, el resultado es conflict y no se cambia nada: vuelve a leer activeVersion y reintenta. No env\xEDes un write sin cambios (el servidor responde "no changes"). Una lib que no est\xE1 en el cat\xE1logo es un warning, no un error. Mant\xE9n siempre artifact.json e index.html. '+Re,inputSchema:{type:"object",additionalProperties:!1,required:["slug","files","message","baseVersion"],properties:{slug:{type:"string",description:"Slug del artifact."},files:{type:"array",minItems:1,items:Rr,description:"Cambios aplicados encima de la versi\xF3n activa. content null borra path."},message:{type:"string",description:"Mensaje de la versi\xF3n, visible en artifact_versions."},baseVersion:{type:"string",description:'Id de la versi\xF3n activa actual. C\xF3piarlo de artifact_read.activeVersion o de la versi\xF3n con state "activa" en artifact_versions. Si est\xE1 desactualizado, el write no se aplica.'}}}},{name:"artifact_rollback",description:"Vuelve a activar el c\xF3digo de una versi\xF3n anterior (el id que devuelve artifact_versions). Los datos de la SQLite del facet no se revierten. La versi\xF3n tiene que existir y haber sido activa alguna vez.",inputSchema:{type:"object",additionalProperties:!1,required:["slug","version"],properties:{slug:{type:"string",description:"Slug del artifact."},version:{type:"string",description:"Id (sha256) de la versi\xF3n a reactivar."}}}},{name:"artifact_settings",description:'Cambia la visibilidad de dise\xF1o o la ejecuci\xF3n p\xFAblica. group: "none" (privado, el defecto), "all" (toda la org) o un roleId. public: si es true cualquiera con la URL abre el artifact sin llave; el c\xF3digo y la gesti\xF3n siguen siendo privados. rotateKey: true invalida la llave anterior al instante. Hay que enviar al menos uno de group, public o rotateKey. public por defecto es false.',inputSchema:{type:"object",additionalProperties:!1,required:["slug"],properties:{slug:{type:"string",description:"Slug del artifact."},group:{type:"string",description:'"none", "all", o el id de un rol. Controla qui\xE9n puede usar el artifact en dise\xF1o, no la URL p\xFAblica.'},public:{type:"boolean",description:"true: la URL se abre sin llave. false: hace falta /k/<llave>/."},rotateKey:{type:"boolean",description:"true rota la llave. La respuesta trae la llave nueva y la URL nueva."}}}},{name:"artifact_versions",description:'Historial de versiones (id, state, message, author, error, createdAt). El id de la versi\xF3n con state "activa" es el baseVersion que exige artifact_write. limit es opcional (1 a 1000). La respuesta incluye activeVersion.',inputSchema:{type:"object",additionalProperties:!1,required:["slug"],properties:{slug:{type:"string",description:"Slug del artifact."},limit:{type:"integer",minimum:1,maximum:1e3,description:"M\xE1ximo de versiones a devolver."}}}}];function Qe(t){return mr.test(t)?hr.has(t)?`slug "${t}" is reserved`:null:"slug must match ^[a-z0-9][a-z0-9-]{1,47}$"}function Ze(t){return t.length===0||t.length>vr?"path length must be 1..200":t.startsWith("/")||t.includes("\\")||t.includes("\0")?'path must be relative and use "/"':t.split("/").some(r=>r===""||r==="."||r==="..")?'path must not contain empty, "." or ".." segments':null}async function et(t,e,r){try{return Ge(t)?r.access&&!Ke(r.access)?c({ok:!1,error:"module required: artifacts"}):await xr(t,e,r):c({ok:!1,error:`unknown tool: ${t}`})}catch(n){let s=n instanceof Error?n.message:"tool failed";return c({ok:!1,error:s})}}async function xr(t,e,r){switch(t){case"artifact_list":return kr(e,r);case"artifact_create":return wr(e,r);case"artifact_read":return Sr(e,r);case"artifact_logs":return Lr(e,r);case"artifact_query":return Ir(e,r);case"artifact_url":return _r(e,r);case"artifact_write":return Nr(e,r);case"artifact_rollback":return Or(e,r);case"artifact_settings":return Cr(e,r);case"artifact_versions":return Pr(e,r);default:return c({ok:!1,error:`unknown tool: ${t}`})}}async function kr(t,e){let r=A(t,[]);if(r)return c({ok:!1,error:r});if(e.access){let s=await he(e.env).list();return v(s.filter(o=>Te(o,e.access)))}let n=await he(e.env).list({owner:e.identity.email});return v(n.filter(s=>s.owner===e.identity.email))}async function wr(t,e){let r=A(t,["slug","title","template"]);if(r)return c({ok:!1,error:r});if(typeof t.slug!="string")return c({ok:!1,error:"slug is required"});let n=Qe(t.slug);if(n)return c({ok:!1,error:n});if(typeof t.title!="string")return c({ok:!1,error:"title is required"});let s=t.title.trim();if(!s||s.length>Ar)return c({ok:!1,error:"title must be 1..200 characters"});let o="blank";if(t.template!==void 0){if(!K(t.template))return c({ok:!1,error:"template must be blank, dashboard, table, or process-form"});o=t.template}let i=C(e.env,t.slug),a=await i.create({slug:t.slug,title:s,tenant:e.identity.tenant,org:e.access?e.access.org:e.identity.org,owner:e.identity.email});if(!a)return c({ok:!1,error:"slug already exists",slug:t.slug});let u=await i.write({changes:Y(o,s),message:"create",baseVersion:null,author:e.identity.email});if(!u.ok)return c({ok:!1,error:"initial write failed",slug:a.meta.slug,uuid:a.meta.uuid,write:u});let l=P({requestUrl:e.requestUrl,host:e.env.ARTIFACT_HOST,devPath:e.env.ARTIFACT_DEV_PATH,slug:a.meta.slug,isPublic:a.meta.public,key:a.key}),f={slug:a.meta.slug,uuid:a.meta.uuid,version:u.version,url:l};return u.warnings.length>0&&(f.warnings=u.warnings),v(f)}async function Sr(t,e){let r=A(t,["slug","path","version"]);if(r)return c({ok:!1,error:r});let n=L(t);if(typeof n!="string")return n;let s=Je(t,"path");if(typeof s!="string"&&s!==void 0)return c({ok:!1,error:"path must be a string"});if(typeof s=="string"){let l=Ze(s);if(l)return c({ok:!1,error:l})}let o=Je(t,"version");if(o===null)return c({ok:!1,error:"version must be a string"});if(typeof o=="string"&&!o)return c({ok:!1,error:"version must be a non-empty string"});let i=await S(e,n,"use");if(i.denied)return i.denied;let a=o??i.meta.activeVersion;if(!a)return c({ok:!1,error:"not_found",slug:n});let u=await i.rpc.readFiles({...s?{path:s}:{},version:a});return u?s&&u.length===0?c({ok:!1,error:"file not found",slug:n,path:s}):v({slug:n,activeVersion:i.meta.activeVersion,version:a,files:u}):c({ok:!1,error:"not_found",slug:n})}async function Lr(t,e){let r=A(t,["slug","limit","source"]);if(r)return c({ok:!1,error:r});let n=L(t);if(typeof n!="string")return n;let s=tt(t.limit);if(s===!1)return c({ok:!1,error:"limit must be an integer from 1 to 1000"});if(t.source!==void 0&&(typeof t.source!="string"||!yr.has(t.source)))return c({ok:!1,error:"source must be server, browser, or system"});let o=await S(e,n,"use");if(o.denied)return o.denied;let i=await o.rpc.logs({...s!==void 0?{limit:s}:{},...typeof t.source=="string"?{source:t.source}:{}});return i?v({slug:n,logs:i}):c({ok:!1,error:"not_found",slug:n})}async function Ir(t,e){let r=A(t,["slug","sql"]);if(r)return c({ok:!1,error:r});let n=L(t);if(typeof n!="string")return n;if(typeof t.sql!="string"||!t.sql.trim())return c({ok:!1,error:"sql is required"});if(t.sql.length>Tr)return c({ok:!1,error:"sql is too long"});if(!Ne(t.sql))return c({ok:!1,error:"artifact_query only accepts a single SELECT statement (WITH and multiple statements are rejected)"});let s=await S(e,n,"use");if(s.denied)return s.denied;let o=await s.rpc.query(t.sql);return o.ok?v(o):c(o)}async function _r(t,e){let r=A(t,["slug"]);if(r)return c({ok:!1,error:r});let n=L(t);if(typeof n!="string")return n;let s=await S(e,n,"use");if(s.denied)return s.denied;let o=await s.rpc.getAccess();if(!o)return c({ok:!1,error:"not_found",slug:n});let i=P({requestUrl:e.requestUrl,host:e.env.ARTIFACT_HOST,devPath:e.env.ARTIFACT_DEV_PATH,slug:n,isPublic:o.public,key:o.key});return i?v({slug:n,public:o.public,url:i}):c({ok:!1,error:"artifact URL is not configured (set ARTIFACT_HOST or ARTIFACT_DEV_PATH)",slug:n})}async function Nr(t,e){let r=A(t,["slug","files","message","baseVersion"]);if(r)return c({ok:!1,error:r});let n=L(t);if(typeof n!="string")return n;let s=Fr(t.files);if(!Array.isArray(s))return s;if(typeof t.message!="string"||!t.message.trim()||t.message.length>Er)return c({ok:!1,error:"message must be a non-empty string up to 4000 characters"});if(t.baseVersion!==null&&(typeof t.baseVersion!="string"||!t.baseVersion))return c({ok:!1,error:"baseVersion is required and must be the active version id returned by artifact_read or artifact_versions"});let o=await S(e,n,"manage");if(o.denied)return o.denied;let i=await o.rpc.write({changes:s,message:t.message,baseVersion:t.baseVersion,author:e.identity.email});return i.ok?v(i):c(i)}async function Or(t,e){let r=A(t,["slug","version"]);if(r)return c({ok:!1,error:r});let n=L(t);if(typeof n!="string")return n;if(typeof t.version!="string"||!t.version)return c({ok:!1,error:"version is required"});let s=await S(e,n,"manage");if(s.denied)return s.denied;let o=await s.rpc.rollback({version:t.version,author:e.identity.email});return o.ok?v(o):c(o)}async function Cr(t,e){let r=A(t,["slug","group","public","rotateKey"]);if(r)return c({ok:!1,error:r});let n=L(t);if(typeof n!="string")return n;let s={};if(t.group!==void 0){if(typeof t.group!="string"||!t.group.trim()||t.group.length>200)return c({ok:!1,error:'group must be a non-empty string ("none", "all", or a role id)'});s.group=t.group}if(t.public!==void 0){if(typeof t.public!="boolean")return c({ok:!1,error:"public must be a boolean"});s.public=t.public}if(t.rotateKey!==void 0){if(typeof t.rotateKey!="boolean")return c({ok:!1,error:"rotateKey must be a boolean"});s.rotateKey=t.rotateKey}if(s.group===void 0&&s.public===void 0&&s.rotateKey===void 0)return c({ok:!1,error:"settings requires group, public, or rotateKey"});let o=await S(e,n,"manage");if(o.denied)return o.denied;let i=await o.rpc.settings(s);if(!i)return c({ok:!1,error:"not_found",slug:n});let a=P({requestUrl:e.requestUrl,host:e.env.ARTIFACT_HOST,devPath:e.env.ARTIFACT_DEV_PATH,slug:n,isPublic:i.meta.public,key:i.meta.public?null:i.key});return v({meta:i.meta,key:i.key,url:a})}async function Pr(t,e){let r=A(t,["slug","limit"]);if(r)return c({ok:!1,error:r});let n=L(t);if(typeof n!="string")return n;let s=tt(t.limit);if(s===!1)return c({ok:!1,error:"limit must be an integer from 1 to 1000"});let o=await S(e,n,"use");if(o.denied)return o.denied;let i=await o.rpc.versions(s!==void 0?{limit:s}:void 0);return i?v({slug:n,activeVersion:o.meta.activeVersion,versions:i}):c({ok:!1,error:"not_found",slug:n})}async function S(t,e,r){let n=C(t.env,e),s=await n.getMeta();return s?Ye(r,s,t.identity,t.access)?{denied:null,rpc:n,meta:s}:{denied:c({ok:!1,error:"forbidden",slug:e})}:{denied:c({ok:!1,error:"not_found",slug:e})}}function L(t){if(typeof t.slug!="string")return c({ok:!1,error:"slug is required"});let e=Qe(t.slug);return e?c({ok:!1,error:e}):t.slug}function Je(t,e){if(t[e]!==void 0)return typeof t[e]!="string"?null:t[e]}function tt(t){if(t!==void 0)return typeof t!="number"||!Number.isInteger(t)||t<1||t>1e3?!1:t}function Fr(t){if(!Array.isArray(t)||t.length===0)return c({ok:!1,error:"files must be a non-empty array"});let e=new TextEncoder,r=new Set,n=[];for(let s of t){if(typeof s!="object"||s===null||Array.isArray(s))return c({ok:!1,error:"each file must be an object { path, content }"});let o=s,i=A(o,["path","content"]);if(i)return c({ok:!1,error:i});if(typeof o.path!="string")return c({ok:!1,error:"file path is required"});let a=Ze(o.path);if(a)return c({ok:!1,error:a,path:o.path});if(r.has(o.path))return c({ok:!1,error:`duplicate path: ${o.path}`});if(r.add(o.path),o.content!==null&&typeof o.content!="string")return c({ok:!1,error:"file content must be a string or null",path:o.path});if(typeof o.content=="string"&&e.encode(o.content).byteLength>br)return c({ok:!1,error:`file exceeds 1 MB: ${o.path}`});n.push({path:o.path,content:o.content})}return n}function A(t,e){for(let r of Object.keys(t))if(!e.includes(r))return`unknown argument: ${r}`;return null}function v(t){return{content:[{type:"text",text:JSON.stringify(t)}]}}function c(t){return{content:[{type:"text",text:JSON.stringify(t)}],isError:!0}}var rt=8*1024*1024,Mr="hugex-artifact",Ur="1.0.0",Dr="2025-06-18",jr=["2024-11-05","2025-03-26","2025-06-18"],qr=["Servidor MCP de HugeX Artifacts (@hugex/artifact).","Contrato de archivos: artifact.json obligatorio { title, libs }, index.html obligatorio, m\xF3dulos cliente con rutas relativas, server.js opcional (export class App extends ArtifactApp importado desde ./artifact-app.js).","No uses localStorage ni sessionStorage: los artifacts del tenant comparten origen. El estado va en la SQLite del facet.","artifact_write exige baseVersion igual a la versi\xF3n activa que devuelven artifact_read (activeVersion) o artifact_versions.","artifact_query solo admite una sentencia SELECT. WITH y las sentencias m\xFAltiples se rechazan."].join(" "),$r="Modo Fase 1 (solo owner): faltan HX_ORA_URL o HX_API_KEY, as\xED que usar y gestionar un artifact exige ser su owner.",Hr="RBAC completo: todas las tools exigen el m\xF3dulo artifacts; usar sigue canUseTool y gestionar sigue canManageTool.";function Vr(t){return`${qr} ${t==="phase1"?$r:Hr}`}async function st(t,e,r){if(t.method!=="POST")return Br();let n=await We(t,e);if(!n.ok)return n.response;let s=Ee(t.headers.get("authorization"));if(!s)return $();let o=await Xe(e,s);if(!o.ok)return o.status===401?$():Wr();let i=o.mode==="rbac"?o.access:null;if(!Gr(t.headers.get("content-type")))return te(415,"Content-Type must be application/json");let a=t.headers.get("content-length");if(a!==null){if(!/^\d+$/.test(a))return te(400,"invalid content-length");if(Number(a)>rt)return te(413,"payload too large")}let u=await t.arrayBuffer();if(u.byteLength>rt)return te(413,"payload too large");let l;try{l=JSON.parse(new TextDecoder().decode(u))}catch{return b(null,-32700,"Parse error",400)}if(Array.isArray(l))return b(null,-32600,"Invalid Request",400,"batch is not supported");if(l===null||typeof l!="object")return b(null,-32600,"Invalid Request",400);let f=Kr(l);return f.ok?f.notification?Xr():Yr(f.request,n.identity,e,t.url,o.mode,i):f.response}function Br(){return new Response(null,{status:405,headers:{Allow:"POST","Referrer-Policy":"no-referrer"}})}function Xr(){return new Response(null,{status:202,headers:{"Referrer-Policy":"no-referrer"}})}function Wr(){return new Response(JSON.stringify({error:"forbidden"}),{status:403,headers:{"Content-Type":"application/json","Referrer-Policy":"no-referrer"}})}function te(t,e){return new Response(e,{status:t,headers:{"Content-Type":"text/plain; charset=utf-8","Referrer-Policy":"no-referrer"}})}function ot(t,e){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":"application/json","Referrer-Policy":"no-referrer"}})}function re(t,e){return ot(200,{jsonrpc:"2.0",id:t,result:e})}function b(t,e,r,n=200,s){let o={code:e,message:r};return s!==void 0&&(o.data=s),ot(n,{jsonrpc:"2.0",id:t,error:o})}function Gr(t){var e;return t?((e=t.split(";",1)[0])==null?void 0:e.trim().toLowerCase())==="application/json":!1}function Kr(t){return t.jsonrpc!=="2.0"||typeof t.method!="string"||t.method.length===0?{ok:!1,response:b(nt(t.id),-32600,"Invalid Request",400)}:t.params!==void 0&&!(Array.isArray(t.params)||typeof t.params=="object"&&t.params!==null)?{ok:!1,response:b(nt(t.id),-32600,"Invalid Request",400)}:!Object.prototype.hasOwnProperty.call(t,"id")||t.method.startsWith("notifications/")?{ok:!0,notification:!0}:it(t.id)?{ok:!0,notification:!1,request:{method:t.method,params:t.params,id:t.id}}:{ok:!1,response:b(null,-32600,"Invalid Request",400)}}function nt(t){return it(t)?t:null}function it(t){return t===null||typeof t=="string"?!0:typeof t=="number"&&Number.isFinite(t)}async function Yr(t,e,r,n,s,o){switch(t.method){case"initialize":return Jr(t,s);case"ping":return re(t.id,{});case"tools/list":return t.params!==void 0&&!ne(t.params)?b(t.id,-32602,"Invalid params"):re(t.id,{tools:ze});case"tools/call":return zr(t,e,r,n,o);default:return b(t.id,-32601,"Method not found")}}function Jr(t,e){if(t.params!==void 0&&!ne(t.params))return b(t.id,-32602,"Invalid params");let r=t.params??{},n=Dr;if(r.protocolVersion!==void 0){if(typeof r.protocolVersion!="string")return b(t.id,-32602,"Invalid params");jr.includes(r.protocolVersion)&&(n=r.protocolVersion)}return re(t.id,{protocolVersion:n,capabilities:{tools:{}},serverInfo:{name:Mr,version:Ur},instructions:Vr(e)})}async function zr(t,e,r,n,s){if(!ne(t.params)||typeof t.params.name!="string"||!t.params.name)return b(t.id,-32602,"Invalid params");let o=Qr(t.params.arguments);if(!o)return b(t.id,-32602,"Invalid params");let i=await et(t.params.name,o,{env:r,identity:e,requestUrl:n,access:s});return re(t.id,i)}function Qr(t){if(t===void 0)return{};if(!ne(t))return null;let e={};for(let r of Object.keys(t))e[r]=t[r];return e}function ne(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Zr(t,e,r,n){let s=new Headers(n);return s.has("content-type")||s.set("content-type","text/plain; charset=utf-8"),k(new Response(t,{status:e,headers:s}),r)}async function en(t,e,r){let n=new URL(t.url),s=!!e.ARTIFACT_HOST&&n.hostname===e.ARTIFACT_HOST;if(!s&&je(n.pathname))return k(await qe(t,e),e.ARTIFACT_FRAME_ANCESTORS);let o=s?void 0:G(n.hostname,e.ARTIFACT_DEV_PATH);if(!s&&!o)return null;let i=Me({pathname:n.pathname,search:n.search,terminal:s,devPrefix:o});if(i.kind==="passthrough")return null;if(i.kind==="mcp")return k(await st(t,e,r),e.ARTIFACT_FRAME_ANCESTORS);if(i.kind==="not-found")return Zr("not found",404,e.ARTIFACT_FRAME_ANCESTORS);if(i.kind==="redirect")return k(new Response(null,{status:308,headers:{Location:i.location}}),e.ARTIFACT_FRAME_ANCESTORS);let a=e.ARTIFACT.get(e.ARTIFACT.idFromName(i.slug)),u=Ue(t,i);return k(await a.fetch(u),e.ARTIFACT_FRAME_ANCESTORS)}export{fe as ARTIFACT_PKG_VERSION,pe as ArtifactDO,me as ArtifactIndexDO,O as HX_HEADER_BASE,N as HX_HEADER_KEY,en as handleArtifactHost};
|