@hugex/artifact 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,11 @@
1
1
  import { DurableObject } from "cloudflare:workers";
2
- import type { ArtifactEnv, ArtifactFile, ArtifactLogEntry, ArtifactMeta, ArtifactRpc, ArtifactVersion, CreateArtifactInput, QueryResult, SettingsInput, WriteInput, WriteResult } from "../types";
2
+ import type { AllowsWorkerInput, AllowsWorkerResult, ArtifactEnv, ArtifactFile, ArtifactLogEntry, ArtifactMeta, ArtifactRpc, ArtifactVersion, CreateArtifactInput, QueryResult, SettingsInput, WorkerGrant, WriteInput, WriteResult } from "../types";
3
3
  /**
4
4
  * One instance per artifact (`idFromName(slug)`).
5
- * Supervisor SQLite holds meta, files, versions, and logs.
6
- * `server.js` runs in a facet named `app`, loaded with `globalOutbound: null` and `env: {}`.
5
+ * Supervisor SQLite holds meta, files, versions, logs, and Worker grants.
6
+ * `server.js` runs in a facet named `app`, loaded with `globalOutbound: null`. Its `env` is
7
+ * `{ HX }` (the tenant's `ArtifactWorkerGateway`, from `ctx.exports`) when the tenant exports
8
+ * it, and `{}` otherwise.
7
9
  */
8
10
  export declare class ArtifactDO extends DurableObject<ArtifactEnv> implements ArtifactRpc {
9
11
  /** Bumped when an activation window expires so a late health check cannot publish. */
@@ -45,6 +47,20 @@ export declare class ArtifactDO extends DurableObject<ArtifactEnv> implements Ar
45
47
  ok: true;
46
48
  oraSyncFailed?: boolean;
47
49
  } | null>;
50
+ allowsWorker(input: AllowsWorkerInput): Promise<AllowsWorkerResult>;
51
+ listWorkerGrants(): Promise<WorkerGrant[] | null>;
52
+ grantWorker(input: {
53
+ flowId: string;
54
+ grantedBy: string;
55
+ expectUuid: string;
56
+ expectOwner: string;
57
+ }): Promise<WorkerGrant | null>;
58
+ revokeWorker(input: {
59
+ flowId: string;
60
+ expectUuid: string;
61
+ }): Promise<{
62
+ removed: boolean;
63
+ } | null>;
48
64
  /** Harness / diagnostics: supervisor SQLite size and row counts. */
49
65
  storageStats(): Promise<{
50
66
  databaseSize: number;
@@ -71,6 +87,8 @@ export declare class ArtifactDO extends DurableObject<ArtifactEnv> implements Ar
71
87
  private markFailed;
72
88
  /** Active/previous/meta move together, and the index is marked dirty in the same transaction. */
73
89
  private promote;
90
+ private workerGateway;
91
+ private hasWorkerGateway;
74
92
  private runtimeId;
75
93
  private loadApp;
76
94
  private facetOf;
package/dist/hash.d.ts CHANGED
@@ -12,12 +12,20 @@ export declare function truncateUtf8(text: string, maxBytes: number): string;
12
12
  */
13
13
  export declare function hashFileSet(files: ReadonlyMap<string, string> | Record<string, string>): Promise<string>;
14
14
  export declare function sameFileSet(a: ReadonlyMap<string, string>, b: ReadonlyMap<string, string>): boolean;
15
- /** Stable config mixed into runtimeId. `globalOutbound: null` and empty env are part of the contract. */
16
- export declare function artifactWorkerConfig(compatibilityDate?: string): {
15
+ /** Name of the tenant entrypoint the loader binds as `env.HX` when `ctx.exports` has it. */
16
+ export declare const ARTIFACT_GATEWAY_EXPORT = "ArtifactWorkerGateway";
17
+ /**
18
+ * Stable config mixed into runtimeId. `globalOutbound: null` is part of the contract.
19
+ * `env` describes the bindings: empty, or `HX` bound to the tenant gateway (props are set by
20
+ * the loader per artifact, so only the entrypoint name enters the hash).
21
+ */
22
+ export declare function artifactWorkerConfig(compatibilityDate?: string, opts?: {
23
+ gateway?: boolean;
24
+ }): {
17
25
  compatibilityDate: string;
18
26
  mainModule: string;
19
27
  globalOutbound: null;
20
- env: Record<string, never>;
28
+ env: Record<string, string>;
21
29
  };
22
30
  /**
23
31
  * runtimeId = sha256(server modules + package version + compatibilityDate + config).
@@ -13,6 +13,14 @@ export type ArtifactRoute = {
13
13
  key: string;
14
14
  internalPath: string;
15
15
  basePath: string;
16
+ }
17
+ /** `<base>/__hx/agent/<flowId>/<sessionId>`: same-origin proxy to a granted Worker. */
18
+ | {
19
+ kind: "agent";
20
+ slug: string;
21
+ key: string;
22
+ flowId: string;
23
+ sessionId: string;
16
24
  };
17
25
  export interface RouteInput {
18
26
  pathname: string;
package/dist/host.d.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  import { artifactDevPrefix } from "./dev-prefix";
2
- import type { ArtifactEnv } from "./types";
2
+ import type { ArtifactEnv, ArtifactHostOptions } from "./types";
3
3
  export { artifactDevPrefix };
4
4
  /**
5
5
  * Terminal on `ARTIFACT_HOST`. On localhost, 127.0.0.1, or [::1], mounts the same
6
6
  * routes under `ARTIFACT_DEV_PATH` (for example `/app/...`). Any other hostname
7
7
  * ignores that variable. Returns null when the path is unrelated.
8
+ * `options.agentProxy` turns on `<base>/__hx/agent/<flowId>/<sessionId>`.
8
9
  */
9
- export declare function handleArtifactHost(request: Request, env: ArtifactEnv, ctx: ExecutionContext): Promise<Response | null>;
10
+ export declare function handleArtifactHost(request: Request, env: ArtifactEnv, ctx: ExecutionContext, options?: ArtifactHostOptions): Promise<Response | null>;
package/dist/index.js CHANGED
@@ -1,5 +1,57 @@
1
- import{DurableObject as jt}from"cloudflare:workers";var bt=[{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:{}},{name:"daisyui",version:"5.7.47",url:"https://cdn.jsdelivr.net/npm/daisyui@5.7.47/daisyui.css",integrity:"sha384-7aEtEHaaQlvolkHZ6DyoGlsNOFe/zuR0er02iYikX9npKr+C4ANk7t3C7wzeItRf",kind:"stylesheet",specifiers:{},stylesheets:[{url:"https://cdn.jsdelivr.net/npm/daisyui@5.7.47/daisyui.css",integrity:"sha384-7aEtEHaaQlvolkHZ6DyoGlsNOFe/zuR0er02iYikX9npKr+C4ANk7t3C7wzeItRf"}]},{name:"lucide",version:"1.55.0",url:"https://cdn.jsdelivr.net/npm/lucide@1.55.0/dist/umd/lucide.min.js",integrity:"sha384-SZUFq9Dx112fyzY/iIBEjyd2gu3jY4XVhp+LUNXSpEMB2IEm/TOoMTNH4BHtQ6Hz",kind:"classic",specifiers:{},scripts:[{url:"https://cdn.jsdelivr.net/npm/lucide@1.55.0/dist/umd/lucide.min.js",integrity:"sha384-SZUFq9Dx112fyzY/iIBEjyd2gu3jY4XVhp+LUNXSpEMB2IEm/TOoMTNH4BHtQ6Hz"}]},{name:"echarts",version:"6.1.0",url:"https://cdn.jsdelivr.net/npm/echarts@6.1.0/dist/echarts.esm.min.js",integrity:"sha384-2svH5QplTeBKhRXWxXOJE2P6pRpgnqVq8l8U1dYXUBXvc2zJ/FMMardtnPnnCXnt",kind:"module",specifiers:{echarts:{url:"https://cdn.jsdelivr.net/npm/echarts@6.1.0/dist/echarts.esm.min.js",integrity:"sha384-2svH5QplTeBKhRXWxXOJE2P6pRpgnqVq8l8U1dYXUBXvc2zJ/FMMardtnPnnCXnt"}}},{name:"tabulator-tables",version:"6.6.1",url:"https://cdn.jsdelivr.net/npm/tabulator-tables@6.6.1/dist/js/tabulator_esm.min.mjs",integrity:"sha384-BWRvD85P1JRHxztvZTpRvryElVps0W2/kgg3atlHAcR6zK70eaoV+IwUzLbn6Cao",kind:"module",specifiers:{"tabulator-tables":{url:"https://cdn.jsdelivr.net/npm/tabulator-tables@6.6.1/dist/js/tabulator_esm.min.mjs",integrity:"sha384-BWRvD85P1JRHxztvZTpRvryElVps0W2/kgg3atlHAcR6zK70eaoV+IwUzLbn6Cao"}},stylesheets:[{url:"https://cdn.jsdelivr.net/npm/tabulator-tables@6.6.1/dist/css/tabulator.min.css",integrity:"sha384-xnEc77Tm0GtDMa5SK6wMci55eU0E+KodAqTli8SS1h1yHo/bRbtEZ+gTgwCEs3d6"}]},{name:"luxon",version:"3.7.2",url:"https://cdn.jsdelivr.net/npm/luxon@3.7.2/build/es6/luxon.mjs",integrity:"sha384-UYCYrzxx4pAeJgaUugx63CVAAg6id38z8o/5HrjiYZOSuT/Rw5FQXmbbA4M/hzfP",kind:"module",specifiers:{luxon:{url:"https://cdn.jsdelivr.net/npm/luxon@3.7.2/build/es6/luxon.mjs",integrity:"sha384-UYCYrzxx4pAeJgaUugx63CVAAg6id38z8o/5HrjiYZOSuT/Rw5FQXmbbA4M/hzfP"}}},{name:"sortablejs",version:"1.15.7",url:"https://cdn.jsdelivr.net/npm/sortablejs@1.15.7/modular/sortable.esm.js",integrity:"sha384-epMYlv+pmbMc16ZCUzLpj1OfyiZhjzumHPnQk8CNKG4yR+Dh/+7y7WMSQqODNIE9",kind:"module",specifiers:{sortablejs:{url:"https://cdn.jsdelivr.net/npm/sortablejs@1.15.7/modular/sortable.esm.js",integrity:"sha384-epMYlv+pmbMc16ZCUzLpj1OfyiZhjzumHPnQk8CNKG4yR+Dh/+7y7WMSQqODNIE9"}}},{name:"marked",version:"18.1.0",url:"https://cdn.jsdelivr.net/npm/marked@18.1.0/lib/marked.esm.js",integrity:"sha384-snMBC5fa3uu2TE5nbJfoysnXEnXn+BPEHkzGLpV/ptEaRtamTgxGuWQvm0LUGEP1",kind:"module",specifiers:{marked:{url:"https://cdn.jsdelivr.net/npm/marked@18.1.0/lib/marked.esm.js",integrity:"sha384-snMBC5fa3uu2TE5nbJfoysnXEnXn+BPEHkzGLpV/ptEaRtamTgxGuWQvm0LUGEP1"}}},{name:"dompurify",version:"3.4.16",url:"https://cdn.jsdelivr.net/npm/dompurify@3.4.16/dist/purify.es.mjs",integrity:"sha384-a/XFwrpeq88LPRbyWBWlLnv0sUPkA6mAADSFODl/XWtg+PHClcleY9DmdjDED9+Z",kind:"module",specifiers:{dompurify:{url:"https://cdn.jsdelivr.net/npm/dompurify@3.4.16/dist/purify.es.mjs",integrity:"sha384-a/XFwrpeq88LPRbyWBWlLnv0sUPkA6mAADSFODl/XWtg+PHClcleY9DmdjDED9+Z"}}},{name:"alpinejs",version:"3.17.4",url:"https://cdn.jsdelivr.net/npm/alpinejs@3.17.4/dist/cdn.min.js",integrity:"sha384-5/joNqFnRyVWzXp99bHot6RHG+EksGp+USSgZwPar7T9SD9PKKER37n/8bXBAZGd",kind:"classic",specifiers:{},scripts:[{url:"https://cdn.jsdelivr.net/npm/alpinejs@3.17.4/dist/cdn.min.js",integrity:"sha384-5/joNqFnRyVWzXp99bHot6RHG+EksGp+USSgZwPar7T9SD9PKKER37n/8bXBAZGd",defer:!0}]}],Se=new Map(bt.map(t=>[t.name,t]));function Le(){let t=Se.get("@tailwindcss/browser");if(!t)throw new Error("catalog missing @tailwindcss/browser");return{url:t.url,integrity:t.integrity}}function V(t){let e=[],r=[],n=new Set,s=(p,m)=>{if(n.has(p))return;let g=Se.get(p);if(!g){m&&e.push(`unknown lib: ${p}`),n.add(p);return}n.add(p),r.push(g);for(let v of g.needs??[])s(v,!1)};for(let p of t)s(p,!0);let i={},o={},a=[],c=new Set,l=[],f=new Set;for(let p of r){for(let[m,g]of Object.entries(p.specifiers))i[m]=g.url,o[g.url]=g.integrity;for(let m of p.stylesheets??[])c.has(m.url)||(c.add(m.url),a.push(m));for(let m of p.scripts??[])f.has(m.url)||(f.add(m.url),l.push(m))}return{imports:i,integrity:o,stylesheets:a,scripts:l,warnings:e}}var h={fileBytes:1e6,versionBytes:5e6,supervisorBytes:2e8,logRows:1e3,logMessageBytes:2048,browserLogsPerSecond:20,pathMaxChars:200,healthTimeoutMs:5e3,keepVersions:50},G="2025-05-15";async function R(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 K(t,e){let r=new TextEncoder,n=r.encode(t),s=r.encode(e),i=Math.max(n.length,s.length),o=n.length^s.length;for(let a=0;a<i;a++)o|=(n[a]??0)^(s[a]??0);return o===0}function x(t){return new TextEncoder().encode(t).length}var vt=/\/k\/[^/]+\//g;function w(t){return t.replace(vt,"/k/***/")}function ae(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 Ie(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 R(s)]);return R(JSON.stringify(r))}function le(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 ce(t=G){return{compatibilityDate:t,mainModule:"server.js",globalOutbound:null,env:{}}}async function Ne(t){let e=["artifact-app.js",t.appSource,"server.js",t.serverJs,t.pkgVersion,t.compatibilityDate,JSON.stringify(t.config)].join("\0");return R(e)}function ue(){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 y(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 Y(t){return/SQLITE_FULL|database or disk is full/i.test(y(t))}function de(t,e){let r=Promise.resolve(t);r.catch(()=>{});let n,s=new Promise((i,o)=>{n=setTimeout(()=>o(new Error("timeout")),e)});return Promise.race([r,s]).finally(()=>{n!==void 0&&clearTimeout(n)})}var Et=["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: https://cdn.jsdelivr.net","connect-src 'self'","base-uri 'self'","form-action 'self'"],At=/^(?: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 Tt(t){let e=(t??"").split(/\s+/).filter(r=>At.test(r));return e.length===0?"frame-ancestors 'none'":`frame-ancestors ${e.join(" ")}`}function Oe(t){return[...Et,Tt(t)].join("; ")}var bn=Oe(),Rt=` --font-sans: "PolySans", ui-sans-serif, system-ui, sans-serif;
2
- --font-inter: "Inter", ui-sans-serif, system-ui, sans-serif;`,_e=` --color-primary-50: var(--theme-primary-50);
1
+ import{DurableObject as $t}from"cloudflare:workers";var wt=[{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:{}},{name:"daisyui",version:"5.7.47",url:"https://cdn.jsdelivr.net/npm/daisyui@5.7.47/daisyui.css",integrity:"sha384-7aEtEHaaQlvolkHZ6DyoGlsNOFe/zuR0er02iYikX9npKr+C4ANk7t3C7wzeItRf",kind:"stylesheet",specifiers:{},stylesheets:[{url:"https://cdn.jsdelivr.net/npm/daisyui@5.7.47/daisyui.css",integrity:"sha384-7aEtEHaaQlvolkHZ6DyoGlsNOFe/zuR0er02iYikX9npKr+C4ANk7t3C7wzeItRf"}]},{name:"lucide",version:"1.55.0",url:"https://cdn.jsdelivr.net/npm/lucide@1.55.0/dist/umd/lucide.min.js",integrity:"sha384-SZUFq9Dx112fyzY/iIBEjyd2gu3jY4XVhp+LUNXSpEMB2IEm/TOoMTNH4BHtQ6Hz",kind:"classic",specifiers:{},scripts:[{url:"https://cdn.jsdelivr.net/npm/lucide@1.55.0/dist/umd/lucide.min.js",integrity:"sha384-SZUFq9Dx112fyzY/iIBEjyd2gu3jY4XVhp+LUNXSpEMB2IEm/TOoMTNH4BHtQ6Hz"}]},{name:"echarts",version:"6.1.0",url:"https://cdn.jsdelivr.net/npm/echarts@6.1.0/dist/echarts.esm.min.js",integrity:"sha384-2svH5QplTeBKhRXWxXOJE2P6pRpgnqVq8l8U1dYXUBXvc2zJ/FMMardtnPnnCXnt",kind:"module",specifiers:{echarts:{url:"https://cdn.jsdelivr.net/npm/echarts@6.1.0/dist/echarts.esm.min.js",integrity:"sha384-2svH5QplTeBKhRXWxXOJE2P6pRpgnqVq8l8U1dYXUBXvc2zJ/FMMardtnPnnCXnt"}}},{name:"tabulator-tables",version:"6.6.1",url:"https://cdn.jsdelivr.net/npm/tabulator-tables@6.6.1/dist/js/tabulator_esm.min.mjs",integrity:"sha384-BWRvD85P1JRHxztvZTpRvryElVps0W2/kgg3atlHAcR6zK70eaoV+IwUzLbn6Cao",kind:"module",specifiers:{"tabulator-tables":{url:"https://cdn.jsdelivr.net/npm/tabulator-tables@6.6.1/dist/js/tabulator_esm.min.mjs",integrity:"sha384-BWRvD85P1JRHxztvZTpRvryElVps0W2/kgg3atlHAcR6zK70eaoV+IwUzLbn6Cao"}},stylesheets:[{url:"https://cdn.jsdelivr.net/npm/tabulator-tables@6.6.1/dist/css/tabulator.min.css",integrity:"sha384-xnEc77Tm0GtDMa5SK6wMci55eU0E+KodAqTli8SS1h1yHo/bRbtEZ+gTgwCEs3d6"}]},{name:"luxon",version:"3.7.2",url:"https://cdn.jsdelivr.net/npm/luxon@3.7.2/build/es6/luxon.mjs",integrity:"sha384-UYCYrzxx4pAeJgaUugx63CVAAg6id38z8o/5HrjiYZOSuT/Rw5FQXmbbA4M/hzfP",kind:"module",specifiers:{luxon:{url:"https://cdn.jsdelivr.net/npm/luxon@3.7.2/build/es6/luxon.mjs",integrity:"sha384-UYCYrzxx4pAeJgaUugx63CVAAg6id38z8o/5HrjiYZOSuT/Rw5FQXmbbA4M/hzfP"}}},{name:"sortablejs",version:"1.15.7",url:"https://cdn.jsdelivr.net/npm/sortablejs@1.15.7/modular/sortable.esm.js",integrity:"sha384-epMYlv+pmbMc16ZCUzLpj1OfyiZhjzumHPnQk8CNKG4yR+Dh/+7y7WMSQqODNIE9",kind:"module",specifiers:{sortablejs:{url:"https://cdn.jsdelivr.net/npm/sortablejs@1.15.7/modular/sortable.esm.js",integrity:"sha384-epMYlv+pmbMc16ZCUzLpj1OfyiZhjzumHPnQk8CNKG4yR+Dh/+7y7WMSQqODNIE9"}}},{name:"marked",version:"18.1.0",url:"https://cdn.jsdelivr.net/npm/marked@18.1.0/lib/marked.esm.js",integrity:"sha384-snMBC5fa3uu2TE5nbJfoysnXEnXn+BPEHkzGLpV/ptEaRtamTgxGuWQvm0LUGEP1",kind:"module",specifiers:{marked:{url:"https://cdn.jsdelivr.net/npm/marked@18.1.0/lib/marked.esm.js",integrity:"sha384-snMBC5fa3uu2TE5nbJfoysnXEnXn+BPEHkzGLpV/ptEaRtamTgxGuWQvm0LUGEP1"}}},{name:"dompurify",version:"3.4.16",url:"https://cdn.jsdelivr.net/npm/dompurify@3.4.16/dist/purify.es.mjs",integrity:"sha384-a/XFwrpeq88LPRbyWBWlLnv0sUPkA6mAADSFODl/XWtg+PHClcleY9DmdjDED9+Z",kind:"module",specifiers:{dompurify:{url:"https://cdn.jsdelivr.net/npm/dompurify@3.4.16/dist/purify.es.mjs",integrity:"sha384-a/XFwrpeq88LPRbyWBWlLnv0sUPkA6mAADSFODl/XWtg+PHClcleY9DmdjDED9+Z"}}},{name:"alpinejs",version:"3.17.4",url:"https://cdn.jsdelivr.net/npm/alpinejs@3.17.4/dist/cdn.min.js",integrity:"sha384-5/joNqFnRyVWzXp99bHot6RHG+EksGp+USSgZwPar7T9SD9PKKER37n/8bXBAZGd",kind:"classic",specifiers:{},scripts:[{url:"https://cdn.jsdelivr.net/npm/alpinejs@3.17.4/dist/cdn.min.js",integrity:"sha384-5/joNqFnRyVWzXp99bHot6RHG+EksGp+USSgZwPar7T9SD9PKKER37n/8bXBAZGd",defer:!0}]}],Le=new Map(wt.map(t=>[t.name,t]));function _e(){let t=Le.get("@tailwindcss/browser");if(!t)throw new Error("catalog missing @tailwindcss/browser");return{url:t.url,integrity:t.integrity}}function $(t){let e=[],r=[],n=new Set,s=(p,g)=>{if(n.has(p))return;let m=Le.get(p);if(!m){g&&e.push(`unknown lib: ${p}`),n.add(p);return}n.add(p),r.push(m);for(let b of m.needs??[])s(b,!1)};for(let p of t)s(p,!0);let o={},i={},a=[],c=new Set,l=[],f=new Set;for(let p of r){for(let[g,m]of Object.entries(p.specifiers))o[g]=m.url,i[m.url]=m.integrity;for(let g of p.stylesheets??[])c.has(g.url)||(c.add(g.url),a.push(g));for(let g of p.scripts??[])f.has(g.url)||(f.add(g.url),l.push(g))}return{imports:o,integrity:i,stylesheets:a,scripts:l,warnings:e}}var h={fileBytes:1e6,versionBytes:5e6,supervisorBytes:2e8,logRows:1e3,logMessageBytes:2048,browserLogsPerSecond:20,pathMaxChars:200,healthTimeoutMs:5e3,keepVersions:50},U="2025-05-15";async function R(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 Y(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 k(t){return new TextEncoder().encode(t).length}var Rt=/\/k\/[^/]+\//g;function x(t){return t.replace(Rt,"/k/***/")}function le(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(;k(s)>e&&s.length>0;)s=s.slice(0,-1);return s}async function Oe(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 R(s)]);return R(JSON.stringify(r))}function ce(t,e){if(t.size!==e.size)return!1;for(let[r,n]of t)if(e.get(r)!==n)return!1;return!0}var ue="ArtifactWorkerGateway";function de(t=U,e={}){return{compatibilityDate:t,mainModule:"server.js",globalOutbound:null,env:e.gateway?{HX:ue}:{}}}async function Ne(t){let e=["artifact-app.js",t.appSource,"server.js",t.serverJs,t.pkgVersion,t.compatibilityDate,JSON.stringify(t.config)].join("\0");return R(e)}function fe(){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 y(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 z(t){return/SQLITE_FULL|database or disk is full/i.test(y(t))}function pe(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)})}function Ce(t){return`<script>
2
+ (function () {
3
+ var base = ${JSON.stringify(t).replaceAll("<","\\u003c")}, sessionId = crypto.randomUUID();
4
+ window.hx = window.hx || {};
5
+ window.hx.worker = function (flowId, opts) {
6
+ if (typeof flowId !== 'string' || !/^[A-Za-z0-9_-]+$/.test(flowId)) throw new Error('Invalid flowId');
7
+ var api = Object.assign({}, opts || {}), socket, timer, closed = false, pending = [], text = '';
8
+ function emit(name, value) { if (typeof api[name] === 'function') api[name](value); }
9
+ function send(type, content) {
10
+ if (closed) throw new Error('Worker connection closed');
11
+ var frame = type + ':' + content;
12
+ if (socket && socket.readyState === 1) socket.send(frame);
13
+ else pending.push(frame);
14
+ }
15
+ function connect() {
16
+ var url = new URL('__hx/agent/' + flowId + '/' + sessionId, new URL(base, location.href));
17
+ url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
18
+ socket = new WebSocket(url.href);
19
+ socket.onopen = function () { pending.splice(0).forEach(function (frame) { socket.send(frame); }); };
20
+ socket.onmessage = function (event) {
21
+ if (typeof event.data !== 'string') return;
22
+ var split = event.data.indexOf('::');
23
+ if (split < 0) return;
24
+ var type = event.data.slice(0, split), content = event.data.slice(split + 2);
25
+ try {
26
+ if (type === 'TS') { text += content; emit('onToken', content); }
27
+ else if (type === 'RS') emit('onReasoning', content);
28
+ else if (type === 'TSC') { var message = text; text = ''; emit('onMessage', message); }
29
+ else if (type === 'SE') emit('onEvent', JSON.parse(content));
30
+ else if (type === 'HIS') { text = ''; emit('onHistory', JSON.parse(content)); }
31
+ else if (type === 'CFG') emit('onConfig', JSON.parse(content));
32
+ else if (type === 'ERR') emit('onError', content);
33
+ } catch (error) { emit('onError', error); }
34
+ };
35
+ socket.onerror = function () { emit('onError', 'Worker connection error'); };
36
+ socket.onclose = function () {
37
+ text = '';
38
+ if (!closed) timer = setTimeout(connect, 1000);
39
+ };
40
+ }
41
+ api.send = function (message) {
42
+ if (typeof message !== 'string' && (!message || typeof message.text !== 'string')) throw new Error('Invalid message');
43
+ text = '';
44
+ send('M', typeof message === 'string' ? message : JSON.stringify(message));
45
+ };
46
+ api.clear = function () { text = ''; send('CH', '1'); };
47
+ api.auth = function (name, value) { send('AUT', JSON.stringify({ name: name, value: value })); };
48
+ api.close = function () { closed = true; clearTimeout(timer); pending = []; socket.close(); };
49
+ connect();
50
+ return api;
51
+ };
52
+ })();
53
+ </script>`}var kt=["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: https://cdn.jsdelivr.net","connect-src 'self'","base-uri 'self'","form-action 'self'"],xt=/^(?: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 St(t){let e=(t??"").split(/\s+/).filter(r=>xt.test(r));return e.length===0?"frame-ancestors 'none'":`frame-ancestors ${e.join(" ")}`}function Fe(t){return[...kt,St(t)].join("; ")}var Ln=Fe(),It=` --font-sans: "PolySans", ui-sans-serif, system-ui, sans-serif;
54
+ --font-inter: "Inter", ui-sans-serif, system-ui, sans-serif;`,Pe=` --color-primary-50: var(--theme-primary-50);
3
55
  --color-primary-100: var(--theme-primary-100);
4
56
  --color-primary-200: var(--theme-primary-200);
5
57
  --color-primary-300: var(--theme-primary-300);
@@ -47,13 +99,13 @@ import{DurableObject as jt}from"cloudflare:workers";var bt=[{name:"preact",versi
47
99
  --color-bg-surface: var(--theme-bg-surface);
48
100
  --color-border-subtle: var(--theme-border-subtle);
49
101
  --color-text-base: var(--theme-text-base);
50
- --color-text-muted: var(--theme-text-muted);`;function Ce(t="none"){return t==="hugex"?`@theme {
51
- ${Rt}
102
+ --color-text-muted: var(--theme-text-muted);`;function Me(t="none"){return t==="hugex"?`@theme {
103
+ ${It}
52
104
 
53
- ${_e}
105
+ ${Pe}
54
106
  }`:`@theme {
55
- ${_e}
56
- }`}var vn=Ce("hugex"),xt=`:root,
107
+ ${Pe}
108
+ }`}var _n=Me("hugex"),Lt=`:root,
57
109
  [data-theme="light"] {
58
110
  --theme-primary-50: #FAF5FF;
59
111
  --theme-primary-100: #F0E0FF;
@@ -104,7 +156,7 @@ ${_e}
104
156
  --theme-border-subtle: #dad3ed;
105
157
  --theme-text-base: #2A2438;
106
158
  --theme-text-muted: #7E7492;
107
- }`,wt=`<script type="module">
159
+ }`,_t=`<script type="module">
108
160
  const baseHref = document.querySelector("base")?.href || location.href;
109
161
  const wsUrl = new URL("__hx/ws", baseHref);
110
162
  wsUrl.protocol = location.protocol === "https:" ? "wss:" : "ws:";
@@ -133,18 +185,18 @@ window.addEventListener("unhandledrejection", (ev) => {
133
185
  const text = reason && reason.stack ? reason.stack : (reason && reason.message ? reason.message : String(reason));
134
186
  report(redact(text));
135
187
  });
136
- </script>`;function O(t){return t.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;")}function kt(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=Ce(e.theme??"none"),i=(e.stylesheets??[]).map(l=>`<link rel="stylesheet" href="${O(l.url)}" integrity="${O(l.integrity)}" crossorigin="anonymous">`).join(`
137
- `),o=(e.scripts??[]).map(l=>`<script ${l.defer?"defer ":""}src="${O(l.url)}" integrity="${O(l.integrity)}" crossorigin="anonymous"></script>`).join(`
138
- `),a=[`<base href="${O(r)}">`,i,'<script>globalThis.process={env:{NODE_ENV:"production"}};</script>',`<script type="importmap">
188
+ </script>`;function P(t){return t.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;")}function Ot(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=Me(e.theme??"none"),o=(e.stylesheets??[]).map(l=>`<link rel="stylesheet" href="${P(l.url)}" integrity="${P(l.integrity)}" crossorigin="anonymous">`).join(`
189
+ `),i=(e.scripts??[]).map(l=>`<script ${l.defer?"defer ":""}src="${P(l.url)}" integrity="${P(l.integrity)}" crossorigin="anonymous"></script>`).join(`
190
+ `),a=[`<base href="${P(r)}">`,o,'<script>globalThis.process={env:{NODE_ENV:"production"}};</script>',`<script type="importmap">
139
191
  ${n}
140
- </script>`,o,`<script src="${O(e.tailwindUrl)}" integrity="${O(e.tailwindIntegrity)}" crossorigin="anonymous"></script>`,`<style>
141
- ${xt}
192
+ </script>`,i,`<script src="${P(e.tailwindUrl)}" integrity="${P(e.tailwindIntegrity)}" crossorigin="anonymous"></script>`,`<style>
193
+ ${Lt}
142
194
  </style>`,`<style type="text/tailwindcss">
143
195
  ${s}
144
- </style>`,wt].filter(Boolean).join(`
196
+ </style>`,Ce(r),_t].filter(Boolean).join(`
145
197
  `),c=/<head[^>]*>/i;return c.test(t)?t.replace(c,l=>`${l}
146
198
  ${a}`):t.includes("</head>")?t.replace("</head>",`${a}
147
- </head>`):a+t}function Pe(t,e,r,n="none"){let s=V(r),i=Le();return kt(t,{baseHref:e,imports:s.imports,integrity:s.integrity,tailwindUrl:i.url,tailwindIntegrity:i.integrity,theme:n,stylesheets:s.stylesheets,scripts:s.scripts})}function Fe(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 St=["image/svg+xml","application/xhtml+xml"];function Lt(t){let e=t.toLowerCase();return St.some(r=>e.includes(r))}function It(t){let e=t!=null&&t.trim()?t.trim():"no-store";return/\bno-transform\b/i.test(e)?e:`${e}, no-transform`}function S(t,e){let r=new Headers(t.headers);r.set("Referrer-Policy","no-referrer"),r.set("Cache-Control",It(r.get("Cache-Control"))),r.set("X-Content-Type-Options","nosniff"),r.delete("Set-Cookie");let n=r.get("content-type")??"",s=Oe(e);Lt(n)&&(s+="; sandbox"),r.set("Content-Security-Policy",s);let i="webSocket"in t?t.webSocket??void 0:void 0;return new Response(t.body,{status:t.status,statusText:t.statusText,headers:r,webSocket:i})}var Nt=`function isSingleSelect(input) {
199
+ </head>`):a+t}function Ue(t,e,r,n="none"){let s=$(r),o=_e();return Ot(t,{baseHref:e,imports:s.imports,integrity:s.integrity,tailwindUrl:o.url,tailwindIntegrity:o.integrity,theme:n,stylesheets:s.stylesheets,scripts:s.scripts})}function je(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 Nt=["image/svg+xml","application/xhtml+xml"];function Ct(t){let e=t.toLowerCase();return Nt.some(r=>e.includes(r))}function Pt(t){let e=t!=null&&t.trim()?t.trim():"no-store";return/\bno-transform\b/i.test(e)?e:`${e}, no-transform`}function S(t,e){let r=new Headers(t.headers);r.set("Referrer-Policy","no-referrer"),r.set("Cache-Control",Pt(r.get("Cache-Control"))),r.set("X-Content-Type-Options","nosniff"),r.delete("Set-Cookie");let n=r.get("content-type")??"",s=Fe(e);Ct(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 Ft=`function isSingleSelect(input) {
148
200
  if (typeof input !== "string") return false;
149
201
  const sql = input;
150
202
  let i = 0;
@@ -222,12 +274,12 @@ ${a}`):t.includes("</head>")?t.replace("</head>",`${a}
222
274
  i += 1;
223
275
  }
224
276
  return true;
225
- }`;function Me(t){if(typeof t!="string")return!1;let e=t,r=0,n=e.length;function s(){for(;r<n;){let o=e[r];if(o===" "||o===" "||o===`
226
- `||o==="\r"||o==="\f"){r+=1;continue}if(o==="-"&&e[r+1]==="-"){for(r+=2;r<n&&e[r]!==`
227
- `;)r+=1;continue}if(o==="/"&&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 i=!1;for(;r<n;){if(i)return s()?r>=n:!1;let o=e[r];if(o==="'"||o==='"'||o==="`"){let a=o;r+=1;let c=!1;for(;r<n;){if(e[r]===a){if(e[r+1]===a){r+=2;continue}r+=1,c=!0;break}r+=1}if(!c)return!1;continue}if(o==="-"&&e[r+1]==="-"){for(r+=2;r<n&&e[r]!==`
228
- `;)r+=1;continue}if(o==="/"&&e[r+1]==="*"){let a=e.indexOf("*/",r+2);if(a<0)return!1;r=a+2;continue}if(o===";"){i=!0,r+=1;continue}r+=1}return!0}function je(){return`export ${Nt}`}var fe=`import { DurableObject } from "cloudflare:workers";
277
+ }`;function De(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===`
278
+ `||i==="\r"||i==="\f"){r+=1;continue}if(i==="-"&&e[r+1]==="-"){for(r+=2;r<n&&e[r]!==`
279
+ `;)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 c=!1;for(;r<n;){if(e[r]===a){if(e[r+1]===a){r+=2;continue}r+=1,c=!0;break}r+=1}if(!c)return!1;continue}if(i==="-"&&e[r+1]==="-"){for(r+=2;r<n&&e[r]!==`
280
+ `;)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 qe(){return`export ${Ft}`}var ge=`import { DurableObject } from "cloudflare:workers";
229
281
 
230
- ${je()}
282
+ ${qe()}
231
283
 
232
284
  function plainRows(rows) {
233
285
  return rows.map((row) => {
@@ -252,7 +304,7 @@ export class ArtifactApp extends DurableObject {
252
304
  return plainRows(this.ctx.storage.sql.exec(sql).toArray());
253
305
  }
254
306
  }
255
- `;var F="x-hx-artifact-key",M="x-hx-artifact-base";function _t(t){return t.includes("content")}function De(t,e,r){_t(r)&&(t(`CREATE TABLE IF NOT EXISTS blob (
307
+ `;var j="x-hx-artifact-key",D="x-hx-artifact-base";function Mt(t){return t.includes("content")}function We(t,e,r){Mt(r)&&(t(`CREATE TABLE IF NOT EXISTS blob (
256
308
  hash TEXT PRIMARY KEY,
257
309
  content TEXT NOT NULL
258
310
  )`),t(`INSERT OR IGNORE INTO blob (hash, content)
@@ -262,13 +314,14 @@ export class ArtifactApp extends DurableObject {
262
314
  hash TEXT NOT NULL,
263
315
  PRIMARY KEY (version, path)
264
316
  )`),t(`INSERT INTO file_dedup (version, path, hash)
265
- SELECT version, path, hash FROM file`),t("DROP TABLE file"),t("ALTER TABLE file_dedup RENAME TO file"))}function Ot(t){let e=new Set;t.activeVersion&&e.add(t.activeVersion);for(let s of t.logVersionIds)s&&e.add(s);let n=[...t.versionRows].sort((s,i)=>{let o=s.createdAt.localeCompare(i.createdAt);return o!==0?o:s.id.localeCompare(i.id)}).slice(-t.keepVersions);for(let s of n)e.add(s.id);return e}function qe(t,e,r){let n=128,s=new Set;for(let[i,o]of t){let a=e.get(i)??"";n+=x(i)+48,!s.has(a)&&!r.has(a)&&(s.add(a),n+=x(o)+x(a)+64)}return n}function pe(t,e,r,n=h.keepVersions){let s=e("SELECT id, created_at AS createdAt FROM version").map(c=>({id:String(c.id),createdAt:String(c.createdAt)})),i=e("SELECT DISTINCT version FROM log WHERE version IS NOT NULL AND version != ''").map(c=>String(c.version)),o=Ot({activeVersion:r,versionRows:s,logVersionIds:i,keepVersions:n});if(o.size>=s.length){Ue(t,e);return}let a=s.map(c=>c.id).filter(c=>!o.has(c));for(let c of a)t("DELETE FROM file WHERE version = ?",c),t("DELETE FROM version WHERE id = ?",c);Ue(t,e)}function Ue(t,e){let r=new Set(e("SELECT DISTINCT hash FROM file").map(n=>String(n.hash)));for(let n of e("SELECT hash FROM blob")){let s=String(n.hash);r.has(s)||t("DELETE FROM blob WHERE hash = ?",s)}}var Ct=[{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 Pt(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 He(t,e){let r=[];for(let s of Ct)e.includes(s.name)||(t(s.ddl),r.push(s.name));let n=Pt(r);return n&&t(n),r}async function Ve(t,e,r=fetch,n=5e3){var a,c;let s=(a=t.HX_ORA_URL)==null?void 0:a.trim().replace(/\/$/,"");if(!s)return{ok:!1,error:"HX_ORA_URL missing"};let i=new AbortController,o=setTimeout(()=>i.abort(),n);try{let l=await r(`${s}/internal/artifacts/${encodeURIComponent(e)}`,{method:"DELETE",headers:{Authorization:((c=t.HX_API_KEY)==null?void 0:c.trim())??""},signal:i.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 delete"}:{ok:!0}}catch(l){return{ok:!1,error:l instanceof Error?l.message:"fetch failed"}}finally{clearTimeout(o)}}async function $e(t,e,r=fetch,n=5e3){var a,c;let s=(a=t.HX_ORA_URL)==null?void 0:a.trim().replace(/\/$/,"");if(!s)return{ok:!1,error:"HX_ORA_URL missing"};let i=new AbortController,o=setTimeout(()=>i.abort(),n);try{let l=await r(`${s}/internal/artifacts/${encodeURIComponent(e.uuid)}`,{method:"PUT",headers:{Authorization:((c=t.HX_API_KEY)==null?void 0:c.trim())??"","Content-Type":"application/json"},body:JSON.stringify(e),signal:i.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(o)}}var Ft=/^[a-z0-9][a-z0-9-]{1,47}$/,Mt=new Set(["mcp","k","api","app","index","assets","static"]);function C(t){return typeof t!="string"||!Ft.test(t)?"invalid slug":Mt.has(t)?"reserved slug":null}function $(t){return typeof t!="string"||t.length===0||t.length>h.pathMaxChars||t.startsWith("/")||t.includes("\\")||t.includes("\0")||t.split("/").some(r=>r===""||r==="."||r==="..")?"invalid path":null}function z(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;if(typeof r.title!="string")return{ok:!1,error:"artifact.json title must be a string"};if(!Array.isArray(r.libs)||r.libs.some(s=>typeof s!="string"))return{ok:!1,error:"artifact.json libs must be a string array"};let n="none";if(r.theme!==void 0){if(r.theme!=="hugex"&&r.theme!=="none")return{ok:!1,error:"artifact.json theme must be 'hugex' or 'none'"};n=r.theme}return{ok:!0,manifest:{title:r.title,libs:r.libs,theme:n}}}var me="0.1.1";var ge=/not found|does not exist|no facet|unknown facet|not currently/i,he=class extends jt{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=C(e.slug);if(n)throw new Error(n);let s=ue(),i=new Date().toISOString();this.ctx.storage.sql.exec(`INSERT INTO meta (
317
+ SELECT version, path, hash FROM file`),t("DROP TABLE file"),t("ALTER TABLE file_dedup RENAME TO file"))}function Ut(t){let e=new Set;t.activeVersion&&e.add(t.activeVersion);for(let s of t.logVersionIds)s&&e.add(s);let n=[...t.versionRows].sort((s,o)=>{let i=s.createdAt.localeCompare(o.createdAt);return i!==0?i:s.id.localeCompare(o.id)}).slice(-t.keepVersions);for(let s of n)e.add(s.id);return e}function Xe(t,e,r){let n=128,s=new Set;for(let[o,i]of t){let a=e.get(o)??"";n+=k(o)+48,!s.has(a)&&!r.has(a)&&(s.add(a),n+=k(i)+k(a)+64)}return n}function me(t,e,r,n=h.keepVersions){let s=e("SELECT id, created_at AS createdAt FROM version").map(c=>({id:String(c.id),createdAt:String(c.createdAt)})),o=e("SELECT DISTINCT version FROM log WHERE version IS NOT NULL AND version != ''").map(c=>String(c.version)),i=Ut({activeVersion:r,versionRows:s,logVersionIds:o,keepVersions:n});if(i.size>=s.length){He(t,e);return}let a=s.map(c=>c.id).filter(c=>!i.has(c));for(let c of a)t("DELETE FROM file WHERE version = ?",c),t("DELETE FROM version WHERE id = ?",c);He(t,e)}function He(t,e){let r=new Set(e("SELECT DISTINCT hash FROM file").map(n=>String(n.hash)));for(let n of e("SELECT hash FROM blob")){let s=String(n.hash);r.has(s)||t("DELETE FROM blob WHERE hash = ?",s)}}var jt=[{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 Dt(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 $e(t,e){let r=[];for(let s of jt)e.includes(s.name)||(t(s.ddl),r.push(s.name));let n=Dt(r);return n&&t(n),r}async function Ve(t,e,r=fetch,n=5e3){var a,c;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)}`,{method:"DELETE",headers:{Authorization:((c=t.HX_API_KEY)==null?void 0:c.trim())??""},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 delete"}:{ok:!0}}catch(l){return{ok:!1,error:l instanceof Error?l.message:"fetch failed"}}finally{clearTimeout(i)}}async function Be(t,e,r=fetch,n=5e3){var a,c;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:((c=t.HX_API_KEY)==null?void 0:c.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 qt=/^[a-z0-9][a-z0-9-]{1,47}$/,Ht=new Set(["mcp","k","api","app","index","assets","static"]);function F(t){return typeof t!="string"||!qt.test(t)?"invalid slug":Ht.has(t)?"reserved slug":null}function V(t){return typeof t!="string"||t.length===0||t.length>h.pathMaxChars||t.startsWith("/")||t.includes("\\")||t.includes("\0")||t.split("/").some(r=>r===""||r==="."||r==="..")?"invalid path":null}var Wt=/^[A-Za-z0-9_-]+$/,Xt=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function _(t){return typeof t=="string"&&Wt.test(t)}function Ge(t){return typeof t=="string"&&Xt.test(t)}function J(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;if(typeof r.title!="string")return{ok:!1,error:"artifact.json title must be a string"};if(!Array.isArray(r.libs)||r.libs.some(s=>typeof s!="string"))return{ok:!1,error:"artifact.json libs must be a string array"};let n="none";if(r.theme!==void 0){if(r.theme!=="hugex"&&r.theme!=="none")return{ok:!1,error:"artifact.json theme must be 'hugex' or 'none'"};n=r.theme}return{ok:!0,manifest:{title:r.title,libs:r.libs,theme:n}}}var he="0.1.2";var ye=/not found|does not exist|no facet|unknown facet|not currently/i,be=class extends $t{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=F(e.slug);if(n)throw new Error(n);let s=fe(),o=new Date().toISOString();this.ctx.storage.sql.exec(`INSERT INTO meta (
266
318
  id, uuid, slug, title, tenant, org, owner, grp, public,
267
319
  key_plain, key_hash, key_gen, active_version, created_at, updated_at, revision,
268
320
  index_dirty, index_retry, ora_dirty, ora_retry
269
- ) 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 R(s),i,i);let o=this.readMeta();if(!o)throw new Error("create failed");return{meta:this.toPublic(o),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 i=this.readFile(n,e.path);return i==null?[]:[{path:e.path,content:i}]}return this.rows(`SELECT f.path, b.content FROM file f
321
+ ) 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 R(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 f.path, b.content FROM file f
270
322
  INNER JOIN blob b ON b.hash = f.hash
271
- WHERE f.version = ? ORDER BY f.path`,n).map(i=>({path:String(i.path),content:String(i.content)}))}async write(e){let r;try{r=await this.ctx.blockConcurrencyWhile(()=>this.writeLocked(e))}catch(n){Y(n)?r={ok:!1,code:"limit",error:"SQLITE_FULL"}:r={ok:!1,code:"invalid",error:w(y(n))}}return await this.flushIndex(),r}async rollback(e){let r;try{r=await this.ctx.blockConcurrencyWhile(()=>this.rollbackLocked(e))}catch(n){Y(n)?r={ok:!1,code:"limit",error:"SQLITE_FULL"}:r={ok:!1,code:"invalid",error:w(y(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,i=n.keyHash,o=n.keyGen,a=n.group,c=n.public;typeof e.group=="string"&&(a=e.group),typeof e.public=="boolean"&&(c=e.public);let l=e.rotateKey===!0;l&&(s=ue(),i=await R(s),o+=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,c?1:0,s,i,o,f),l&&this.closeStaleSockets(o);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=Xe(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=Xe(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 delete(e){if(typeof e.author!="string"||!e.author.trim())throw new Error("author must be a non-empty string");return await this.ctx.blockConcurrencyWhile(async()=>{var s;let r=this.readMeta();if(!r)return null;this.writeLog("system","info",`delete requested by ${e.author}`,r.activeVersion),this.closeAllSockets("artifact deleted"),this.destroyFacet();try{let i=this.env.ARTIFACT_INDEX;await i.get(i.idFromName("index")).remove(r.slug)}catch(i){this.writeLog("system","error",`index remove failed: ${y(i)}`,r.activeVersion)}let n=!1;(s=this.env.HX_ORA_URL)!=null&&s.trim()&&((await Ve(this.env,r.uuid)).ok||(n=!0));try{await this.ctx.storage.deleteAlarm()}catch{}return await this.ctx.storage.deleteAll(),this.migrate(),n?{ok:!0,oraSyncFailed:!0}:{ok:!0}})}async storageStats(){var n,s;if(!this.readMeta())return null;let e=Number(((n=this.rows("SELECT COUNT(*) AS n FROM blob")[0])==null?void 0:n.n)??0),r=Number(((s=this.rows("SELECT COUNT(*) AS n FROM version")[0])==null?void 0:s.n)??0);return{databaseSize:this.ctx.storage.sql.databaseSize,blobCount:e,versionCount:r}}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:w(s.error)};try{return{ok:!0,rows:await s.facet.__hxQuery(e)}}catch(i){return{ok:!1,error:w(y(i))}}}async fetch(e){try{let r=this.readMeta();if(!r)return this.notFound();let n=e.headers.get(F)??"";if(!await this.allow(r,n))return this.notFound();let s=new URL(e.url),i=s.pathname;try{i=decodeURIComponent(i)}catch{return this.notFound()}if(i.includes("\\")||i.split("/").includes(".."))return this.notFound();let o=i.replace(/^\/+/,"");return o==="__hx/ws"?this.acceptReload(e,r.keyGen):r.activeVersion?o==="api"||o.startsWith("api/")?await this.forwardApi(e,s,o,r):o===""||o==="index.html"?this.serveHtml(e,r):o==="server.js"||o==="artifact.json"?this.notFound():$(o)?this.notFound():this.serveFile(r,o):this.notFound()}catch(r){let n=this.readMeta(),s=w(y(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 i=s;if(i.type!=="log")return;let o=i.level==="debug"||i.level==="info"||i.level==="warn"||i.level==="error"?i.level:"error";if(!this.browserLogAllowed())return;let a=this.readMeta();this.writeLog("browser",o,String(i.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 (
323
+ WHERE f.version = ? ORDER BY f.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){z(n)?r={ok:!1,code:"limit",error:"SQLITE_FULL"}:r={ok:!1,code:"invalid",error:x(y(n))}}return await this.flushIndex(),r}async rollback(e){let r;try{r=await this.ctx.blockConcurrencyWhile(()=>this.rollbackLocked(e))}catch(n){z(n)?r={ok:!1,code:"limit",error:"SQLITE_FULL"}:r={ok:!1,code:"invalid",error:x(y(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,c=n.public;typeof e.group=="string"&&(a=e.group),typeof e.public=="boolean"&&(c=e.public);let l=e.rotateKey===!0;l&&(s=fe(),o=await R(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,c?1:0,s,o,i,f),l&&this.closeStaleSockets(i);let p=this.readMeta();if(!p)return null;let g=l||!p.public;return{meta:this.toPublic(p),key:g?p.keyPlain:null}});return await this.flushIndex(),r}async versions(e){if(!this.readMeta())return null;let r=Ke(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=Ke(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 delete(e){if(typeof e.author!="string"||!e.author.trim())throw new Error("author must be a non-empty string");return await this.ctx.blockConcurrencyWhile(async()=>{var s;let r=this.readMeta();if(!r)return null;this.writeLog("system","info",`delete requested by ${e.author}`,r.activeVersion),this.closeAllSockets("artifact deleted"),this.destroyFacet();try{let o=this.env.ARTIFACT_INDEX;await o.get(o.idFromName("index")).remove(r.slug)}catch(o){this.writeLog("system","error",`index remove failed: ${y(o)}`,r.activeVersion)}let n=!1;(s=this.env.HX_ORA_URL)!=null&&s.trim()&&((await Ve(this.env,r.uuid)).ok||(n=!0));try{await this.ctx.storage.deleteAlarm()}catch{}return await this.ctx.storage.deleteAll(),this.migrate(),n?{ok:!0,oraSyncFailed:!0}:{ok:!0}})}async allowsWorker(e){let r={ok:!1};if(!e||typeof e!="object"||!_(e.flowId)||e.mode!=="browser"&&e.mode!=="server")return r;let n=this.readMeta();if(!n||e.mode==="server"&&e.artifactUuid!==n.uuid||e.artifactUuid!==void 0&&e.artifactUuid!==n.uuid)return r;if(e.mode==="browser"){let o=typeof e.key=="string"?e.key:"";if(!n.public&&!await this.allow(n,o))return r;let i=this.readMeta();if(!i||i.uuid!==n.uuid||i.keyGen!==n.keyGen||i.public!==n.public)return r}return this.rows("SELECT flow_id FROM worker_grant WHERE flow_id = ?",e.flowId)[0]?{ok:!0,owner:n.owner}:r}async listWorkerGrants(){return this.readMeta()?this.rows("SELECT flow_id, granted_by, granted_at FROM worker_grant ORDER BY granted_at, flow_id").map(e=>Gt(e)):null}async grantWorker(e){if(!e||!_(e.flowId))throw new Error("invalid flowId");if(typeof e.grantedBy!="string"||!e.grantedBy.trim())throw new Error("grantedBy is required");let r=this.readMeta();if(!r||r.uuid!==e.expectUuid||r.owner!==e.expectOwner)return null;let n=new Date().toISOString();return this.ctx.storage.sql.exec(`INSERT INTO worker_grant (flow_id, granted_by, granted_at) VALUES (?, ?, ?)
324
+ ON CONFLICT(flow_id) DO UPDATE SET granted_by = excluded.granted_by, granted_at = excluded.granted_at`,e.flowId,e.grantedBy.slice(0,320),n),this.writeLog("system","info",`worker granted: ${e.flowId} by ${e.grantedBy}`,r.activeVersion),{flowId:e.flowId,grantedBy:e.grantedBy.slice(0,320),grantedAt:n}}async revokeWorker(e){if(!e||!_(e.flowId))throw new Error("invalid flowId");let r=this.readMeta();return!r||r.uuid!==e.expectUuid?null:this.rows("SELECT flow_id FROM worker_grant WHERE flow_id = ?",e.flowId).length>0?(this.ctx.storage.sql.exec("DELETE FROM worker_grant WHERE flow_id = ?",e.flowId),this.writeLog("system","info",`worker revoked: ${e.flowId}`,r.activeVersion),{removed:!0}):{removed:!1}}async storageStats(){var n,s;if(!this.readMeta())return null;let e=Number(((n=this.rows("SELECT COUNT(*) AS n FROM blob")[0])==null?void 0:n.n)??0),r=Number(((s=this.rows("SELECT COUNT(*) AS n FROM version")[0])==null?void 0:s.n)??0);return{databaseSize:this.ctx.storage.sql.databaseSize,blobCount:e,versionCount:r}}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:x(s.error)};try{return{ok:!0,rows:await s.facet.__hxQuery(e)}}catch(o){return{ok:!1,error:x(y(o))}}}async fetch(e){try{let r=this.readMeta();if(!r)return this.notFound();let n=e.headers.get(j)??"";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():V(i)?this.notFound():this.serveFile(r,i):this.notFound()}catch(r){let n=this.readMeta(),s=x(y(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 (
272
325
  id INTEGER PRIMARY KEY CHECK (id = 1),
273
326
  uuid TEXT NOT NULL,
274
327
  slug TEXT NOT NULL,
@@ -289,7 +342,7 @@ export class ArtifactApp extends DurableObject {
289
342
  index_retry INTEGER NOT NULL DEFAULT 0,
290
343
  ora_dirty INTEGER NOT NULL DEFAULT 0,
291
344
  ora_retry INTEGER NOT NULL DEFAULT 0
292
- )`);let e=this.rows("PRAGMA table_info(meta)").map(n=>String(n.name));He(n=>{this.ctx.storage.sql.exec(n)},e),this.ctx.storage.sql.exec(`CREATE TABLE IF NOT EXISTS blob (
345
+ )`);let e=this.rows("PRAGMA table_info(meta)").map(n=>String(n.name));$e(n=>{this.ctx.storage.sql.exec(n)},e),this.ctx.storage.sql.exec(`CREATE TABLE IF NOT EXISTS blob (
293
346
  hash TEXT PRIMARY KEY,
294
347
  content TEXT NOT NULL
295
348
  )`),this.ctx.storage.sql.exec(`CREATE TABLE IF NOT EXISTS file (
@@ -297,7 +350,7 @@ export class ArtifactApp extends DurableObject {
297
350
  path TEXT NOT NULL,
298
351
  hash TEXT NOT NULL,
299
352
  PRIMARY KEY (version, path)
300
- )`);let r=this.rows("PRAGMA table_info(file)").map(n=>String(n.name));this.ctx.storage.transactionSync(()=>{De((n,...s)=>{this.ctx.storage.sql.exec(n,...s)},(n,...s)=>this.rows(n,...s),r)}),this.ctx.storage.sql.exec(`CREATE TABLE IF NOT EXISTS version (
353
+ )`);let r=this.rows("PRAGMA table_info(file)").map(n=>String(n.name));this.ctx.storage.transactionSync(()=>{We((n,...s)=>{this.ctx.storage.sql.exec(n,...s)},(n,...s)=>this.rows(n,...s),r)}),this.ctx.storage.sql.exec(`CREATE TABLE IF NOT EXISTS version (
301
354
  id TEXT PRIMARY KEY,
302
355
  runtime_id TEXT,
303
356
  author TEXT,
@@ -312,14 +365,18 @@ export class ArtifactApp extends DurableObject {
312
365
  level TEXT NOT NULL,
313
366
  message TEXT NOT NULL,
314
367
  version TEXT
315
- )`)}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,i=Dt(s,e.changes);if(!i.ok)return{ok:!1,code:i.code,error:i.error};let o=i.files;if(Ut(o)>h.versionBytes)return{ok:!1,code:"limit",error:"version exceeds 5 MB"};if(le(o,s))return{ok:!1,code:"invalid",error:"no changes"};let c=o.get("artifact.json");if(c==null)return{ok:!1,code:"invalid",error:"artifact.json is required"};let l=z(c);if(!l.ok)return{ok:!1,code:"invalid",error:l.error};if(!o.has("index.html"))return{ok:!1,code:"invalid",error:"index.html is required"};let f=V(l.manifest.libs).warnings,p=await Ie(o),m=this.rows("SELECT id FROM version WHERE id = ?",p)[0],g=o.get("server.js")??null,v=g==null?null:await this.runtimeId(g);if(m){if(!le(this.filesFor(p),o))return{ok:!1,code:"invalid",error:"version id already exists with different files"}}else{let P=new Map;for(let[H,yt]of o)P.set(H,await R(yt));try{this.persistNewVersion(p,v,e.author,e.message,o,P,r.activeVersion)}catch(H){if(Y(H))return{ok:!1,code:"limit",error:"SQLITE_FULL"};if(/storage limit exceeded/i.test(y(H)))return{ok:!1,code:"limit",error:"storage limit exceeded"};throw H}}let k=this.beginActivation(),_;try{_=await this.activateCode(g,n,k)}finally{k.stop()}if(!this.activationLive(k)||!_.ok){let P=w(_.ok?"timeout":_.error);return m||this.markFailed(p,P),this.writeLog("server","error",P,p),{ok:!1,code:"failed",version:p,state:"fallida",error:P}}this.promote(p,n,l.manifest.title),this.runRetention();let ht=this.readMeta()??r;return this.broadcastReload(p,ht.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 i=this.filesFor(e.version),o=i.get("artifact.json");if(o==null)return{ok:!1,code:"invalid",error:"artifact.json is required"};let a=z(o);if(!a.ok)return{ok:!1,code:"invalid",error:a.error};if(!i.has("index.html"))return{ok:!1,code:"invalid",error:"index.html is required"};let c=i.get("server.js")??null,l=this.beginActivation(),f;try{f=await this.activateCode(c,r.activeVersion,l)}finally{l.stop()}if(!this.activationLive(l)||!f.ok){let g=w(f.ok?"timeout":f.error);return this.writeLog("server","error",g,e.version),{ok:!1,code:"failed",version:e.version,state:"fallida",error:g}}this.promote(e.version,r.activeVersion,a.manifest.title),this.runRetention();let p=this.readMeta()??r;this.broadcastReload(e.version,p.keyGen);let m=V(a.manifest.libs).warnings;return{ok:!0,version:e.version,state:"activa",warnings:m}}beginActivation(){let e=++this.activationGen,r=Date.now()+h.healthTimeoutMs,n=setTimeout(()=>{this.activationGen===e&&(this.activationGen+=1)},h.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 i=this.abortFacet();return i.ok?this.activationLive(n)?{ok:!0}:{ok:!1,error:"timeout"}:i}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 i=this.readFile(r,"server.js");if(i!=null){let o=await this.swapFacet(i,n);o.ok||this.writeLog("server","error",`restore failed: ${o.error}`,r)}else this.activationLive(n)&&this.abortFacet()}return s}persistNewVersion(e,r,n,s,i,o,a){let c=new Date().toISOString(),l=n.slice(0,320),f=s.slice(0,2e3);this.ctx.storage.transactionSync(()=>{let p=new Set(this.rows("SELECT hash FROM blob").map(v=>String(v.hash))),m=qe(i,o,p),g=this.ctx.storage.sql.databaseSize+m;if(g>h.supervisorBytes&&(pe((v,...k)=>{this.ctx.storage.sql.exec(v,...k)},(v,...k)=>this.rows(v,...k),a),g=this.ctx.storage.sql.databaseSize+m),g>h.supervisorBytes)throw new Error("storage limit exceeded");this.ctx.storage.sql.exec(`INSERT INTO version (id, runtime_id, author, message, created_at, state, error)
316
- VALUES (?, ?, ?, ?, ?, 'provisional', NULL)`,e,r,l,f,c);for(let[v,k]of i){let _=o.get(v)??"";this.ctx.storage.sql.exec("INSERT OR IGNORE INTO blob (hash, content) VALUES (?, ?)",_,k),this.ctx.storage.sql.exec("INSERT INTO file (version, path, hash) VALUES (?, ?, ?)",e,v,_)}})}runRetention(){let e=this.readMeta();e&&this.ctx.storage.transactionSync(()=>{pe((r,...n)=>{this.ctx.storage.sql.exec(r,...n)},(r,...n)=>this.rows(r,...n),e.activeVersion)})}markFailed(e,r){this.ctx.storage.sql.exec("UPDATE version SET state = 'fallida', error = ? WHERE id = ?",ae(w(r),h.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=ce();return Ne({appSource:fe,serverJs:e,pkgVersion:me,compatibilityDate:G,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=ce(),s=await this.runtimeId(e),i={compatibilityDate:n.compatibilityDate,mainModule:n.mainModule,modules:{"server.js":e,"artifact-app.js":fe},globalOutbound:null,env:{}};try{return{ok:!0,appClass:this.env.LOADER.get(`artifact:${r.uuid}:${s}`,()=>i).getDurableObjectClass("App")}}catch(o){return{ok:!1,error:y(o)}}}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 de(n.__hxHealth(),h.healthTimeoutMs),{ok:!0,facet:n}}catch(n){return{ok:!1,error:y(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 i=r.deadline-Date.now();if(i<=0||!this.activationLive(r))return{ok:!1,error:"timeout"};try{let o=this.facetOf(n.appClass);return await de(o.__hxHealth(),i),this.activationLive(r)?{ok:!0}:{ok:!1,error:"timeout"}}catch(o){return{ok:!1,error:y(o)}}}abortFacet(){try{return this.ctx.facets.abort("app",new Error("swap")),{ok:!0}}catch(e){return ge.test(y(e))?{ok:!0}:{ok:!1,error:`abort: ${y(e)}`}}}async allow(e,r){if(!r)return e.public;let n=await R(r);return K(n,e.keyHash)}acceptReload(e,r){var o;if(((o=e.headers.get("Upgrade"))==null?void 0:o.toLowerCase())!=="websocket")return this.notFound();let n=new WebSocketPair,s=n[0],i=n[1];return i.serializeAttachment({keyGen:r}),this.ctx.acceptWebSocket(i),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"),i=[];if(s!=null){let l=z(s);l.ok&&(i=l.manifest.libs)}let o=e.headers.get(M)||"/",a=o.endsWith("/")?o:`${o}/`,c=Pe(n,a,i);return this.secure(new Response(c,{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":Fe(r)}}))}async forwardApi(e,r,n,s){if(!s.activeVersion)return this.notFound();let i=this.readFile(s.activeVersion,"server.js");if(i==null)return this.notFound();let o=await this.ensureFacet(i);if(!o.ok)return this.plain("facet unavailable",502);let a=new Headers(e.headers);a.delete("cookie"),a.delete(F),a.delete(M);let c=e.method!=="GET"&&e.method!=="HEAD",l=await o.facet.fetch(new Request(`http://artifact.local/${n}${r.search}`,{method:e.method,headers:a,body:c?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 i=s.deserializeAttachment();if(!(!i||Number(i.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{}}}closeAllSockets(e){for(let r of this.ctx.getWebSockets())try{r.close(1e3,e)}catch{}}destroyFacet(){if(!(!this.ctx.facets||typeof this.ctx.facets.get!="function")){try{this.ctx.facets.abort("app",new Error("deleted"))}catch(e){ge.test(y(e))}try{this.ctx.facets.delete("app")}catch(e){ge.test(y(e))}}}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)<h.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,ae(w(String(n)),h.logMessageBytes),s),this.ctx.storage.sql.exec(`DELETE FROM log WHERE id <= (
368
+ )`),this.ctx.storage.sql.exec(`CREATE TABLE IF NOT EXISTS worker_grant (
369
+ flow_id TEXT PRIMARY KEY,
370
+ granted_by TEXT NOT NULL,
371
+ granted_at TEXT NOT NULL
372
+ )`)}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=Bt(s,e.changes);if(!o.ok)return{ok:!1,code:o.code,error:o.error};let i=o.files;if(Vt(i)>h.versionBytes)return{ok:!1,code:"limit",error:"version exceeds 5 MB"};if(ce(i,s))return{ok:!1,code:"invalid",error:"no changes"};let c=i.get("artifact.json");if(c==null)return{ok:!1,code:"invalid",error:"artifact.json is required"};let l=J(c);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=$(l.manifest.libs).warnings,p=await Oe(i),g=this.rows("SELECT id FROM version WHERE id = ?",p)[0],m=i.get("server.js")??null,b=m==null?null:await this.runtimeId(m);if(g){if(!ce(this.filesFor(p),i))return{ok:!1,code:"invalid",error:"version id already exists with different files"}}else{let M=new Map;for(let[X,Tt]of i)M.set(X,await R(Tt));try{this.persistNewVersion(p,b,e.author,e.message,i,M,r.activeVersion)}catch(X){if(z(X))return{ok:!1,code:"limit",error:"SQLITE_FULL"};if(/storage limit exceeded/i.test(y(X)))return{ok:!1,code:"limit",error:"storage limit exceeded"};throw X}}let A=this.beginActivation(),C;try{C=await this.activateCode(m,n,A)}finally{A.stop()}if(!this.activationLive(A)||!C.ok){let M=x(C.ok?"timeout":C.error);return g||this.markFailed(p,M),this.writeLog("server","error",M,p),{ok:!1,code:"failed",version:p,state:"fallida",error:M}}this.promote(p,n,l.manifest.title),this.runRetention();let At=this.readMeta()??r;return this.broadcastReload(p,At.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=J(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 c=o.get("server.js")??null,l=this.beginActivation(),f;try{f=await this.activateCode(c,r.activeVersion,l)}finally{l.stop()}if(!this.activationLive(l)||!f.ok){let m=x(f.ok?"timeout":f.error);return this.writeLog("server","error",m,e.version),{ok:!1,code:"failed",version:e.version,state:"fallida",error:m}}this.promote(e.version,r.activeVersion,a.manifest.title),this.runRetention();let p=this.readMeta()??r;this.broadcastReload(e.version,p.keyGen);let g=$(a.manifest.libs).warnings;return{ok:!0,version:e.version,state:"activa",warnings:g}}beginActivation(){let e=++this.activationGen,r=Date.now()+h.healthTimeoutMs,n=setTimeout(()=>{this.activationGen===e&&(this.activationGen+=1)},h.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,a){let c=new Date().toISOString(),l=n.slice(0,320),f=s.slice(0,2e3);this.ctx.storage.transactionSync(()=>{let p=new Set(this.rows("SELECT hash FROM blob").map(b=>String(b.hash))),g=Xe(o,i,p),m=this.ctx.storage.sql.databaseSize+g;if(m>h.supervisorBytes&&(me((b,...A)=>{this.ctx.storage.sql.exec(b,...A)},(b,...A)=>this.rows(b,...A),a),m=this.ctx.storage.sql.databaseSize+g),m>h.supervisorBytes)throw new Error("storage limit exceeded");this.ctx.storage.sql.exec(`INSERT INTO version (id, runtime_id, author, message, created_at, state, error)
373
+ VALUES (?, ?, ?, ?, ?, 'provisional', NULL)`,e,r,l,f,c);for(let[b,A]of o){let C=i.get(b)??"";this.ctx.storage.sql.exec("INSERT OR IGNORE INTO blob (hash, content) VALUES (?, ?)",C,A),this.ctx.storage.sql.exec("INSERT INTO file (version, path, hash) VALUES (?, ?, ?)",e,b,C)}})}runRetention(){let e=this.readMeta();e&&this.ctx.storage.transactionSync(()=>{me((r,...n)=>{this.ctx.storage.sql.exec(r,...n)},(r,...n)=>this.rows(r,...n),e.activeVersion)})}markFailed(e,r){this.ctx.storage.sql.exec("UPDATE version SET state = 'fallida', error = ? WHERE id = ?",le(x(r),h.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)})}workerGateway(){var r;return(r=this.ctx.exports)==null?void 0:r[ue]}hasWorkerGateway(){return typeof this.workerGateway()=="function"}async runtimeId(e){let r=de(U,{gateway:this.hasWorkerGateway()});return Ne({appSource:ge,serverJs:e,pkgVersion:he,compatibilityDate:U,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=de(U,{gateway:this.hasWorkerGateway()}),s=await this.runtimeId(e),o={compatibilityDate:n.compatibilityDate,mainModule:n.mainModule,modules:{"server.js":e,"artifact-app.js":ge},globalOutbound:null,env:this.hasWorkerGateway()?{HX:this.workerGateway()({props:{tenant:r.tenant,slug:r.slug,artifactUuid:r.uuid}})}:{}};try{return{ok:!0,appClass:this.env.LOADER.get(`artifact:${r.uuid}:${s}`,()=>o).getDurableObjectClass("App")}}catch(i){return{ok:!1,error:y(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 pe(n.__hxHealth(),h.healthTimeoutMs),{ok:!0,facet:n}}catch(n){return{ok:!1,error:y(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 pe(i.__hxHealth(),o),this.activationLive(r)?{ok:!0}:{ok:!1,error:"timeout"}}catch(i){return{ok:!1,error:y(i)}}}abortFacet(){try{return this.ctx.facets.abort("app",new Error("swap")),{ok:!0}}catch(e){return ye.test(y(e))?{ok:!0}:{ok:!1,error:`abort: ${y(e)}`}}}async allow(e,r){if(!r)return e.public;let n=await R(r);return Y(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=J(s);l.ok&&(o=l.manifest.libs)}let i=e.headers.get(D)||"/",a=i.endsWith("/")?i:`${i}/`,c=Ue(n,a,o);return this.secure(new Response(c,{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":je(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(j),a.delete(D);let c=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:c?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{}}}closeAllSockets(e){for(let r of this.ctx.getWebSockets())try{r.close(1e3,e)}catch{}}destroyFacet(){if(!(!this.ctx.facets||typeof this.ctx.facets.get!="function")){try{this.ctx.facets.abort("app",new Error("deleted"))}catch(e){ye.test(y(e))}try{this.ctx.facets.delete("app")}catch(e){ye.test(y(e))}}}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)<h.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,le(x(String(n)),h.logMessageBytes),s),this.ctx.storage.sql.exec(`DELETE FROM log WHERE id <= (
317
374
  SELECT id FROM log ORDER BY id DESC LIMIT 1 OFFSET ?
318
- )`,h.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: ${y(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 $e(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 o;let e=this.readMeta(),r=!!(e!=null&&e.indexDirty),n=!!(e!=null&&e.oraDirty&&((o=this.env.HX_ORA_URL)!=null&&o.trim()));if(!r&&!n){try{await this.ctx.storage.deleteAlarm()}catch{}return}let s=Math.max(r?e.indexRetry:0,n?e.oraRetry:0),i=Math.min(6e4,1e3*2**Math.max(0,s-1));await this.ctx.storage.setAlarm(Date.now()+i)}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 S(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 f.path, b.content FROM file f
375
+ )`,h.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: ${y(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 Be(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 S(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 f.path, b.content FROM file f
319
376
  INNER JOIN blob b ON b.hash = f.hash
320
377
  WHERE f.version = ?`,e))r.set(String(n.path),String(n.content));return r}readFile(e,r){let n=this.rows(`SELECT b.content FROM file f
321
378
  INNER JOIN blob b ON b.hash = f.hash
322
- WHERE f.version = ? AND f.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 Ut(t){let e=0;for(let r of t.values())e+=x(r);return e}function Xe(t,e){return t==null||!Number.isFinite(t)?e:Math.min(h.logRows,Math.max(1,Math.floor(t)))}function Dt(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=$(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)>h.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 qt}from"cloudflare:workers";var ye=`INSERT INTO artifact (slug, uuid, title, org, owner, grp, public, active_version, updated_at, revision)
379
+ WHERE f.version = ? AND f.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 Vt(t){let e=0;for(let r of t.values())e+=k(r);return e}function Ke(t,e){return t==null||!Number.isFinite(t)?e:Math.min(h.logRows,Math.max(1,Math.floor(t)))}function Bt(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=V(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(k(n.content)>h.fileBytes)return{ok:!1,code:"limit",error:`file exceeds 1 MB: ${n.path}`};r.set(n.path,n.content)}return{ok:!0,files:r}}function Gt(t){return{flowId:String(t.flow_id),grantedBy:String(t.granted_by),grantedAt:String(t.granted_at)}}import{DurableObject as Kt}from"cloudflare:workers";var ve=`INSERT INTO artifact (slug, uuid, title, org, owner, grp, public, active_version, updated_at, revision)
323
380
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
324
381
  ON CONFLICT(slug) DO UPDATE SET
325
382
  uuid = excluded.uuid,
@@ -331,7 +388,7 @@ export class ArtifactApp extends DurableObject {
331
388
  active_version = excluded.active_version,
332
389
  updated_at = excluded.updated_at,
333
390
  revision = excluded.revision
334
- WHERE excluded.revision > artifact.revision`;var be=class extends qt{constructor(e,r){super(e,r),e.blockConcurrencyWhile(async()=>{this.ctx.storage.sql.exec(`CREATE TABLE IF NOT EXISTS artifact (
391
+ WHERE excluded.revision > artifact.revision`;var Ee=class extends Kt{constructor(e,r){super(e,r),e.blockConcurrencyWhile(async()=>{this.ctx.storage.sql.exec(`CREATE TABLE IF NOT EXISTS artifact (
335
392
  slug TEXT PRIMARY KEY,
336
393
  uuid TEXT NOT NULL,
337
394
  title TEXT NOT NULL,
@@ -342,20 +399,20 @@ export class ArtifactApp extends DurableObject {
342
399
  active_version TEXT,
343
400
  updated_at TEXT NOT NULL,
344
401
  revision INTEGER NOT NULL DEFAULT 0
345
- )`),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(ye,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 Ht=new Set(["localhost","127.0.0.1","[::1]"]);function J(t,e){if(e&&Ht.has(t))return e}function Vt(t){if(!t)return null;let e=t.endsWith("/")?t.slice(0,-1):t;return!e.startsWith("/")||e.includes("//")?null:e}function Be(t){let e=Vt(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),i=s[0];if(!i||C(i))return{kind:"not-found"};let o="",a;if(s[1]==="k"){let p=s[2];if(!p)return{kind:"not-found"};try{o=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 c=a.length===0?"/":`/${a.join("/")}`,l=o?`k/${encodeURIComponent(o)}/`:"",f=`${n}/${i}/${l}`;return{kind:"forward",slug:i,key:o,internalPath:c,basePath:f}}function We(t,e){let r=new URL(t.url);r.pathname=e.internalPath;let n=new Request(r.toString(),t);return n.headers.delete(F),n.headers.delete(M),n.headers.delete("cookie"),n.headers.set(F,e.key),n.headers.set(M,e.basePath),n}function j(t,e){return t.ARTIFACT.get(t.ARTIFACT.idFromName(e))}function ve(t){return t.ARTIFACT_INDEX.get(t.ARTIFACT_INDEX.idFromName("index"))}var Ee=["blank","dashboard","table","process-form"];function Q(t){return typeof t=="string"&&Ee.includes(t)}function Z(t,e){switch(t){case"blank":return Xt(e);case"dashboard":return Bt(e);case"table":return Wt(e);case"process-form":return Gt(e)}}function ee(t,e){return`${JSON.stringify({title:t,libs:e,theme:"none"},null,2)}
346
- `}function te(t){return`<!doctype html>
402
+ )`),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(ve,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 Yt=new Set(["localhost","127.0.0.1","[::1]"]);function Q(t,e){if(e&&Yt.has(t))return e}function zt(t){if(!t)return null;let e=t.endsWith("/")?t.slice(0,-1):t;return!e.startsWith("/")||e.includes("//")?null:e}function Ye(t){let e=zt(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||F(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}`};if(a[0]==="__hx"&&a[1]==="agent"){let[p,g]=[a[2],a[3]];return r.includes("//")||r.endsWith("/")||a.length!==4||!_(p)||!Ge(g)?{kind:"not-found"}:{kind:"agent",slug:o,key:i,flowId:p,sessionId:g}}let c=a.length===0?"/":`/${a.join("/")}`,l=i?`k/${encodeURIComponent(i)}/`:"",f=`${n}/${o}/${l}`;return{kind:"forward",slug:o,key:i,internalPath:c,basePath:f}}function ze(t,e){let r=new URL(t.url);r.pathname=e.internalPath;let n=new Request(r.toString(),t);return n.headers.delete(j),n.headers.delete(D),n.headers.delete("cookie"),n.headers.set(j,e.key),n.headers.set(D,e.basePath),n}function O(t,e){return t.ARTIFACT.get(t.ARTIFACT.idFromName(e))}function Ae(t){return t.ARTIFACT_INDEX.get(t.ARTIFACT_INDEX.idFromName("index"))}var Te=["blank","dashboard","table","process-form"];function Z(t){return typeof t=="string"&&Te.includes(t)}function ee(t,e){switch(t){case"blank":return Qt(e);case"dashboard":return Zt(e);case"table":return er(e);case"process-form":return tr(e)}}function te(t,e){return`${JSON.stringify({title:t,libs:e,theme:"none"},null,2)}
403
+ `}function re(t){return`<!doctype html>
347
404
  <html lang="es">
348
405
  <head>
349
406
  <meta charset="utf-8" />
350
407
  <meta name="viewport" content="width=device-width, initial-scale=1" />
351
- <title>${$t(t)}</title>
408
+ <title>${Jt(t)}</title>
352
409
  </head>
353
410
  <body>
354
411
  <div id="app"></div>
355
412
  <script type="module" src="./app.js"></script>
356
413
  </body>
357
414
  </html>
358
- `}function $t(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Xt(t){let e=`import { h, render } from 'preact';
415
+ `}function Jt(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Qt(t){let e=`import { h, render } from 'preact';
359
416
  import htm from 'htm';
360
417
 
361
418
  const html = htm.bind(h);
@@ -378,7 +435,7 @@ function App() {
378
435
  }
379
436
 
380
437
  render(html\`<\${App} />\`, document.getElementById('app'));
381
- `;return[{path:"artifact.json",content:ee(t,["preact","htm"])},{path:"index.html",content:te(t)},{path:"app.js",content:e}]}var Ae=`function jsonRows(cursor) {
438
+ `;return[{path:"artifact.json",content:te(t,["preact","htm"])},{path:"index.html",content:re(t)},{path:"app.js",content:e}]}var we=`function jsonRows(cursor) {
382
439
  return cursor.toArray().map((row) => {
383
440
  const out = {};
384
441
  for (const key of Object.keys(row)) {
@@ -388,7 +445,7 @@ render(html\`<\${App} />\`, document.getElementById('app'));
388
445
  return out;
389
446
  });
390
447
  }
391
- `;function Bt(t){let e=`import { h, render } from "preact";
448
+ `;function Zt(t){let e=`import { h, render } from "preact";
392
449
  import { useEffect, useRef, useState } from "preact/hooks";
393
450
  import htm from "htm";
394
451
  import Chart from "chart.js/auto";
@@ -474,7 +531,7 @@ function App() {
474
531
  render(html\`<\${App} />\`, document.getElementById("app"));
475
532
  `,r=`import { ArtifactApp } from "./artifact-app.js";
476
533
 
477
- ${Ae}
534
+ ${we}
478
535
  const MESES = [
479
536
  ["Ene", 12],
480
537
  ["Feb", 18],
@@ -543,7 +600,7 @@ export class App extends ArtifactApp {
543
600
  return new Response("Not found", { status: 404 });
544
601
  }
545
602
  }
546
- `;return[{path:"artifact.json",content:ee(t,["preact","preact/hooks","htm","chart.js"])},{path:"index.html",content:te(t)},{path:"app.js",content:e},{path:"server.js",content:r}]}function Wt(t){let e=`import { h, render } from "preact";
603
+ `;return[{path:"artifact.json",content:te(t,["preact","preact/hooks","htm","chart.js"])},{path:"index.html",content:re(t)},{path:"app.js",content:e},{path:"server.js",content:r}]}function er(t){let e=`import { h, render } from "preact";
547
604
  import { useEffect, useState } from "preact/hooks";
548
605
  import htm from "htm";
549
606
  import { createTable, getCoreRowModel, getFilteredRowModel, getSortedRowModel } from "@tanstack/table-core";
@@ -653,7 +710,7 @@ function App() {
653
710
  render(html\`<\${App} />\`, document.getElementById("app"));
654
711
  `,r=`import { ArtifactApp } from "./artifact-app.js";
655
712
 
656
- ${Ae}
713
+ ${we}
657
714
  export class App extends ArtifactApp {
658
715
  constructor(ctx, env) {
659
716
  super(ctx, env);
@@ -727,7 +784,7 @@ export class App extends ArtifactApp {
727
784
  return new Response("Not found", { status: 404 });
728
785
  }
729
786
  }
730
- `;return[{path:"artifact.json",content:ee(t,["preact","preact/hooks","htm","@tanstack/table-core"])},{path:"index.html",content:te(t)},{path:"app.js",content:e},{path:"server.js",content:r}]}function Gt(t){let e=`import { h, render } from "preact";
787
+ `;return[{path:"artifact.json",content:te(t,["preact","preact/hooks","htm","@tanstack/table-core"])},{path:"index.html",content:re(t)},{path:"app.js",content:e},{path:"server.js",content:r}]}function tr(t){let e=`import { h, render } from "preact";
731
788
  import { useEffect, useState } from "preact/hooks";
732
789
  import htm from "htm";
733
790
 
@@ -826,7 +883,7 @@ function labelEstado(value) {
826
883
  render(html\`<\${App} />\`, document.getElementById("app"));
827
884
  `,r=`import { ArtifactApp } from "./artifact-app.js";
828
885
 
829
- ${Ae}
886
+ ${we}
830
887
  const ESTADOS = ["pendiente", "en_curso", "cerrado"];
831
888
 
832
889
  export class App extends ArtifactApp {
@@ -889,6 +946,6 @@ export class App extends ArtifactApp {
889
946
  return new Response("Not found", { status: 404 });
890
947
  }
891
948
  }
892
- `;return[{path:"artifact.json",content:ee(t,["preact","preact/hooks","htm"])},{path:"index.html",content:te(t)},{path:"app.js",content:e},{path:"server.js",content:r}]}function U(t){var a,c;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(),i=J(n.hostname,s);if(i)return`${n.origin}${Ge(i)}/${r}`;let o=(c=t.host)==null?void 0:c.trim();return o?`https://${o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}/${r}`:s?`${n.origin}${Ge(s)}/${r}`:null}function Ge(t){let e=t.startsWith("/")?t:`/${t}`;return e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e==="/"?"":e}var X="/api/internal/artifacts",Kt=new Set(["server","browser","system"]),Yt=200,q=200,zt=4e3;function Ke(t){return t===X||t.startsWith(`${X}/`)}function Jt(t,e){let r=e.HX_API_KEY;return r?K(t.headers.get("Authorization")??"",r):!1}async function Ye(t,e){if(!Jt(t,e))return d({error:"unauthorized"},401);let r=new URL(t.url),n=Qt(r.pathname);if(n.kind==="missing")return d({error:"not found"},404);if(n.kind==="create")return t.method!=="POST"?L():Zt(t,e);let s=j(e,n.slug),i=await s.getMeta();if(!i)return d({error:"not found"},404);switch(n.kind){case"meta":return t.method==="DELETE"?er(t,s):t.method!=="GET"?L():re(r,i.uuid)?d({error:"not found"},404):rr(t,e,s,i);case"files":return t.method!=="GET"?L():re(r,i.uuid)?d({error:"not found"},404):nr(r,s,i);case"versions":return t.method!=="GET"?L():re(r,i.uuid)?d({error:"not found"},404):sr(r,s,i);case"logs":return t.method!=="GET"?L():re(r,i.uuid)?d({error:"not found"},404):ir(r,s,i);case"write":return t.method!=="POST"?L():or(t,s);case"rollback":return t.method!=="POST"?L():ar(t,s);case"settings":return t.method!=="POST"?L():lr(t,e,n.slug,s);default:return d({error:"not found"},404)}}function Qt(t){let e=t;if(e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e===X)return{kind:"create"};if(!e.startsWith(`${X}/`))return{kind:"missing"};let r;try{r=e.slice(X.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(C(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 Zt(t,e){let r=await B(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=C(r.value.slug);if(n)return d({error:n},400);let s=D(r.value.title,Yt);if(!s)return d({error:"title must be 1..200 characters"},400);let i=D(r.value.org,q);if(!i)return d({error:"org is required"},400);let o=D(r.value.owner,q);if(!o)return d({error:"owner is required"},400);let a="blank";if(r.value.template!==void 0){if(!Q(r.value.template))return d({error:"template must be blank, dashboard, table, or process-form"},400);a=r.value.template}let c=j(e,r.value.slug),l=await c.create({slug:r.value.slug,title:s,tenant:e.TENANT,org:i,owner:o});if(!l)return d({error:"slug already exists"},409);let f=await c.write({changes:Z(a,s),message:"create",baseVersion:null,author:o});if(!f.ok)return d(f,Te(f));let p=await c.getMeta()??{...l.meta,activeVersion:f.version},m=await c.getAccess(),g=Re(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:g},200)}function re(t,e){return t.searchParams.has("expectUuid")?t.searchParams.get("expectUuid")!==e:!1}async function er(t,e){let r=await tr(t);if(!r)return d({error:"author is required"},400);let n=await e.delete({author:r});return n?d({ok:!0,...n.oraSyncFailed?{oraSyncFailed:!0}:{}},200):d({error:"not found"},404)}async function tr(t){let r=new URL(t.url).searchParams.get("author");if(r!=null&&r.trim())return r.trim();if(t.method==="GET"||t.method==="HEAD")return null;let n=await B(t);return n.ok?D(n.value.author,q):null}async function rr(t,e,r,n){let s=await r.getAccess();if(!s)return d({error:"not found"},404);let i=Re(t,e,n.slug,s.public,s.key);return d({meta:n,url:i},200)}async function nr(t,e,r){let n=t.searchParams.get("version"),s=n||r.activeVersion;if(!s)return d({error:"not found"},404);let i=await e.readFiles({version:s});return i?d({meta:r,version:s,files:i},200):d({error:"not found"},404)}async function sr(t,e,r){let n=ze(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 ir(t,e,r){let n=ze(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&&!Kt.has(s))return d({error:"source must be server, browser, or system"},400);let i=await e.logs({...n!==void 0?{limit:n}:{},...s?{source:s}:{}});return i?d({meta:r,logs:i},200):d({error:"not found"},404)}async function or(t,e){let r=await B(t);if(!r.ok)return b("invalid json");let n=cr(r.value.changes);if(!Array.isArray(n))return n;if(typeof r.value.message!="string"||!r.value.message.trim()||r.value.message.length>zt)return b("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 b("baseVersion is required");let s=D(r.value.author,q);if(!s)return b("author is required");let i=await e.write({changes:n,message:r.value.message,baseVersion:r.value.baseVersion,author:s});return d(i,Te(i))}async function ar(t,e){let r=await B(t);if(!r.ok)return b("invalid json");if(typeof r.value.version!="string"||!r.value.version)return b("version is required");let n=D(r.value.author,q);if(!n)return b("author is required");let s=await e.rollback({version:r.value.version,author:n});return d(s,Te(s))}async function lr(t,e,r,n){let s=await B(t);if(!s.ok)return d({error:"invalid json"},400);let i={};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);i.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);i.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);i.rotateKey=s.value.rotateKey}if(i.group===void 0&&i.public===void 0&&i.rotateKey===void 0)return d({error:"settings requires group, public, or rotateKey"},400);let o=await n.settings(i);if(!o)return d({error:"not found"},404);let a=Re(t,e,r,o.meta.public,o.meta.public?null:o.key);return d({meta:o.meta,url:a},200)}function Te(t){return t.ok?200:t.code==="conflict"?409:422}function Re(t,e,r,n,s){return U({requestUrl:t.url,host:e.ARTIFACT_HOST,devPath:e.ARTIFACT_DEV_PATH,slug:r,isPublic:n,key:s})}function cr(t){if(!Array.isArray(t)||t.length===0)return b("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 b("each change must be an object");let s=n;if(typeof s.path!="string")return b("change path is required");let i=$(s.path);if(i)return b(i);if(e.has(s.path))return b(`duplicate path: ${s.path}`);if(e.add(s.path),s.content!==null&&typeof s.content!="string")return b("content must be a string or null");if(typeof s.content=="string"&&x(s.content)>h.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 ze(t){if(t==null||t==="")return;if(!/^\d+$/.test(t))return null;let e=Number(t);return e<1||e>1e3?null:e}function D(t,e){if(typeof t!="string")return null;let r=t.trim();return!r||r.length>e?null:r}async function B(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 b(t){return d({ok:!1,code:"invalid",error:t},422)}function L(){return d({error:"method not allowed"},405)}function d(t,e){return Response.json(t,{status:e})}var ur=5e3,dr=6e4,Je=new Map;function fr(t){var e,r;return!!((e=t.HX_ORA_URL)!=null&&e.trim()&&((r=t.HX_API_KEY)!=null&&r.trim()))}async function et(t,e,r=fetch,n=ur){if(!fr(t))return{ok:!0,mode:"phase1"};let s=await R(e),i=Je.get(s);if(i&&Date.now()-i.at<dr)return Ze(i.value);let o=await pr(t,e,r,n);return Je.set(s,{at:Date.now(),value:o}),Ze(o)}async function pr(t,e,r,n){let s=t.HX_ORA_URL.trim().replace(/\/$/,""),i=new AbortController,o=setTimeout(()=>i.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:i.signal});if(a.status===401)return{ok:!1,status:401};if(!a.ok)return{ok:!1,status:403};let c;try{c=await a.json()}catch{return{ok:!1,status:403}}let l=mr(c);return l?{ok:!0,mode:"rbac",access:l}:{ok:!1,status:403}}catch{return{ok:!1,status:403}}finally{clearTimeout(o)}}function mr(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"||!Qe(r.roleIds)||!Qe(r.modules)?null:{userId:r.userId,org:r.org,roleIds:r.roleIds,isAdmin:r.isAdmin,isSuperAdmin:r.isSuperAdmin,modules:r.modules}}function Qe(t){return Array.isArray(t)&&t.every(e=>typeof e=="string")}function Ze(t){return t.ok?{ok:!0,mode:"rbac",access:{...t.access,roleIds:[...t.access.roleIds],modules:[...t.access.modules]}}:t}import{importSPKI as gr,jwtVerify as hr}from"jose";var yr=/^Bearer ([A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)$/,br='Bearer realm="hugex-artifact"',ne=new Map;function xe(t){if(typeof t!="string")return null;let e=yr.exec(t);return e?e[1]:null}function vr(t){let e=t.trim();return e.includes("BEGIN PUBLIC KEY")?e:`-----BEGIN PUBLIC KEY-----
949
+ `;return[{path:"artifact.json",content:te(t,["preact","preact/hooks","htm"])},{path:"index.html",content:re(t)},{path:"app.js",content:e},{path:"server.js",content:r}]}function q(t){var a,c;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=Q(n.hostname,s);if(o)return`${n.origin}${Je(o)}/${r}`;let i=(c=t.host)==null?void 0:c.trim();return i?`https://${i.replace(/^https?:\/\//,"").replace(/\/+$/,"")}/${r}`:s?`${n.origin}${Je(s)}/${r}`:null}function Je(t){let e=t.startsWith("/")?t:`/${t}`;return e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e==="/"?"":e}var B="/api/internal/artifacts",rr=new Set(["server","browser","system"]),nr=200,W=200,sr=4e3;function Qe(t){return t===B||t.startsWith(`${B}/`)}function or(t,e){let r=e.HX_API_KEY;return r?Y(t.headers.get("Authorization")??"",r):!1}async function Ze(t,e){if(!or(t,e))return d({error:"unauthorized"},401);let r=new URL(t.url),n=ir(r.pathname);if(n.kind==="missing")return d({error:"not found"},404);if(n.kind==="create")return t.method!=="POST"?N():ar(t,e);let s=O(e,n.slug),o=await s.getMeta();if(!o)return d({error:"not found"},404);switch(n.kind){case"meta":return t.method==="DELETE"?lr(t,s):t.method!=="GET"?N():ne(r,o.uuid)?d({error:"not found"},404):ur(t,e,s,o);case"files":return t.method!=="GET"?N():ne(r,o.uuid)?d({error:"not found"},404):dr(r,s,o);case"versions":return t.method!=="GET"?N():ne(r,o.uuid)?d({error:"not found"},404):fr(r,s,o);case"logs":return t.method!=="GET"?N():ne(r,o.uuid)?d({error:"not found"},404):pr(r,s,o);case"write":return t.method!=="POST"?N():gr(t,s);case"rollback":return t.method!=="POST"?N():mr(t,s);case"settings":return t.method!=="POST"?N():hr(t,e,n.slug,s);default:return d({error:"not found"},404)}}function ir(t){let e=t;if(e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e===B)return{kind:"create"};if(!e.startsWith(`${B}/`))return{kind:"missing"};let r;try{r=e.slice(B.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(F(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 ar(t,e){let r=await G(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=F(r.value.slug);if(n)return d({error:n},400);let s=H(r.value.title,nr);if(!s)return d({error:"title must be 1..200 characters"},400);let o=H(r.value.org,W);if(!o)return d({error:"org is required"},400);let i=H(r.value.owner,W);if(!i)return d({error:"owner is required"},400);let a="blank";if(r.value.template!==void 0){if(!Z(r.value.template))return d({error:"template must be blank, dashboard, table, or process-form"},400);a=r.value.template}let c=O(e,r.value.slug),l=await c.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 c.write({changes:ee(a,s),message:"create",baseVersion:null,author:i});if(!f.ok)return d(f,Re(f));let p=await c.getMeta()??{...l.meta,activeVersion:f.version},g=await c.getAccess(),m=ke(t,e,p.slug,p.public,p.public?null:(g==null?void 0:g.key)??l.key);return d({meta:p,version:f.version,url:m},200)}function ne(t,e){return t.searchParams.has("expectUuid")?t.searchParams.get("expectUuid")!==e:!1}async function lr(t,e){let r=await cr(t);if(!r)return d({error:"author is required"},400);let n=await e.delete({author:r});return n?d({ok:!0,...n.oraSyncFailed?{oraSyncFailed:!0}:{}},200):d({error:"not found"},404)}async function cr(t){let r=new URL(t.url).searchParams.get("author");if(r!=null&&r.trim())return r.trim();if(t.method==="GET"||t.method==="HEAD")return null;let n=await G(t);return n.ok?H(n.value.author,W):null}async function ur(t,e,r,n){let s=await r.getAccess();if(!s)return d({error:"not found"},404);let o=ke(t,e,n.slug,s.public,s.key);return d({meta:n,url:o},200)}async function dr(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 fr(t,e,r){let n=et(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 pr(t,e,r){let n=et(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&&!rr.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 gr(t,e){let r=await G(t);if(!r.ok)return E("invalid json");let n=yr(r.value.changes);if(!Array.isArray(n))return n;if(typeof r.value.message!="string"||!r.value.message.trim()||r.value.message.length>sr)return E("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 E("baseVersion is required");let s=H(r.value.author,W);if(!s)return E("author is required");let o=await e.write({changes:n,message:r.value.message,baseVersion:r.value.baseVersion,author:s});return d(o,Re(o))}async function mr(t,e){let r=await G(t);if(!r.ok)return E("invalid json");if(typeof r.value.version!="string"||!r.value.version)return E("version is required");let n=H(r.value.author,W);if(!n)return E("author is required");let s=await e.rollback({version:r.value.version,author:n});return d(s,Re(s))}async function hr(t,e,r,n){let s=await G(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>W)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=ke(t,e,r,i.meta.public,i.meta.public?null:i.key);return d({meta:i.meta,url:a},200)}function Re(t){return t.ok?200:t.code==="conflict"?409:422}function ke(t,e,r,n,s){return q({requestUrl:t.url,host:e.ARTIFACT_HOST,devPath:e.ARTIFACT_DEV_PATH,slug:r,isPublic:n,key:s})}function yr(t){if(!Array.isArray(t)||t.length===0)return E("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 E("each change must be an object");let s=n;if(typeof s.path!="string")return E("change path is required");let o=V(s.path);if(o)return E(o);if(e.has(s.path))return E(`duplicate path: ${s.path}`);if(e.add(s.path),s.content!==null&&typeof s.content!="string")return E("content must be a string or null");if(typeof s.content=="string"&&k(s.content)>h.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 et(t){if(t==null||t==="")return;if(!/^\d+$/.test(t))return null;let e=Number(t);return e<1||e>1e3?null:e}function H(t,e){if(typeof t!="string")return null;let r=t.trim();return!r||r.length>e?null:r}async function G(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 E(t){return d({ok:!1,code:"invalid",error:t},422)}function N(){return d({error:"method not allowed"},405)}function d(t,e){return Response.json(t,{status:e})}var br=5e3,vr=6e4,tt=new Map;function Er(t){var e,r;return!!((e=t.HX_ORA_URL)!=null&&e.trim()&&((r=t.HX_API_KEY)!=null&&r.trim()))}async function st(t,e,r=fetch,n=br){if(!Er(t))return{ok:!0,mode:"phase1"};let s=await R(e),o=tt.get(s);if(o&&Date.now()-o.at<vr)return nt(o.value);let i=await Ar(t,e,r,n);return tt.set(s,{at:Date.now(),value:i}),nt(i)}async function Ar(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 c;try{c=await a.json()}catch{return{ok:!1,status:403}}let l=Tr(c);return l?{ok:!0,mode:"rbac",access:l}:{ok:!1,status:403}}catch{return{ok:!1,status:403}}finally{clearTimeout(i)}}function Tr(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"||!rt(r.roleIds)||!rt(r.modules)?null:{userId:r.userId,org:r.org,roleIds:r.roleIds,isAdmin:r.isAdmin,isSuperAdmin:r.isSuperAdmin,modules:r.modules}}function rt(t){return Array.isArray(t)&&t.every(e=>typeof e=="string")}function nt(t){return t.ok?{ok:!0,mode:"rbac",access:{...t.access,roleIds:[...t.access.roleIds],modules:[...t.access.modules]}}:t}import{importSPKI as wr,jwtVerify as Rr}from"jose";var kr=/^Bearer ([A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)$/,xr='Bearer realm="hugex-artifact"',se=new Map;function xe(t){if(typeof t!="string")return null;let e=kr.exec(t);return e?e[1]:null}function Sr(t){let e=t.trim();return e.includes("BEGIN PUBLIC KEY")?e:`-----BEGIN PUBLIC KEY-----
893
950
  ${e}
894
- -----END PUBLIC KEY-----`}function Er(t){let e=ne.get(t);if(e)return e;let r=gr(vr(t),"RS256");return ne.set(t,r),r.catch(()=>{ne.get(t)===r&&ne.delete(t)}),r}function W(){return new Response(JSON.stringify({error:"unauthorized"}),{status:401,headers:{"Content-Type":"application/json","WWW-Authenticate":br,"Referrer-Policy":"no-referrer"}})}function Ar(t){return(typeof t.email=="string"?t.email.trim():"")||null}async function Tr(t,e,r){try{let n=typeof e=="string"?await Er(e):e,{payload:s}=await hr(t,n,{algorithms:["RS256"]}),i=Ar(s);if(!i||s.tenant!==r)return null;let o=typeof s.org=="string"&&s.org?s.org:"default";return{email:i,org:o,tenant:r}}catch{return null}}async function tt(t,e){let r=xe(t.headers.get("authorization"));if(!r)return{ok:!1,response:W()};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 Tr(r,e.KC_RS256_PK,e.TENANT);return n?{ok:!0,identity:n}:{ok:!1,response:W()}}var Rr="artifacts",xr={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 rt(t){return Object.prototype.hasOwnProperty.call(xr,t)}function nt(t){return t.modules.includes(Rr)}function we(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 wr(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 st(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"?wr(s,n):we(s,n)}var kr=/^[a-z0-9][a-z0-9-]{1,47}$/,Sr=new Set(["mcp","k","api","app","index","assets","static"]),Lr=new Set(["server","browser","system"]),Ir=1024*1024,Nr=200,_r=200,Or=4e3,Cr=1e5,ke='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). Estilos libres: Tailwind con su paleta normal, daisyUI, CSS propio o fuentes desde jsDelivr; el artifact no tiene que verse como HugeX. artifact.json acepta "theme": "none" (por defecto) o "hugex" (tipograf\xEDa institucional). Cat\xE1logo: preact, preact/hooks, htm, alpinejs, daisyui, lucide, chart.js, echarts, tabulator-tables, @tanstack/table-core, luxon, sortablejs, marked y dompurify (usa marked siempre con dompurify).',Pr={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."}}},ot=[{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, paleta neutra de Tailwind, "theme": "none"). Devuelve { slug, uuid, version, url }. '+ke,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:[...Ee],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. "+ke,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. '+ke,inputSchema:{type:"object",additionalProperties:!1,required:["slug","files","message","baseVersion"],properties:{slug:{type:"string",description:"Slug del artifact."},files:{type:"array",minItems:1,items:Pr,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 at(t){return kr.test(t)?Sr.has(t)?`slug "${t}" is reserved`:null:"slug must match ^[a-z0-9][a-z0-9-]{1,47}$"}function lt(t){return t.length===0||t.length>Nr?"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 ct(t,e,r){try{return rt(t)?r.access&&!nt(r.access)?u({ok:!1,error:"module required: artifacts"}):await Fr(t,e,r):u({ok:!1,error:`unknown tool: ${t}`})}catch(n){let s=n instanceof Error?n.message:"tool failed";return u({ok:!1,error:s})}}async function Fr(t,e,r){switch(t){case"artifact_list":return Mr(e,r);case"artifact_create":return jr(e,r);case"artifact_read":return Ur(e,r);case"artifact_logs":return Dr(e,r);case"artifact_query":return qr(e,r);case"artifact_url":return Hr(e,r);case"artifact_write":return Vr(e,r);case"artifact_rollback":return $r(e,r);case"artifact_settings":return Xr(e,r);case"artifact_versions":return Br(e,r);default:return u({ok:!1,error:`unknown tool: ${t}`})}}async function Mr(t,e){let r=T(t,[]);if(r)return u({ok:!1,error:r});if(e.access){let s=await ve(e.env).list();return A(s.filter(i=>we(i,e.access)))}let n=await ve(e.env).list({owner:e.identity.email});return A(n.filter(s=>s.owner===e.identity.email))}async function jr(t,e){let r=T(t,["slug","title","template"]);if(r)return u({ok:!1,error:r});if(typeof t.slug!="string")return u({ok:!1,error:"slug is required"});let n=at(t.slug);if(n)return u({ok:!1,error:n});if(typeof t.title!="string")return u({ok:!1,error:"title is required"});let s=t.title.trim();if(!s||s.length>_r)return u({ok:!1,error:"title must be 1..200 characters"});let i="blank";if(t.template!==void 0){if(!Q(t.template))return u({ok:!1,error:"template must be blank, dashboard, table, or process-form"});i=t.template}let o=j(e.env,t.slug),a=await o.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 u({ok:!1,error:"slug already exists",slug:t.slug});let c=await o.write({changes:Z(i,s),message:"create",baseVersion:null,author:e.identity.email});if(!c.ok)return u({ok:!1,error:"initial write failed",slug:a.meta.slug,uuid:a.meta.uuid,write:c});let l=U({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:c.version,url:l};return c.warnings.length>0&&(f.warnings=c.warnings),A(f)}async function Ur(t,e){let r=T(t,["slug","path","version"]);if(r)return u({ok:!1,error:r});let n=N(t);if(typeof n!="string")return n;let s=it(t,"path");if(typeof s!="string"&&s!==void 0)return u({ok:!1,error:"path must be a string"});if(typeof s=="string"){let l=lt(s);if(l)return u({ok:!1,error:l})}let i=it(t,"version");if(i===null)return u({ok:!1,error:"version must be a string"});if(typeof i=="string"&&!i)return u({ok:!1,error:"version must be a non-empty string"});let o=await I(e,n,"use");if(o.denied)return o.denied;let a=i??o.meta.activeVersion;if(!a)return u({ok:!1,error:"not_found",slug:n});let c=await o.rpc.readFiles({...s?{path:s}:{},version:a});return c?s&&c.length===0?u({ok:!1,error:"file not found",slug:n,path:s}):A({slug:n,activeVersion:o.meta.activeVersion,version:a,files:c}):u({ok:!1,error:"not_found",slug:n})}async function Dr(t,e){let r=T(t,["slug","limit","source"]);if(r)return u({ok:!1,error:r});let n=N(t);if(typeof n!="string")return n;let s=ut(t.limit);if(s===!1)return u({ok:!1,error:"limit must be an integer from 1 to 1000"});if(t.source!==void 0&&(typeof t.source!="string"||!Lr.has(t.source)))return u({ok:!1,error:"source must be server, browser, or system"});let i=await I(e,n,"use");if(i.denied)return i.denied;let o=await i.rpc.logs({...s!==void 0?{limit:s}:{},...typeof t.source=="string"?{source:t.source}:{}});return o?A({slug:n,logs:o}):u({ok:!1,error:"not_found",slug:n})}async function qr(t,e){let r=T(t,["slug","sql"]);if(r)return u({ok:!1,error:r});let n=N(t);if(typeof n!="string")return n;if(typeof t.sql!="string"||!t.sql.trim())return u({ok:!1,error:"sql is required"});if(t.sql.length>Cr)return u({ok:!1,error:"sql is too long"});if(!Me(t.sql))return u({ok:!1,error:"artifact_query only accepts a single SELECT statement (WITH and multiple statements are rejected)"});let s=await I(e,n,"use");if(s.denied)return s.denied;let i=await s.rpc.query(t.sql);return i.ok?A(i):u(i)}async function Hr(t,e){let r=T(t,["slug"]);if(r)return u({ok:!1,error:r});let n=N(t);if(typeof n!="string")return n;let s=await I(e,n,"use");if(s.denied)return s.denied;let i=await s.rpc.getAccess();if(!i)return u({ok:!1,error:"not_found",slug:n});let o=U({requestUrl:e.requestUrl,host:e.env.ARTIFACT_HOST,devPath:e.env.ARTIFACT_DEV_PATH,slug:n,isPublic:i.public,key:i.key});return o?A({slug:n,public:i.public,url:o}):u({ok:!1,error:"artifact URL is not configured (set ARTIFACT_HOST or ARTIFACT_DEV_PATH)",slug:n})}async function Vr(t,e){let r=T(t,["slug","files","message","baseVersion"]);if(r)return u({ok:!1,error:r});let n=N(t);if(typeof n!="string")return n;let s=Wr(t.files);if(!Array.isArray(s))return s;if(typeof t.message!="string"||!t.message.trim()||t.message.length>Or)return u({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 u({ok:!1,error:"baseVersion is required and must be the active version id returned by artifact_read or artifact_versions"});let i=await I(e,n,"manage");if(i.denied)return i.denied;let o=await i.rpc.write({changes:s,message:t.message,baseVersion:t.baseVersion,author:e.identity.email});return o.ok?A(o):u(o)}async function $r(t,e){let r=T(t,["slug","version"]);if(r)return u({ok:!1,error:r});let n=N(t);if(typeof n!="string")return n;if(typeof t.version!="string"||!t.version)return u({ok:!1,error:"version is required"});let s=await I(e,n,"manage");if(s.denied)return s.denied;let i=await s.rpc.rollback({version:t.version,author:e.identity.email});return i.ok?A(i):u(i)}async function Xr(t,e){let r=T(t,["slug","group","public","rotateKey"]);if(r)return u({ok:!1,error:r});let n=N(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 u({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 u({ok:!1,error:"public must be a boolean"});s.public=t.public}if(t.rotateKey!==void 0){if(typeof t.rotateKey!="boolean")return u({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 u({ok:!1,error:"settings requires group, public, or rotateKey"});let i=await I(e,n,"manage");if(i.denied)return i.denied;let o=await i.rpc.settings(s);if(!o)return u({ok:!1,error:"not_found",slug:n});let a=U({requestUrl:e.requestUrl,host:e.env.ARTIFACT_HOST,devPath:e.env.ARTIFACT_DEV_PATH,slug:n,isPublic:o.meta.public,key:o.meta.public?null:o.key});return A({meta:o.meta,key:o.key,url:a})}async function Br(t,e){let r=T(t,["slug","limit"]);if(r)return u({ok:!1,error:r});let n=N(t);if(typeof n!="string")return n;let s=ut(t.limit);if(s===!1)return u({ok:!1,error:"limit must be an integer from 1 to 1000"});let i=await I(e,n,"use");if(i.denied)return i.denied;let o=await i.rpc.versions(s!==void 0?{limit:s}:void 0);return o?A({slug:n,activeVersion:i.meta.activeVersion,versions:o}):u({ok:!1,error:"not_found",slug:n})}async function I(t,e,r){let n=j(t.env,e),s=await n.getMeta();return s?st(r,s,t.identity,t.access)?{denied:null,rpc:n,meta:s}:{denied:u({ok:!1,error:"forbidden",slug:e})}:{denied:u({ok:!1,error:"not_found",slug:e})}}function N(t){if(typeof t.slug!="string")return u({ok:!1,error:"slug is required"});let e=at(t.slug);return e?u({ok:!1,error:e}):t.slug}function it(t,e){if(t[e]!==void 0)return typeof t[e]!="string"?null:t[e]}function ut(t){if(t!==void 0)return typeof t!="number"||!Number.isInteger(t)||t<1||t>1e3?!1:t}function Wr(t){if(!Array.isArray(t)||t.length===0)return u({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 u({ok:!1,error:"each file must be an object { path, content }"});let i=s,o=T(i,["path","content"]);if(o)return u({ok:!1,error:o});if(typeof i.path!="string")return u({ok:!1,error:"file path is required"});let a=lt(i.path);if(a)return u({ok:!1,error:a,path:i.path});if(r.has(i.path))return u({ok:!1,error:`duplicate path: ${i.path}`});if(r.add(i.path),i.content!==null&&typeof i.content!="string")return u({ok:!1,error:"file content must be a string or null",path:i.path});if(typeof i.content=="string"&&e.encode(i.content).byteLength>Ir)return u({ok:!1,error:`file exceeds 1 MB: ${i.path}`});n.push({path:i.path,content:i.content})}return n}function T(t,e){for(let r of Object.keys(t))if(!e.includes(r))return`unknown argument: ${r}`;return null}function A(t){return{content:[{type:"text",text:JSON.stringify(t)}]}}function u(t){return{content:[{type:"text",text:JSON.stringify(t)}],isError:!0}}var dt=8*1024*1024,Gr="hugex-artifact",Kr="1.0.0",Yr="2025-06-18",zr=["2024-11-05","2025-03-26","2025-06-18"],Jr=["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(" "),Qr="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.",Zr="RBAC completo: todas las tools exigen el m\xF3dulo artifacts; usar sigue canUseTool y gestionar sigue canManageTool.";function en(t){return`${Jr} ${t==="phase1"?Qr:Zr}`}async function pt(t,e,r){if(t.method!=="POST")return tn();let n=await tt(t,e);if(!n.ok)return n.response;let s=xe(t.headers.get("authorization"));if(!s)return W();let i=await et(e,s);if(!i.ok)return i.status===401?W():nn();let o=i.mode==="rbac"?i.access:null;if(!sn(t.headers.get("content-type")))return se(415,"Content-Type must be application/json");let a=t.headers.get("content-length");if(a!==null){if(!/^\d+$/.test(a))return se(400,"invalid content-length");if(Number(a)>dt)return se(413,"payload too large")}let c=await t.arrayBuffer();if(c.byteLength>dt)return se(413,"payload too large");let l;try{l=JSON.parse(new TextDecoder().decode(c))}catch{return E(null,-32700,"Parse error",400)}if(Array.isArray(l))return E(null,-32600,"Invalid Request",400,"batch is not supported");if(l===null||typeof l!="object")return E(null,-32600,"Invalid Request",400);let f=on(l);return f.ok?f.notification?rn():an(f.request,n.identity,e,t.url,i.mode,o):f.response}function tn(){return new Response(null,{status:405,headers:{Allow:"POST","Referrer-Policy":"no-referrer"}})}function rn(){return new Response(null,{status:202,headers:{"Referrer-Policy":"no-referrer"}})}function nn(){return new Response(JSON.stringify({error:"forbidden"}),{status:403,headers:{"Content-Type":"application/json","Referrer-Policy":"no-referrer"}})}function se(t,e){return new Response(e,{status:t,headers:{"Content-Type":"text/plain; charset=utf-8","Referrer-Policy":"no-referrer"}})}function mt(t,e){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":"application/json","Referrer-Policy":"no-referrer"}})}function ie(t,e){return mt(200,{jsonrpc:"2.0",id:t,result:e})}function E(t,e,r,n=200,s){let i={code:e,message:r};return s!==void 0&&(i.data=s),mt(n,{jsonrpc:"2.0",id:t,error:i})}function sn(t){var e;return t?((e=t.split(";",1)[0])==null?void 0:e.trim().toLowerCase())==="application/json":!1}function on(t){return t.jsonrpc!=="2.0"||typeof t.method!="string"||t.method.length===0?{ok:!1,response:E(ft(t.id),-32600,"Invalid Request",400)}:t.params!==void 0&&!(Array.isArray(t.params)||typeof t.params=="object"&&t.params!==null)?{ok:!1,response:E(ft(t.id),-32600,"Invalid Request",400)}:!Object.prototype.hasOwnProperty.call(t,"id")||t.method.startsWith("notifications/")?{ok:!0,notification:!0}:gt(t.id)?{ok:!0,notification:!1,request:{method:t.method,params:t.params,id:t.id}}:{ok:!1,response:E(null,-32600,"Invalid Request",400)}}function ft(t){return gt(t)?t:null}function gt(t){return t===null||typeof t=="string"?!0:typeof t=="number"&&Number.isFinite(t)}async function an(t,e,r,n,s,i){switch(t.method){case"initialize":return ln(t,s);case"ping":return ie(t.id,{});case"tools/list":return t.params!==void 0&&!oe(t.params)?E(t.id,-32602,"Invalid params"):ie(t.id,{tools:ot});case"tools/call":return cn(t,e,r,n,i);default:return E(t.id,-32601,"Method not found")}}function ln(t,e){if(t.params!==void 0&&!oe(t.params))return E(t.id,-32602,"Invalid params");let r=t.params??{},n=Yr;if(r.protocolVersion!==void 0){if(typeof r.protocolVersion!="string")return E(t.id,-32602,"Invalid params");zr.includes(r.protocolVersion)&&(n=r.protocolVersion)}return ie(t.id,{protocolVersion:n,capabilities:{tools:{}},serverInfo:{name:Gr,version:Kr},instructions:en(e)})}async function cn(t,e,r,n,s){if(!oe(t.params)||typeof t.params.name!="string"||!t.params.name)return E(t.id,-32602,"Invalid params");let i=un(t.params.arguments);if(!i)return E(t.id,-32602,"Invalid params");let o=await ct(t.params.name,i,{env:r,identity:e,requestUrl:n,access:s});return ie(t.id,o)}function un(t){if(t===void 0)return{};if(!oe(t))return null;let e={};for(let r of Object.keys(t))e[r]=t[r];return e}function oe(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function dn(t,e,r,n){let s=new Headers(n);return s.has("content-type")||s.set("content-type","text/plain; charset=utf-8"),S(new Response(t,{status:e,headers:s}),r)}async function fn(t,e,r){let n=new URL(t.url),s=!!e.ARTIFACT_HOST&&n.hostname===e.ARTIFACT_HOST;if(!s&&Ke(n.pathname))return S(await Ye(t,e),e.ARTIFACT_FRAME_ANCESTORS);let i=s?void 0:J(n.hostname,e.ARTIFACT_DEV_PATH);if(!s&&!i)return null;let o=Be({pathname:n.pathname,search:n.search,terminal:s,devPrefix:i});if(o.kind==="passthrough")return null;if(o.kind==="mcp")return S(await pt(t,e,r),e.ARTIFACT_FRAME_ANCESTORS);if(o.kind==="not-found")return dn("not found",404,e.ARTIFACT_FRAME_ANCESTORS);if(o.kind==="redirect")return S(new Response(null,{status:308,headers:{Location:o.location}}),e.ARTIFACT_FRAME_ANCESTORS);let a=e.ARTIFACT.get(e.ARTIFACT.idFromName(o.slug)),c=We(t,o);return S(await a.fetch(c),e.ARTIFACT_FRAME_ANCESTORS)}export{me as ARTIFACT_PKG_VERSION,he as ArtifactDO,be as ArtifactIndexDO,M as HX_HEADER_BASE,F as HX_HEADER_KEY,fn as handleArtifactHost};
951
+ -----END PUBLIC KEY-----`}function Ir(t){let e=se.get(t);if(e)return e;let r=wr(Sr(t),"RS256");return se.set(t,r),r.catch(()=>{se.get(t)===r&&se.delete(t)}),r}function K(){return new Response(JSON.stringify({error:"unauthorized"}),{status:401,headers:{"Content-Type":"application/json","WWW-Authenticate":xr,"Referrer-Policy":"no-referrer"}})}function Lr(t){return(typeof t.email=="string"?t.email.trim():"")||null}async function _r(t,e,r){try{let n=typeof e=="string"?await Ir(e):e,{payload:s}=await Rr(t,n,{algorithms:["RS256"]}),o=Lr(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 ot(t,e){let r=xe(t.headers.get("authorization"));if(!r)return{ok:!1,response:K()};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 _r(r,e.KC_RS256_PK,e.TENANT);return n?{ok:!0,identity:n}:{ok:!1,response:K()}}var Or="artifacts",Nr={artifact_workers:"manage",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 it(t){return Object.prototype.hasOwnProperty.call(Nr,t)}function at(t){return t.modules.includes(Or)}function Se(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 Cr(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 lt(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"?Cr(s,n):Se(s,n)}var Pr=/^[a-z0-9][a-z0-9-]{1,47}$/,Fr=new Set(["mcp","k","api","app","index","assets","static"]),Mr=new Set(["server","browser","system"]),Ur=1024*1024,jr=200,Dr=200,qr=4e3,Hr=1e5,Ie='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). Estilos libres: Tailwind con su paleta normal, daisyUI, CSS propio o fuentes desde jsDelivr; el artifact no tiene que verse como HugeX. artifact.json acepta "theme": "none" (por defecto) o "hugex" (tipograf\xEDa institucional). Cat\xE1logo: preact, preact/hooks, htm, alpinejs, daisyui, lucide, chart.js, echarts, tabulator-tables, @tanstack/table-core, luxon, sortablejs, marked y dompurify (usa marked siempre con dompurify).',Wr={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."}}},ut=[{name:"artifact_workers",description:"List, grant or revoke Workers for an artifact. Only its owner can grant; owner or admin can revoke. Grant requires HX_CORE_URL and HX_API_KEY and verifies the owner can access an active flow in this tenant.",inputSchema:{type:"object",additionalProperties:!1,required:["slug","action"],properties:{slug:{type:"string"},action:{enum:["list","grant","revoke"]},flowId:{type:"string"}}}},{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, paleta neutra de Tailwind, "theme": "none"). Devuelve { slug, uuid, version, url }. '+Ie,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:[...Te],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. "+Ie,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. '+Ie,inputSchema:{type:"object",additionalProperties:!1,required:["slug","files","message","baseVersion"],properties:{slug:{type:"string",description:"Slug del artifact."},files:{type:"array",minItems:1,items:Wr,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 dt(t){return Pr.test(t)?Fr.has(t)?`slug "${t}" is reserved`:null:"slug must match ^[a-z0-9][a-z0-9-]{1,47}$"}function ft(t){return t.length===0||t.length>jr?"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 pt(t,e,r){try{return it(t)?r.access&&!at(r.access)?u({ok:!1,error:"module required: artifacts"}):await Xr(t,e,r):u({ok:!1,error:`unknown tool: ${t}`})}catch(n){let s=n instanceof Error?n.message:"tool failed";return u({ok:!1,error:s})}}async function Xr(t,e,r){switch(t){case"artifact_workers":return $r(e,r);case"artifact_list":return Vr(e,r);case"artifact_create":return Br(e,r);case"artifact_read":return Gr(e,r);case"artifact_logs":return Kr(e,r);case"artifact_query":return Yr(e,r);case"artifact_url":return zr(e,r);case"artifact_write":return Jr(e,r);case"artifact_rollback":return Qr(e,r);case"artifact_settings":return Zr(e,r);case"artifact_versions":return en(e,r);default:return u({ok:!1,error:`unknown tool: ${t}`})}}async function $r(t,e){var l,f,p;let r=T(t,["slug","action","flowId"]);if(r)return u({ok:!1,error:r});let n=L(t);if(typeof n!="string")return n;if(!["list","grant","revoke"].includes(String(t.action)))return u({ok:!1,error:"invalid action"});if(t.action!=="list"&&!_(t.flowId))return u({ok:!1,error:"invalid flowId"});let s=await I(e,n,"manage");if(s.denied)return s.denied;if(t.action==="list"){let g=await s.rpc.listWorkerGrants();return g===null?u({ok:!1,error:"not_found",slug:n}):v(g)}if(t.action==="revoke"){let g=await s.rpc.revokeWorker({flowId:t.flowId,expectUuid:s.meta.uuid});return g===null?u({ok:!1,error:"not_found",slug:n}):v(g)}if(s.meta.owner!==e.identity.email)return u({ok:!1,error:"only the owner can grant Workers"});let o=(l=e.env.HX_CORE_URL)==null?void 0:l.trim().replace(/\/+$/,"");if(!o||!e.env.HX_API_KEY||!e.token)return u({ok:!1,error:"Worker grants require HX_CORE_URL, HX_API_KEY and an owner JWT"});let i=t.flowId;try{let g=await fetch(`${o}/flows/${encodeURIComponent(i)}`,{headers:{Authorization:e.token},cache:"no-store",redirect:"manual"});if(g.status!==200)throw new Error("flow unavailable");if((await g.json()).id!==i)throw new Error("flow unavailable");let b=await fetch(`${o}/ora/flow/${encodeURIComponent(i)}`,{headers:{Authorization:e.env.HX_API_KEY},cache:"no-store",redirect:"manual"});if(b.status!==200)throw new Error("flow unavailable");let A=await b.json();if(((f=A.metadata)==null?void 0:f.tenant)!==e.env.TENANT||s.meta.tenant!==e.env.TENANT||!["active","activo"].includes(((p=A.metadata)==null?void 0:p.status)??""))throw new Error("flow unavailable")}catch{return u({ok:!1,error:"flow unavailable"})}let a=await s.rpc.getMeta();if(!a||a.uuid!==s.meta.uuid||a.owner!==e.identity.email)return u({ok:!1,error:"not_found",slug:n});let c=await s.rpc.grantWorker({flowId:i,grantedBy:e.identity.email,expectUuid:s.meta.uuid,expectOwner:s.meta.owner});return c===null?u({ok:!1,error:"not_found",slug:n}):v(c)}async function Vr(t,e){let r=T(t,[]);if(r)return u({ok:!1,error:r});if(e.access){let s=await Ae(e.env).list();return v(s.filter(o=>Se(o,e.access)))}let n=await Ae(e.env).list({owner:e.identity.email});return v(n.filter(s=>s.owner===e.identity.email))}async function Br(t,e){let r=T(t,["slug","title","template"]);if(r)return u({ok:!1,error:r});if(typeof t.slug!="string")return u({ok:!1,error:"slug is required"});let n=dt(t.slug);if(n)return u({ok:!1,error:n});if(typeof t.title!="string")return u({ok:!1,error:"title is required"});let s=t.title.trim();if(!s||s.length>Dr)return u({ok:!1,error:"title must be 1..200 characters"});let o="blank";if(t.template!==void 0){if(!Z(t.template))return u({ok:!1,error:"template must be blank, dashboard, table, or process-form"});o=t.template}let i=O(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 u({ok:!1,error:"slug already exists",slug:t.slug});let c=await i.write({changes:ee(o,s),message:"create",baseVersion:null,author:e.identity.email});if(!c.ok)return u({ok:!1,error:"initial write failed",slug:a.meta.slug,uuid:a.meta.uuid,write:c});let l=q({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:c.version,url:l};return c.warnings.length>0&&(f.warnings=c.warnings),v(f)}async function Gr(t,e){let r=T(t,["slug","path","version"]);if(r)return u({ok:!1,error:r});let n=L(t);if(typeof n!="string")return n;let s=ct(t,"path");if(typeof s!="string"&&s!==void 0)return u({ok:!1,error:"path must be a string"});if(typeof s=="string"){let l=ft(s);if(l)return u({ok:!1,error:l})}let o=ct(t,"version");if(o===null)return u({ok:!1,error:"version must be a string"});if(typeof o=="string"&&!o)return u({ok:!1,error:"version must be a non-empty string"});let i=await I(e,n,"use");if(i.denied)return i.denied;let a=o??i.meta.activeVersion;if(!a)return u({ok:!1,error:"not_found",slug:n});let c=await i.rpc.readFiles({...s?{path:s}:{},version:a});return c?s&&c.length===0?u({ok:!1,error:"file not found",slug:n,path:s}):v({slug:n,activeVersion:i.meta.activeVersion,version:a,files:c}):u({ok:!1,error:"not_found",slug:n})}async function Kr(t,e){let r=T(t,["slug","limit","source"]);if(r)return u({ok:!1,error:r});let n=L(t);if(typeof n!="string")return n;let s=gt(t.limit);if(s===!1)return u({ok:!1,error:"limit must be an integer from 1 to 1000"});if(t.source!==void 0&&(typeof t.source!="string"||!Mr.has(t.source)))return u({ok:!1,error:"source must be server, browser, or system"});let o=await I(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}):u({ok:!1,error:"not_found",slug:n})}async function Yr(t,e){let r=T(t,["slug","sql"]);if(r)return u({ok:!1,error:r});let n=L(t);if(typeof n!="string")return n;if(typeof t.sql!="string"||!t.sql.trim())return u({ok:!1,error:"sql is required"});if(t.sql.length>Hr)return u({ok:!1,error:"sql is too long"});if(!De(t.sql))return u({ok:!1,error:"artifact_query only accepts a single SELECT statement (WITH and multiple statements are rejected)"});let s=await I(e,n,"use");if(s.denied)return s.denied;let o=await s.rpc.query(t.sql);return o.ok?v(o):u(o)}async function zr(t,e){let r=T(t,["slug"]);if(r)return u({ok:!1,error:r});let n=L(t);if(typeof n!="string")return n;let s=await I(e,n,"use");if(s.denied)return s.denied;let o=await s.rpc.getAccess();if(!o)return u({ok:!1,error:"not_found",slug:n});let i=q({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}):u({ok:!1,error:"artifact URL is not configured (set ARTIFACT_HOST or ARTIFACT_DEV_PATH)",slug:n})}async function Jr(t,e){let r=T(t,["slug","files","message","baseVersion"]);if(r)return u({ok:!1,error:r});let n=L(t);if(typeof n!="string")return n;let s=tn(t.files);if(!Array.isArray(s))return s;if(typeof t.message!="string"||!t.message.trim()||t.message.length>qr)return u({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 u({ok:!1,error:"baseVersion is required and must be the active version id returned by artifact_read or artifact_versions"});let o=await I(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):u(i)}async function Qr(t,e){let r=T(t,["slug","version"]);if(r)return u({ok:!1,error:r});let n=L(t);if(typeof n!="string")return n;if(typeof t.version!="string"||!t.version)return u({ok:!1,error:"version is required"});let s=await I(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):u(o)}async function Zr(t,e){let r=T(t,["slug","group","public","rotateKey"]);if(r)return u({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 u({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 u({ok:!1,error:"public must be a boolean"});s.public=t.public}if(t.rotateKey!==void 0){if(typeof t.rotateKey!="boolean")return u({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 u({ok:!1,error:"settings requires group, public, or rotateKey"});let o=await I(e,n,"manage");if(o.denied)return o.denied;let i=await o.rpc.settings(s);if(!i)return u({ok:!1,error:"not_found",slug:n});let a=q({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 en(t,e){let r=T(t,["slug","limit"]);if(r)return u({ok:!1,error:r});let n=L(t);if(typeof n!="string")return n;let s=gt(t.limit);if(s===!1)return u({ok:!1,error:"limit must be an integer from 1 to 1000"});let o=await I(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}):u({ok:!1,error:"not_found",slug:n})}async function I(t,e,r){let n=O(t.env,e),s=await n.getMeta();return s?lt(r,s,t.identity,t.access)?{denied:null,rpc:n,meta:s}:{denied:u({ok:!1,error:"forbidden",slug:e})}:{denied:u({ok:!1,error:"not_found",slug:e})}}function L(t){if(typeof t.slug!="string")return u({ok:!1,error:"slug is required"});let e=dt(t.slug);return e?u({ok:!1,error:e}):t.slug}function ct(t,e){if(t[e]!==void 0)return typeof t[e]!="string"?null:t[e]}function gt(t){if(t!==void 0)return typeof t!="number"||!Number.isInteger(t)||t<1||t>1e3?!1:t}function tn(t){if(!Array.isArray(t)||t.length===0)return u({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 u({ok:!1,error:"each file must be an object { path, content }"});let o=s,i=T(o,["path","content"]);if(i)return u({ok:!1,error:i});if(typeof o.path!="string")return u({ok:!1,error:"file path is required"});let a=ft(o.path);if(a)return u({ok:!1,error:a,path:o.path});if(r.has(o.path))return u({ok:!1,error:`duplicate path: ${o.path}`});if(r.add(o.path),o.content!==null&&typeof o.content!="string")return u({ok:!1,error:"file content must be a string or null",path:o.path});if(typeof o.content=="string"&&e.encode(o.content).byteLength>Ur)return u({ok:!1,error:`file exceeds 1 MB: ${o.path}`});n.push({path:o.path,content:o.content})}return n}function T(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 u(t){return{content:[{type:"text",text:JSON.stringify(t)}],isError:!0}}var mt=8*1024*1024,rn="hugex-artifact",nn="1.0.0",sn="2025-06-18",on=["2024-11-05","2025-03-26","2025-06-18"],an=["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(" "),ln="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.",cn="RBAC completo: todas las tools exigen el m\xF3dulo artifacts; usar sigue canUseTool y gestionar sigue canManageTool.";function un(t){return`${an} ${t==="phase1"?ln:cn}`}async function yt(t,e,r){if(t.method!=="POST")return dn();let n=await ot(t,e);if(!n.ok)return n.response;let s=xe(t.headers.get("authorization"));if(!s)return K();let o=await st(e,s);if(!o.ok)return o.status===401?K():pn();let i=o.mode==="rbac"?o.access:null;if(!gn(t.headers.get("content-type")))return oe(415,"Content-Type must be application/json");let a=t.headers.get("content-length");if(a!==null){if(!/^\d+$/.test(a))return oe(400,"invalid content-length");if(Number(a)>mt)return oe(413,"payload too large")}let c=await t.arrayBuffer();if(c.byteLength>mt)return oe(413,"payload too large");let l;try{l=JSON.parse(new TextDecoder().decode(c))}catch{return w(null,-32700,"Parse error",400)}if(Array.isArray(l))return w(null,-32600,"Invalid Request",400,"batch is not supported");if(l===null||typeof l!="object")return w(null,-32600,"Invalid Request",400);let f=mn(l);return f.ok?f.notification?fn():hn(f.request,n.identity,e,t.url,o.mode,i,s):f.response}function dn(){return new Response(null,{status:405,headers:{Allow:"POST","Referrer-Policy":"no-referrer"}})}function fn(){return new Response(null,{status:202,headers:{"Referrer-Policy":"no-referrer"}})}function pn(){return new Response(JSON.stringify({error:"forbidden"}),{status:403,headers:{"Content-Type":"application/json","Referrer-Policy":"no-referrer"}})}function oe(t,e){return new Response(e,{status:t,headers:{"Content-Type":"text/plain; charset=utf-8","Referrer-Policy":"no-referrer"}})}function bt(t,e){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":"application/json","Referrer-Policy":"no-referrer"}})}function ie(t,e){return bt(200,{jsonrpc:"2.0",id:t,result:e})}function w(t,e,r,n=200,s){let o={code:e,message:r};return s!==void 0&&(o.data=s),bt(n,{jsonrpc:"2.0",id:t,error:o})}function gn(t){var e;return t?((e=t.split(";",1)[0])==null?void 0:e.trim().toLowerCase())==="application/json":!1}function mn(t){return t.jsonrpc!=="2.0"||typeof t.method!="string"||t.method.length===0?{ok:!1,response:w(ht(t.id),-32600,"Invalid Request",400)}:t.params!==void 0&&!(Array.isArray(t.params)||typeof t.params=="object"&&t.params!==null)?{ok:!1,response:w(ht(t.id),-32600,"Invalid Request",400)}:!Object.prototype.hasOwnProperty.call(t,"id")||t.method.startsWith("notifications/")?{ok:!0,notification:!0}:vt(t.id)?{ok:!0,notification:!1,request:{method:t.method,params:t.params,id:t.id}}:{ok:!1,response:w(null,-32600,"Invalid Request",400)}}function ht(t){return vt(t)?t:null}function vt(t){return t===null||typeof t=="string"?!0:typeof t=="number"&&Number.isFinite(t)}async function hn(t,e,r,n,s,o,i){switch(t.method){case"initialize":return yn(t,s);case"ping":return ie(t.id,{});case"tools/list":return t.params!==void 0&&!ae(t.params)?w(t.id,-32602,"Invalid params"):ie(t.id,{tools:ut});case"tools/call":return bn(t,e,r,n,o,i);default:return w(t.id,-32601,"Method not found")}}function yn(t,e){if(t.params!==void 0&&!ae(t.params))return w(t.id,-32602,"Invalid params");let r=t.params??{},n=sn;if(r.protocolVersion!==void 0){if(typeof r.protocolVersion!="string")return w(t.id,-32602,"Invalid params");on.includes(r.protocolVersion)&&(n=r.protocolVersion)}return ie(t.id,{protocolVersion:n,capabilities:{tools:{}},serverInfo:{name:rn,version:nn},instructions:un(e)})}async function bn(t,e,r,n,s,o){if(!ae(t.params)||typeof t.params.name!="string"||!t.params.name)return w(t.id,-32602,"Invalid params");let i=vn(t.params.arguments);if(!i)return w(t.id,-32602,"Invalid params");let a=await pt(t.params.name,i,{env:r,identity:e,requestUrl:n,access:s,token:o});return ie(t.id,a)}function vn(t){if(t===void 0)return{};if(!ae(t))return null;let e={};for(let r of Object.keys(t))e[r]=t[r];return e}function ae(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Et(t,e,r,n){let s=new Headers(n);return s.has("content-type")||s.set("content-type","text/plain; charset=utf-8"),S(new Response(t,{status:e,headers:s}),r)}async function En(t,e,r,n){let s=new URL(t.url),o=!!e.ARTIFACT_HOST&&s.hostname===e.ARTIFACT_HOST;if(!o&&Qe(s.pathname))return S(await Ze(t,e),e.ARTIFACT_FRAME_ANCESTORS);let i=o?void 0:Q(s.hostname,e.ARTIFACT_DEV_PATH);if(!o&&!i)return null;let a=Ye({pathname:s.pathname,search:s.search,terminal:o,devPrefix:i});if(a.kind==="passthrough")return null;if(a.kind==="mcp")return S(await yt(t,e,r),e.ARTIFACT_FRAME_ANCESTORS);if(a.kind==="not-found")return Et("not found",404,e.ARTIFACT_FRAME_ANCESTORS);if(a.kind==="redirect")return S(new Response(null,{status:308,headers:{Location:a.location}}),e.ARTIFACT_FRAME_ANCESTORS);if(a.kind==="agent")return An(t,e,r,a,n);let c=e.ARTIFACT.get(e.ARTIFACT.idFromName(a.slug)),l=ze(t,a);return S(await c.fetch(l),e.ARTIFACT_FRAME_ANCESTORS)}async function An(t,e,r,n,s){var l;let o=()=>Et("not found",404,e.ARTIFACT_FRAME_ANCESTORS),i=s==null?void 0:s.agentProxy;if(typeof i!="function"||t.method!=="GET"||((l=t.headers.get("Upgrade"))==null?void 0:l.toLowerCase())!=="websocket")return o();let a;try{a=await O(e,n.slug).allowsWorker({flowId:n.flowId,key:n.key||null,mode:"browser"})}catch{return o()}if(!(a!=null&&a.ok))return o();let c=await i(t,e,r,{flowId:n.flowId,sessionId:n.sessionId});return c.status===101?c:S(c,e.ARTIFACT_FRAME_ANCESTORS)}export{he as ARTIFACT_PKG_VERSION,be as ArtifactDO,Ee as ArtifactIndexDO,D as HX_HEADER_BASE,j as HX_HEADER_KEY,En as handleArtifactHost};
package/dist/limits.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- /** MVP caps from PLAN-ARTIFACTS.md section 10. Byte counts are decimal MB as in the spike. */
1
+ /** MVP caps from plans/notes/artifacts-design.md section 10 (workspace root). Byte counts are decimal MB as in the spike. */
2
2
  export declare const LIMITS: {
3
3
  readonly fileBytes: 1000000;
4
4
  readonly versionBytes: 5000000;
@@ -24,6 +24,7 @@ export type ToolAccessRow = {
24
24
  org?: string | null;
25
25
  };
26
26
  export declare const TOOL_PERMISSION: {
27
+ readonly artifact_workers: 'manage';
27
28
  readonly artifact_list: 'module';
28
29
  readonly artifact_create: 'module';
29
30
  readonly artifact_read: 'use';
@@ -1,7 +1,3 @@
1
- /**
2
- * MCP tool definitions and handlers for @hugex/artifact.
3
- * Authorization happens before any mutating RPC. The Durable Object does not authorize.
4
- */
5
1
  import { isSingleSelect } from '../sql';
6
2
  import { artifactIndexRpc, artifactRpc } from '../rpc';
7
3
  import type { ArtifactEnv } from '../types';
@@ -15,6 +11,8 @@ interface ToolDeps {
15
11
  identity: ArtifactIdentity;
16
12
  requestUrl: string;
17
13
  access: ArtifactAccess | null;
14
+ /** Verified MCP bearer token, forwarded only to hx-core. */
15
+ token?: string;
18
16
  }
19
17
  export interface ToolDefinition {
20
18
  name: string;
package/dist/types.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Contract shared by the @hugex/artifact runtime (ArtifactDO, ArtifactIndexDO, host routing) and the MCP layer.
3
- * Owned by the orchestrator: workers must not change these shapes without updating .orchestrator/00-ESTADO.md.
3
+ * Owned by the orchestrator: workers must not change these shapes without updating plans/notes/artifacts-design.md (§10 contract, workspace root).
4
4
  */
5
5
  /** Bindings and vars a tenant worker must provide to mount @hugex/artifact. */
6
6
  export interface ArtifactEnv {
@@ -35,7 +35,45 @@ export interface ArtifactEnv {
35
35
  HX_ORA_URL?: string;
36
36
  /** Tenant API key sent as the `Authorization` header to hx-ora internal routes (no `Bearer` prefix). */
37
37
  HX_API_KEY?: string;
38
+ /**
39
+ * hx-core base URL, e.g. `http://localhost:3001`. Same variable the ora worker already uses.
40
+ * `artifact_workers grant` needs it (with `HX_API_KEY`) to check that the owner can use the flow.
41
+ * Without it, granting a Worker fails; list and revoke still work.
42
+ */
43
+ HX_CORE_URL?: string;
44
+ }
45
+ /** Target of the same-origin agent route `<base>/__hx/agent/<flowId>/<sessionId>`. */
46
+ export interface ArtifactAgentProxyTarget {
47
+ flowId: string;
48
+ sessionId: string;
38
49
  }
50
+ /**
51
+ * Injected by the tenant (for example `artifactAgentProxy` from `@hugex/ai`). Runs the tenant's
52
+ * flow chat handler for the visitor. `@hugex/artifact` does not depend on the agent runtime.
53
+ */
54
+ export type ArtifactAgentProxy = (request: Request, env: any, ctx: ExecutionContext, target: ArtifactAgentProxyTarget) => Promise<Response>;
55
+ export interface ArtifactHostOptions {
56
+ /** Without it, `__hx/agent/...` is a 404. */
57
+ agentProxy?: ArtifactAgentProxy;
58
+ }
59
+ /** A flow the artifact owner allowed this artifact to talk to. */
60
+ export interface WorkerGrant {
61
+ flowId: string;
62
+ grantedBy: string;
63
+ grantedAt: string;
64
+ }
65
+ export type AllowsWorkerInput = {
66
+ flowId: string;
67
+ key?: string | null;
68
+ mode: 'browser' | 'server';
69
+ artifactUuid?: string;
70
+ };
71
+ export type AllowsWorkerResult = {
72
+ ok: true;
73
+ owner: string;
74
+ } | {
75
+ ok: false;
76
+ };
39
77
  export type ArtifactGroup = 'none' | 'all' | (string & {});
40
78
  export type VersionState = 'provisional' | 'activa' | 'fallida' | 'anterior';
41
79
  export interface ArtifactMeta {
@@ -197,6 +235,28 @@ export interface ArtifactRpc {
197
235
  ok: true;
198
236
  oraSyncFailed?: boolean;
199
237
  } | null>;
238
+ /**
239
+ * May this artifact talk to the Worker `flowId`? `browser` also requires access to the artifact
240
+ * (public, or a valid key). `server` requires artifactUuid to match the current artifact and checks the grant.
241
+ * In browser mode artifactUuid is optional; when supplied it must also match.
242
+ */
243
+ allowsWorker(input: AllowsWorkerInput): Promise<AllowsWorkerResult>;
244
+ /** Grants, oldest first. Null when the artifact does not exist. */
245
+ listWorkerGrants(): Promise<WorkerGrant[] | null>;
246
+ /** Upsert. The caller validated the owner and flow. Null when UUID or owner no longer matches. */
247
+ grantWorker(input: {
248
+ flowId: string;
249
+ grantedBy: string;
250
+ expectUuid: string;
251
+ expectOwner: string;
252
+ }): Promise<WorkerGrant | null>;
253
+ /** Null when the artifact does not exist or its UUID no longer matches. */
254
+ revokeWorker(input: {
255
+ flowId: string;
256
+ expectUuid: string;
257
+ }): Promise<{
258
+ removed: boolean;
259
+ } | null>;
200
260
  }
201
261
  /** RPC surface of ArtifactIndexDO (stub = env.ARTIFACT_INDEX.get(env.ARTIFACT_INDEX.idFromName('index'))). */
202
262
  export interface ArtifactIndexRpc {
@@ -8,6 +8,12 @@ export declare function validateSlug(slug: string): string | null;
8
8
  * Rejects `..`, a leading `/`, backslashes, empty segments, and paths over 200 chars.
9
9
  */
10
10
  export declare function validateFilePath(path: string): string | null;
11
+ /** Same flow id grammar as the tenant's flow chat route. */
12
+ export declare const WORKER_FLOW_ID_RE: RegExp;
13
+ /** Browser sessions are `crypto.randomUUID()` values (UUID v4). */
14
+ export declare const WORKER_SESSION_ID_RE: RegExp;
15
+ export declare function isWorkerFlowId(value: unknown): value is string;
16
+ export declare function isWorkerSessionId(value: unknown): value is string;
11
17
  export type ArtifactTheme = "hugex" | "none";
12
18
  export type ArtifactManifest = {
13
19
  title: string;
@@ -0,0 +1,2 @@
1
+ /** Dependency-free browser client. The injected base includes the artifact access key. */
2
+ export declare function workerClientScript(baseHref: string): string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hugex/artifact",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "HugeX Artifacts runtime for Cloudflare Workers",
5
5
  "author": "a@hugex.co",
6
6
  "license": "SEE LICENSE IN LICENSE",