@embd/mcp 0.1.0 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +121 -4
- package/dist/bin-2pd22980.js +77 -0
- package/dist/bin-5b95b3jx.js +17 -0
- package/dist/bin-crkm8v3n.js +14 -0
- package/dist/bin-facfqmdm.js +70 -0
- package/dist/bin-ph1y1a8b.js +4 -0
- package/dist/bin.js +2 -4
- package/dist/documents-bin.js +2 -0
- package/dist/http-bin.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +12 -8
- package/dist/bin-kp5d3tt5.js +0 -14
- package/dist/bin-q5p2211j.js +0 -92
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import{A as C2,B as N2,C as R2,D as C,L as I2,M as O2}from"./bin-2pd22980.js";var $2=N2((h0,g0)=>{(function(Z,$){if(typeof define==="function"&&define.amd)define([],$);else if(typeof g0==="object"&&typeof h0<"u")g0.exports=$();else Z.Papa=$()})(h0,function Z(){var $=function(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof $<"u")return $;return{}}();function U(){var Y=$.URL||$.webkitURL||null,J=Z.toString();return G.BLOB_URL||(G.BLOB_URL=Y.createObjectURL(new Blob(["var global = (function() { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } return {}; })(); global.IS_PAPA_WORKER=true; ","(",J,")();"],{type:"text/javascript"})))}var V=!$.document&&!!$.postMessage,W=$.IS_PAPA_WORKER||!1,_={},I=0,G={};if(G.parse=Y0,G.unparse=v,G.RECORD_SEP=String.fromCharCode(30),G.UNIT_SEP=String.fromCharCode(31),G.BYTE_ORDER_MARK="\uFEFF",G.BAD_DELIMITERS=["\r",`
|
|
2
|
+
`,'"',G.BYTE_ORDER_MARK],G.WORKERS_SUPPORTED=!V&&!!$.Worker,G.NODE_STREAM_INPUT=1,G.LocalChunkSize=10485760,G.RemoteChunkSize=5242880,G.DefaultDelimiter=",",G.Parser=W0,G.ParserHandle=i,G.NetworkStreamer=m,G.FileStreamer=a,G.StringStreamer=t,G.ReadableStreamStreamer=$0,typeof PAPA_BROWSER_CONTEXT>"u")G.DuplexStreamStreamer=N;if($.jQuery){var f=$.jQuery;f.fn.parse=function(Y){var J=Y.config||{},X=[];return this.each(function(K){var F=f(this).prop("tagName").toUpperCase()==="INPUT"&&f(this).attr("type").toLowerCase()==="file"&&$.FileReader;if(!F||!this.files||this.files.length===0)return!0;for(var E=0;E<this.files.length;E++)X.push({file:this.files[E],inputElem:this,instanceConfig:f.extend({},J)})}),M(),this;function M(){if(X.length===0){if(S(Y.complete))Y.complete();return}var K=X[0];if(S(Y.before)){var F=Y.before(K.file,K.inputElem);if(typeof F==="object"){if(F.action==="abort"){Q("AbortError",K.file,K.inputElem,F.reason);return}else if(F.action==="skip"){L();return}else if(typeof F.config==="object")K.instanceConfig=f.extend(K.instanceConfig,F.config)}else if(F==="skip"){L();return}}var E=K.instanceConfig.complete;K.instanceConfig.complete=function(x){if(S(E))E(x,K.file,K.inputElem);L()},G.parse(K.file,K.instanceConfig)}function Q(K,F,E,x){if(S(Y.error))Y.error({name:K},F,E,x)}function L(){X.splice(0,1),M()}}}if(W)$.onmessage=j2;function e(Y){if(Y.charCodeAt(0)===65279)return Y.slice(1);return Y}function Y0(Y,J){J=J||{};var X=J.dynamicTyping||!1;if(S(X))J.dynamicTypingFunction=X,X={};if(J.dynamicTyping=X,J.transform=S(J.transform)?J.transform:!1,J.worker&&G.WORKERS_SUPPORTED){var M=D0();M.userStep=J.step,M.userChunk=J.chunk,M.userComplete=J.complete,M.userError=J.error,J.step=S(J.step),J.chunk=S(J.chunk),J.complete=S(J.complete),J.error=S(J.error),delete J.worker,M.postMessage({input:Y,config:J,workerId:M.id});return}var Q=null;if(Y===G.NODE_STREAM_INPUT&&typeof PAPA_BROWSER_CONTEXT>"u")return Q=new N(J),Q.getStream();else if(typeof Y==="string")if(Y=e(Y),J.download)Q=new m(J);else Q=new t(J);else if(Y.readable===!0&&S(Y.read)&&S(Y.on))Q=new $0(J);else if($.File&&Y instanceof File||Y instanceof Object)Q=new a(J);return Q.stream(Y)}function v(Y,J){var X=!1,M=!0,Q=",",L=`\r
|
|
3
|
+
`,K='"',F=K+K,E=!1,x=null,h=!1;r();var O=new RegExp(J0(K),"g");if(typeof Y==="string")Y=JSON.parse(Y);if(Array.isArray(Y)){if(!Y.length||Array.isArray(Y[0]))return B(null,Y,E);else if(typeof Y[0]==="object")return B(x||Object.keys(Y[0]),Y,E)}else if(typeof Y==="object"){if(typeof Y.data==="string")Y.data=JSON.parse(Y.data);if(Array.isArray(Y.data)){if(!Y.fields)Y.fields=Y.meta&&Y.meta.fields||x;if(!Y.fields)Y.fields=Array.isArray(Y.data[0])?Y.fields:typeof Y.data[0]==="object"?Object.keys(Y.data[0]):[];if(!Array.isArray(Y.data[0])&&typeof Y.data[0]!=="object")Y.data=[Y.data]}return B(Y.fields||[],Y.data||[],E)}throw Error("Unable to serialize unrecognized input");function r(){if(typeof J!=="object")return;if(typeof J.delimiter==="string"&&!G.BAD_DELIMITERS.filter(function(A){return J.delimiter.indexOf(A)!==-1}).length)Q=J.delimiter;if(typeof J.quotes==="boolean"||typeof J.quotes==="function"||Array.isArray(J.quotes))X=J.quotes;if(typeof J.skipEmptyLines==="boolean"||typeof J.skipEmptyLines==="string")E=J.skipEmptyLines;if(typeof J.newline==="string")L=J.newline;if(typeof J.quoteChar==="string")K=J.quoteChar,F=K+K;if(typeof J.header==="boolean")M=J.header;if(Array.isArray(J.columns)){if(J.columns.length===0)throw Error("Option columns is empty");x=J.columns}if(J.escapeChar!==void 0)F=J.escapeChar+K;if(J.escapeFormulae instanceof RegExp)h=J.escapeFormulae;else if(typeof J.escapeFormulae==="boolean"&&J.escapeFormulae)h=/^[=+\-@\t\r].*$/}function B(A,R,b){var p="";if(typeof A==="string")A=JSON.parse(A);if(typeof R==="string")R=JSON.parse(R);var g=Array.isArray(A)&&A.length>0,u=!Array.isArray(R[0]);if(g&&M){for(var s=0;s<A.length;s++){if(s>0)p+=Q;p+=j(A[s],s)}if(R.length>0)p+=L}for(var q=0;q<R.length;q++){var G0=g?A.length:R[q].length,Z0=!1,z=g?Object.keys(R[q]).length===0:R[q].length===0;if(b&&!g)Z0=b==="greedy"?R[q].join("").trim()==="":R[q].length===1&&R[q][0].length===0;if(b==="greedy"&&g){var H=[];for(var D=0;D<G0;D++){var k=u?A[D]:D;H.push(R[q][k])}Z0=H.join("").trim()===""}if(!Z0){for(var P=0;P<G0;P++){if(P>0&&!z)p+=Q;var y=g&&u?A[P]:P;p+=j(R[q][y],P)}if(q<R.length-1&&(!b||G0>0&&!z))p+=L}}return p}function j(A,R){if(typeof A>"u"||A===null)return"";if(A.constructor===Date)return JSON.stringify(A).slice(1,25);var b=!1;if(h&&typeof A==="string"&&h.test(A))A="'"+A,b=!0;var p=A.toString(),g=p.replace(O,F);return b=b||X===!0||typeof X==="function"&&X(A,R)||Array.isArray(X)&&X[R]||P0(g,G.BAD_DELIMITERS)||g.indexOf(Q)>-1||p.indexOf(K)>-1||g.charAt(0)===" "||g.charAt(g.length-1)===" ",b?K+g+K:g}function P0(A,R){for(var b=0;b<R.length;b++)if(A.indexOf(R[b])>-1)return!0;return!1}}function T(Y){this._handle=null,this._finished=!1,this._completed=!1,this._halted=!1,this._input=null,this._baseIndex=0,this._partialLine="",this._rowCount=0,this._start=0,this._nextChunk=null,this.isFirstChunk=!0,this._completeResults={data:[],errors:[],meta:{}},J.call(this,Y),this.parseChunk=function(X,M){let Q=parseInt(this._config.skipFirstNLines)||0;if(this.isFirstChunk&&Q>0){let h=this._config.newline;if(!h){let r=this._config.quoteChar||'"';h=this._handle.guessLineEndings(X,r)}X=[...X.split(h).slice(Q)].join(h)}if(this.isFirstChunk&&S(this._config.beforeFirstChunk)){var L=this._config.beforeFirstChunk(X);if(L!==void 0)X=L}this.isFirstChunk=!1,this._halted=!1;var K=this._partialLine+X;this._partialLine="";var F=this._handle.parse(K,this._baseIndex,!this._finished);if(this._handle.paused()||this._handle.aborted()){this._halted=!0;return}var E=F.meta.cursor;if(!this._finished)this._partialLine=K.substring(E-this._baseIndex),this._baseIndex=E;if(F&&F.data)this._rowCount+=F.data.length;var x=this._finished||this._config.preview&&this._rowCount>=this._config.preview;if(W)$.postMessage({results:F,workerId:G.WORKER_ID,finished:x});else if(S(this._config.chunk)&&!M){if(this._config.chunk(F,this._handle),this._handle.paused()||this._handle.aborted()){this._halted=!0;return}F=void 0,this._completeResults=void 0}if(!this._config.step&&!this._config.chunk)this._completeResults.data=this._completeResults.data.concat(F.data),this._completeResults.errors=this._completeResults.errors.concat(F.errors),this._completeResults.meta=F.meta;if(!this._completed&&x&&S(this._config.complete)&&(!F||!F.meta.aborted))this._config.complete(this._completeResults,this._input),this._completed=!0;if(!x&&(!F||!F.meta.paused))this._nextChunk();return F},this._sendError=function(X){if(S(this._config.error))this._config.error(X);else if(W&&this._config.error)$.postMessage({workerId:G.WORKER_ID,error:X,finished:!1})};function J(X){var M=N0(X);if(M.chunkSize=parseInt(M.chunkSize),!X.step&&!X.chunk)M.chunkSize=null;this._handle=new i(M),this._handle.streamer=this,this._config=M}}function m(Y){if(Y=Y||{},!Y.chunkSize)Y.chunkSize=G.RemoteChunkSize;T.call(this,Y);var J;if(V)this._nextChunk=function(){this._readChunk(),this._chunkLoaded()};else this._nextChunk=function(){this._readChunk()};this.stream=function(M){this._input=M,this._nextChunk()},this._readChunk=function(){if(this._finished){this._chunkLoaded();return}if(J=new XMLHttpRequest,this._config.withCredentials)J.withCredentials=this._config.withCredentials;if(!V)J.onload=n(this._chunkLoaded,this),J.onerror=n(this._chunkError,this);if(J.open(this._config.downloadRequestBody?"POST":"GET",this._input,!V),this._config.downloadRequestHeaders){var M=this._config.downloadRequestHeaders;for(var Q in M)J.setRequestHeader(Q,M[Q])}if(this._config.chunkSize){var L=this._start+this._config.chunkSize-1;J.setRequestHeader("Range","bytes="+this._start+"-"+L)}try{J.send(this._config.downloadRequestBody)}catch(K){this._chunkError(K.message)}if(V&&J.status===0)this._chunkError()},this._chunkLoaded=function(){if(J.readyState!==4)return;if(J.status<200||J.status>=400){this._chunkError();return}this._start+=this._config.chunkSize?this._config.chunkSize:J.responseText.length,this._finished=!this._config.chunkSize||this._start>=X(J),this.parseChunk(J.responseText)},this._chunkError=function(M){var Q=J.statusText||M;this._sendError(Error(Q))};function X(M){var Q=M.getResponseHeader("Content-Range");if(Q===null)return-1;return parseInt(Q.substring(Q.lastIndexOf("/")+1))}}m.prototype=Object.create(T.prototype),m.prototype.constructor=m;function a(Y){if(Y=Y||{},!Y.chunkSize)Y.chunkSize=G.LocalChunkSize;T.call(this,Y);var J,X,M=typeof FileReader<"u";this.stream=function(Q){if(this._input=Q,X=Q.slice||Q.webkitSlice||Q.mozSlice,M)J=new FileReader,J.onload=n(this._chunkLoaded,this),J.onerror=n(this._chunkError,this);else J=new FileReaderSync;this._nextChunk()},this._nextChunk=function(){if(!this._finished&&(!this._config.preview||this._rowCount<this._config.preview))this._readChunk()},this._readChunk=function(){var Q=this._input;if(this._config.chunkSize){var L=Math.min(this._start+this._config.chunkSize,this._input.size);Q=X.call(Q,this._start,L)}var K=J.readAsText(Q,this._config.encoding);if(!M)this._chunkLoaded({target:{result:K}})},this._chunkLoaded=function(Q){this._start+=this._config.chunkSize,this._finished=!this._config.chunkSize||this._start>=this._input.size,this.parseChunk(Q.target.result)},this._chunkError=function(){this._sendError(J.error)}}a.prototype=Object.create(T.prototype),a.prototype.constructor=a;function t(Y){Y=Y||{},T.call(this,Y);var J;this.stream=function(X){return J=X,this._nextChunk()},this._nextChunk=function(){if(this._finished)return;var X=this._config.chunkSize,M;if(X)M=J.substring(0,X),J=J.substring(X);else M=J,J="";return this._finished=!J,this.parseChunk(M)}}t.prototype=Object.create(t.prototype),t.prototype.constructor=t;function $0(Y){Y=Y||{},T.call(this,Y);var J=[],X=!0,M=!1;this.pause=function(){T.prototype.pause.apply(this,arguments),this._input.pause()},this.resume=function(){T.prototype.resume.apply(this,arguments),this._input.resume()},this.stream=function(Q){this._input=Q,this._input.on("data",this._streamData),this._input.on("end",this._streamEnd),this._input.on("error",this._streamError)},this._checkIsFinished=function(){if(M&&J.length===1)this._finished=!0},this._nextChunk=function(){if(this._checkIsFinished(),J.length)this.parseChunk(J.shift());else X=!0},this._streamData=n(function(Q){try{if(J.push(typeof Q==="string"?Q:Q.toString(this._config.encoding)),X)X=!1,this._checkIsFinished(),this.parseChunk(J.shift())}catch(L){this._streamError(L)}},this),this._streamError=n(function(Q){this._streamCleanUp(),this._sendError(Q)},this),this._streamEnd=n(function(){this._streamCleanUp(),M=!0,this._streamData("")},this),this._streamCleanUp=n(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError)},this)}$0.prototype=Object.create(T.prototype),$0.prototype.constructor=$0;function N(Y){var J=R2("stream").Duplex,X=N0(Y),M=!0,Q=!1,L=[],K=null;this._onCsvData=function(F){var E=F.data;if(!K.push(E)&&!this._handle.paused())this._handle.pause()},this._onCsvComplete=function(){K.push(null)},X.step=n(this._onCsvData,this),X.complete=n(this._onCsvComplete,this),T.call(this,X),this._nextChunk=function(){if(Q&&L.length===1)this._finished=!0;if(L.length)L.shift()();else M=!0},this._addToParseQueue=function(F,E){if(L.push(n(function(){if(this.parseChunk(typeof F==="string"?F:F.toString(X.encoding)),S(E))return E()},this)),M)M=!1,this._nextChunk()},this._onRead=function(){if(this._handle.paused())this._handle.resume()},this._onWrite=function(F,E,x){this._addToParseQueue(F,x)},this._onWriteComplete=function(){Q=!0,this._addToParseQueue("")},this.getStream=function(){return K},K=new J({readableObjectMode:!0,decodeStrings:!1,read:n(this._onRead,this),write:n(this._onWrite,this)}),K.once("finish",n(this._onWriteComplete,this))}if(typeof PAPA_BROWSER_CONTEXT>"u")N.prototype=Object.create(T.prototype),N.prototype.constructor=N;function i(Y){var J=Math.pow(2,53),X=-J,M=/^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/,Q=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,L=this,K=0,F=0,E,x,h=!1,O=!1,r,B=[],j={data:[],errors:[],meta:{}};if(S(Y.step)){var P0=Y.step;Y.step=function(z){if(j=z,p())b();else{if(b(),j.data.length===0)return;if(K+=z.data.length,Y.preview&&K>Y.preview)x.abort();else j.data=j.data[0],P0(j,L)}}}this.parse=function(z,H,D){var k=Y.quoteChar||'"';if(!Y.newline)Y.newline=this.guessLineEndings(z,k);if(r=!1,!Y.delimiter){var P=G0(z,Y.newline,Y.skipEmptyLines,Y.comments,Y.delimitersToGuess);if(P.successful)Y.delimiter=P.bestDelimiter;else r=!0,Y.delimiter=G.DefaultDelimiter;j.meta.delimiter=Y.delimiter}else if(S(Y.delimiter))Y.delimiter=Y.delimiter(z),j.meta.delimiter=Y.delimiter;var y=N0(Y);if(Y.preview&&Y.header)y.preview++;return E=z,x=new W0(y),j=x.parse(E,H,D),b(),h?{meta:{paused:!0}}:j||{meta:{paused:!1}}},this.paused=function(){return h},this.pause=function(){h=!0,x.abort(),E=S(Y.chunk)?"":E.substring(x.getCharIndex())},this.resume=function(){if(L.streamer._halted)h=!1,L.streamer.parseChunk(E,!0);else setTimeout(L.resume,3)},this.aborted=function(){return O},this.abort=function(){if(O=!0,x.abort(),j.meta.aborted=!0,S(Y.complete))Y.complete(j);E=""},this.guessLineEndings=function(z,H){z=z.substring(0,1048576);var D=new RegExp(J0(H)+"([^]*?)"+J0(H),"gm");z=z.replace(D,"");var k=z.split("\r"),P=z.split(`
|
|
4
|
+
`),y=P.length>1&&P[0].length<k[0].length;if(k.length===1||y)return`
|
|
5
|
+
`;var c=0;for(var w=0;w<k.length;w++)if(k[w][0]===`
|
|
6
|
+
`)c++;return c>=k.length/2?`\r
|
|
7
|
+
`:"\r"};function A(z){return Y.skipEmptyLines==="greedy"?z.join("").trim()==="":z.length===1&&z[0].length===0}function R(z){if(M.test(z)){var H=parseFloat(z);if(H>X&&H<J)return!0}return!1}function b(){if(j&&r)Z0("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+G.DefaultDelimiter+"'"),r=!1;if(Y.skipEmptyLines)j.data=j.data.filter(function(z){return!A(z)});if(p())g();return q()}function p(){return Y.header&&B.length===0}function g(){if(!j)return;function z(D,k){if(D=e(D),S(Y.transformHeader))D=Y.transformHeader(D,k);B.push(D)}if(Array.isArray(j.data[0])){for(var H=0;p()&&H<j.data.length;H++)j.data[H].forEach(z);j.data.splice(0,1)}else j.data.forEach(z)}function u(z){if(Y.dynamicTypingFunction&&Y.dynamicTyping[z]===void 0)Y.dynamicTyping[z]=Y.dynamicTypingFunction(z);return(Y.dynamicTyping[z]||Y.dynamicTyping)===!0}function s(z,H){if(u(z))if(H==="true"||H==="TRUE")return!0;else if(H==="false"||H==="FALSE")return!1;else if(R(H))return parseFloat(H);else if(Q.test(H))return new Date(H);else return H===""?null:H;return H}function q(){if(!j||!Y.header&&!Y.dynamicTyping&&!Y.transform)return j;function z(D,k){var P=Y.header?{}:[],y;for(y=0;y<D.length;y++){var c=y,w=D[y];if(Y.header)c=y>=B.length?"__parsed_extra":B[y];if(Y.transform)w=Y.transform(w,c);if(w=s(c,w),c==="__parsed_extra")P[c]=P[c]||[],P[c].push(w);else P[c]=w}if(Y.header){if(y>B.length)Z0("FieldMismatch","TooManyFields","Too many fields: expected "+B.length+" fields but parsed "+y,F+k);else if(y<B.length)Z0("FieldMismatch","TooFewFields","Too few fields: expected "+B.length+" fields but parsed "+y,F+k)}return P}var H=1;if(!j.data.length||Array.isArray(j.data[0]))j.data=j.data.map(z),H=j.data.length;else j.data=z(j.data,0);if(Y.header&&j.meta)j.meta.fields=B;return F+=H,j}function G0(z,H,D,k,P){var y,c,w,K0;P=P||[",","\t","|",";",G.RECORD_SEP,G.UNIT_SEP];for(var M0=0;M0<P.length;M0++){var L0=P[M0],z0=0,F0=0,d=0;w=void 0;var U0=new W0({comments:k,delimiter:L0,newline:H,preview:10}).parse(z);for(var l=0;l<U0.data.length;l++){if(D&&A(U0.data[l])){d++;continue}var o=U0.data[l].length;if(F0+=o,typeof w>"u"){w=o;continue}else if(o>0)z0+=Math.abs(o-w),w=o}if(U0.data.length>0)F0/=U0.data.length-d;if((typeof c>"u"||z0<=c)&&(typeof K0>"u"||F0>K0)&&F0>1.99)c=z0,y=L0,K0=F0}return Y.delimiter=y,{successful:!!y,bestDelimiter:y}}function Z0(z,H,D,k){var P={type:z,code:H,message:D};if(k!==void 0)P.row=k;j.errors.push(P)}}function J0(Y){return Y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function W0(Y){Y=Y||{};var{delimiter:J,newline:X,comments:M,step:Q,preview:L,fastMode:K}=Y,F,E=null,x=!1;if(Y.quoteChar===void 0||Y.quoteChar===null)F='"';else F=Y.quoteChar;var h=F;if(Y.escapeChar!==void 0)h=Y.escapeChar;if(typeof J!=="string"||G.BAD_DELIMITERS.indexOf(J)>-1)J=",";if(M===J)throw Error("Comment character same as delimiter");else if(M===!0)M="#";else if(typeof M!=="string"||G.BAD_DELIMITERS.indexOf(M)>-1)M=!1;if(X!==`
|
|
8
|
+
`&&X!=="\r"&&X!==`\r
|
|
9
|
+
`)X=`
|
|
10
|
+
`;var O=0,r=!1;this.parse=function(B,j,P0){if(typeof B!=="string")throw Error("Input must be a string");var A=B.length,R=J.length,b=X.length,p=M.length,g=S(Q);O=0;var u=[],s=[],q=[],G0=0;if(!B)return d();if(K||K!==!1&&B.indexOf(F)===-1){var Z0=B.split(X);for(var z=0;z<Z0.length;z++){if(q=Z0[z],O+=q.length,z!==Z0.length-1)O+=X.length;else if(P0)return d();if(M&&q.substring(0,p)===M)continue;if(g){if(u=[],M0(q.split(J)),U0(),r)return d()}else M0(q.split(J));if(L&&z>=L)return u=u.slice(0,L),d(!0)}return d()}var H=B.indexOf(J,O),D=B.indexOf(X,O),k=new RegExp(J0(h)+J0(F),"g"),P=B.indexOf(F,O);for(;;){if(B[O]===F){P=O,O++;for(;;){if(P=B.indexOf(F,P+1),P===-1){if(!P0)s.push({type:"Quotes",code:"MissingQuotes",message:"Quoted field unterminated",row:u.length,index:O});return z0()}if(P===A-1){var y=B.substring(O,P).replace(k,F);return z0(y)}if(F===h&&B[P+1]===h){P++;continue}if(F!==h&&P!==0&&B[P-1]===h)continue;if(H!==-1&&H<P+1)H=B.indexOf(J,P+1);if(D!==-1&&D<P+1)D=B.indexOf(X,P+1);var c=D===-1?H:Math.min(H,D),w=L0(c);if(B.substr(P+1+w,R)===J){if(q.push(B.substring(O,P).replace(k,F)),O=P+1+w+R,B[P+1+w+R]!==F)P=B.indexOf(F,O);H=B.indexOf(J,O),D=B.indexOf(X,O);break}var K0=L0(D);if(B.substring(P+1+K0,P+1+K0+b)===X){if(q.push(B.substring(O,P).replace(k,F)),F0(P+1+K0+b),H=B.indexOf(J,O),P=B.indexOf(F,O),g){if(U0(),r)return d()}if(L&&u.length>=L)return d(!0);break}s.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:u.length,index:O}),P++;continue}continue}if(M&&q.length===0&&B.substring(O,O+p)===M){if(D===-1)return d();O=D+b,D=B.indexOf(X,O),H=B.indexOf(J,O);continue}if(H!==-1&&(H<D||D===-1)){q.push(B.substring(O,H)),O=H+R,H=B.indexOf(J,O);continue}if(D!==-1){if(q.push(B.substring(O,D)),F0(D+b),g){if(U0(),r)return d()}if(L&&u.length>=L)return d(!0);continue}break}return z0();function M0(l){u.push(l),G0=O}function L0(l){var o=0;if(l!==-1){var Q0=B.substring(P+1,l);if(Q0&&Q0.trim()==="")o=Q0.length}return o}function z0(l){if(P0)return d();if(typeof l>"u")l=B.substring(O);if(q.push(l),O=A,M0(q),g)U0();return d()}function F0(l){O=l,M0(q),q=[],D=B.indexOf(X,O)}function d(l){if(Y.header&&!j&&u.length&&!x){let o=u[0],Q0=Object.create(null),f0=new Set(o),a0=!1;for(let I0=0;I0<o.length;I0++){let V0=e(o[I0]);if(S(Y.transformHeader))V0=Y.transformHeader(V0,I0);if(!Q0[V0])Q0[V0]=1,o[I0]=V0;else{let E0,t0=Q0[V0];do E0=`${V0}_${t0}`,t0++;while(f0.has(E0));if(f0.add(E0),o[I0]=E0,Q0[V0]++,a0=!0,E===null)E={};E[E0]=V0}f0.add(V0)}if(a0)console.warn("Duplicate headers found and renamed.");x=!0}return{data:u,errors:s,meta:{delimiter:J,linebreak:X,aborted:r,truncated:!!l,cursor:G0+(j||0),renamedHeaders:E}}}function U0(){Q(d()),u=[],s=[]}},this.abort=function(){r=!0},this.getCharIndex=function(){return O}}function D0(){if(!G.WORKERS_SUPPORTED)return!1;var Y=U(),J=new $.Worker(Y);return J.onmessage=k0,J.id=I++,_[J.id]=J,J}function k0(Y){var J=Y.data,X=_[J.workerId],M=!1;if(J.error)X.userError(J.error,J.file);else if(J.results&&J.results.data){var Q=function(){M=!0,r0(J.workerId,{data:[],errors:[],meta:{aborted:!0}})},L={abort:Q,pause:o0,resume:o0};if(S(X.userStep)){for(var K=0;K<J.results.data.length;K++)if(X.userStep({data:J.results.data[K],errors:J.results.errors,meta:J.results.meta},L),M)break;delete J.results}else if(S(X.userChunk))X.userChunk(J.results,L,J.file),delete J.results}if(J.finished&&!M)r0(J.workerId,J.results)}function r0(Y,J){var X=_[Y];if(S(X.userComplete))X.userComplete(J);X.terminate(),delete _[Y]}function o0(){throw Error("Not implemented.")}function j2(Y){var J=Y.data;if(typeof G.WORKER_ID>"u"&&J)G.WORKER_ID=J.workerId;if(typeof J.input==="string")$.postMessage({workerId:G.WORKER_ID,results:G.parse(J.input,J.config),finished:!0});else if($.File&&J.input instanceof File||J.input instanceof Object){var X=G.parse(J.input,J.config);if(X)$.postMessage({workerId:G.WORKER_ID,results:X,finished:!0})}}function N0(Y){if(typeof Y!=="object"||Y===null)return Y;var J=Array.isArray(Y)?[]:{};for(var X in Y)J[X]=N0(Y[X]);return J}function n(Y,J){return function(){Y.apply(J,arguments)}}function S(Y){return typeof Y==="function"}return G})});var I$="https://jqjkhlrgstlixasyqrbk.supabase.co/functions/v1/api";class b0 extends Error{code;status;constructor(Z,$,U){super($);this.name="EmbdApiError",this.code=Z,this.status=U}}var D2="https://www.embd.sh/login?next=%2Faccount&ref=mcp";function s0(Z){if(Z instanceof b0)switch(Z.code){case"invalid_key":return`embd rejected the API key. Check that EMBD_API_KEY is set to a valid, non-revoked key (starts with "embd_sk_") from your embd account settings at ${D2}.`;case"publish_cap":return`${Z.message} You can delete an existing published chart, create this one as a draft (publish: false), or upgrade to embd Pro for unlimited published charts.`;case"save_cap":return`${Z.message} You can delete existing charts (delete_chart) or upgrade to embd Pro for unlimited saved charts.`;case"pro_required":return`${Z.message} This option requires an embd Pro plan.`;case"invalid_request":return`The embd API rejected the request: ${Z.message}`;case"not_found":return`Not found: ${Z.message}`;default:return Z.message}if(Z instanceof Error)return`Could not reach the embd API: ${Z.message}`;return`Could not reach the embd API: ${String(Z)}`}class L2{apiKey;apiUrl;constructor(Z){this.apiKey=Z.apiKey,this.apiUrl=(Z.apiUrl??"https://jqjkhlrgstlixasyqrbk.supabase.co/functions/v1/api").replace(/\/+$/,"")}async createChart(Z){return this.request("POST","/charts",Z)}async createDoc(Z){return this.request("POST","/docs",Z)}async listCharts(){return(await this.request("GET","/charts")).charts}async deleteChart(Z){await this.request("DELETE",`/charts/${encodeURIComponent(Z)}`)}async request(Z,$,U){let V=await fetch(`${this.apiUrl}${$}`,{method:Z,headers:{Authorization:`Bearer ${this.apiKey}`,...U!==void 0?{"Content-Type":"application/json"}:{}},...U!==void 0?{body:JSON.stringify(U)}:{}});if(!V.ok)throw await E2(V);if(V.status===204)return;return await V.json()}}async function E2(Z){let $="http_error",U=`embd API responded with HTTP ${Z.status}`;try{let V=await Z.json();if(V?.error?.code)$=V.error.code;if(V?.error?.message)U=V.error.message}catch{}return new b0($,U,Z.status)}function A2(){return crypto.randomUUID().slice(0,8)}var T2={kind:"line",encodings:{x:"",y:[]},options:{showLegend:!0}};function e0(Z,$="light"){let U=Z.columns.filter((_)=>_.type==="number").map((_)=>_.name),V=Z.columns.find((_)=>_.type!=="number")?.name??Z.columns[0]?.name??"",W=U.length>0?[U[0]]:[];return{id:A2(),type:"chart",chart:{...T2,encodings:{x:V,y:W}},themeId:$}}var U2=C2($2(),1);function O0(Z){if(Z==null)return null;let $=String(Z).trim();if($==="")return null;let U=!1;if(/^\(.*\)$/.test($))U=!0,$=$.slice(1,-1);if($.endsWith("%"))$=$.slice(0,-1);if($=$.replace(/[$€£¥]/g,"").replace(/,/g,"").replace(/\s/g,""),$.startsWith("+"))$=$.slice(1);if($.startsWith("-"))U=!U,$=$.slice(1);if(!/^\d*\.?\d+$/.test($))return null;let V=Number($);if(Number.isNaN(V))return null;return U?-V:V}var Z2=new Set(["true","yes","y"]),Y2=new Set(["false","no","n"]),q2=[{re:/^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2})?(\.\d+)?(Z|[+-]\d{2}:?\d{2})?)?$/,format:"ISO-8601"},{re:/^\d{1,2}\/\d{1,2}\/\d{4}$/,format:"MM/DD/YYYY"},{re:/^\d{4}\/\d{1,2}\/\d{1,2}$/,format:"YYYY/MM/DD"}];function S2(Z){return Z.map(($)=>$==null?"":String($).trim()).filter(($)=>$!=="")}function _0(Z){let $=S2(Z);if($.length===0)return{type:"string"};for(let{re:V,format:W}of q2)if($.every((_)=>V.test(_)))return{type:"date",format:W};if($.every((V)=>O0(V)!==null))return{type:"number"};if($.map((V)=>V.toLowerCase()).every((V)=>Z2.has(V)||Y2.has(V)))return{type:"boolean"};return{type:"string"}}function A0(Z,$){let U=Z==null?"":String(Z).trim();if(U==="")return null;switch($){case"number":return O0(U);case"boolean":{let V=U.toLowerCase();if(Z2.has(V))return!0;if(Y2.has(V))return!1;return null}case"date":return U;case"string":default:return U}}function J2(Z){let $=new Map;return Z.map((U)=>{let V=U.trim()||"column",W=$.get(V)??0;return $.set(V,W+1),W===0?V:`${V}_${W+1}`})}function B0(Z){return{dataset:{columns:[],rows:[]},detected:{format:Z},issues:[]}}function y2(Z){if(Z.length===0)return!1;let $=Z[0];if($.length===0)return!1;return $.every((U)=>U.trim()!==""&&O0(U)===null)}function R0(Z,$={}){let U=[],V=Z.trim();if(V==="")return B0("csv");let W=U2.parse(V,{delimiter:$.delimiter??"",skipEmptyLines:"greedy"});for(let N of W.errors)U.push({message:N.message,severity:N.type==="Quotes"?"data-loss":"warning"});let _=$.delimiter??W.meta.delimiter??",",I=W.data.filter((N)=>N.length>0);if(I.length===0)return{...B0("csv"),detected:{format:"csv",delimiter:_,hasHeader:!1}};let G=$.hasHeader??y2(I),f,e;if(G)f=I[0],e=I.slice(1);else f=I[0].map((N,i)=>`column_${i+1}`),e=I;if($.columnNames)f=f.map((N,i)=>$.columnNames?.[i]??N);f=J2(f);let Y0=f.length,v=0,T=0,m=[],a=e.map((N,i)=>{if(N.length<Y0)return v++,[...N,...Array(Y0-N.length).fill("")];if(N.length>Y0){if(T++,m.length<3)m.push(i+(G?2:1));return N.slice(0,Y0)}return N});if(v>0)U.push({message:`${v} row(s) had fewer than ${Y0} columns and were padded with empty values.`,severity:"warning"});if(T>0){let N=m.join(", "),i=T>m.length?", …":"";U.push({message:`${T} row(s) had more than ${Y0} columns (line ${N}${i}). The extra values were dropped and the remaining ones shifted left, so this data is probably wrong. A common cause is an unquoted comma inside a value, `+'such as $1,200.00 — quote those fields ("$1,200.00") and re-run.',severity:"data-loss"})}let t=f.map((N,i)=>{let J0=a.map((k0)=>k0[i]),W0=_0(J0),D0=$.columnTypes?.[N]??W0.type;return D0==="date"?{name:N,type:D0,format:W0.format}:{name:N,type:D0}}),$0=a.map((N)=>{let i={};return t.forEach((J0,W0)=>{i[J0.name]=A0(N[W0],J0.type)}),i});return{dataset:{columns:t,rows:$0},detected:{format:"csv",delimiter:_,hasHeader:G},issues:U}}function q0(Z){return Z!==null&&typeof Z==="object"&&!Array.isArray(Z)}function x2(Z){if(!q0(Z))return!1;let $=Object.values(Z);return $.length>0&&$.every((U)=>Array.isArray(U))}function k2(Z){let $=Object.keys(Z),U=Math.max(...$.map((W)=>Z[W].length)),V=[];for(let W=0;W<U;W++){let _={};for(let I of $)_[I]=Z[I][W]??null;V.push(_)}return V}function f2(Z){return Z.map(($)=>q0($)?$:{value:$})}function b2(Z){let $=Z.split(/\r?\n/).map((V)=>V.trim()).filter((V)=>V!=="");if($.length===0)return null;let U=[];for(let V of $)try{let W=JSON.parse(V);U.push(q0(W)?W:{value:W})}catch{return null}return U}function V2(Z,$,U,V){if(Z.length===0)return{...B0($),detected:{format:$},issues:V};let W=[],_=new Set;for(let v of Z)for(let T of Object.keys(v))if(!_.has(T))_.add(T),W.push(T);let I=[],G=W.filter((v)=>{let T=Z.some((m)=>m[v]!==null&&typeof m[v]==="object");if(T)I.push(v);return!T});if(I.length>0)V.push({message:`Skipped nested field(s): ${I.join(", ")}. Nested data isn't supported yet.`});let f=U.columnNames?G.map((v,T)=>U.columnNames?.[T]??v):G,e=G.map((v,T)=>{let m=f[T],a=Z.map((N)=>N[v]),t=_0(a),$0=U.columnTypes?.[m]??t.type;return $0==="date"?{name:m,type:$0,format:t.format}:{name:m,type:$0}}),Y0=Z.map((v)=>{let T={};return G.forEach((m,a)=>{T[e[a].name]=A0(v[m],e[a].type)}),T});return{dataset:{columns:e,rows:Y0},detected:{format:$},issues:V}}function w0(Z,$={}){let U=Z.trim();if(U==="")return B0("json");let V;try{V=JSON.parse(U)}catch{let _=b2(U);if(!_)return{...B0("json"),issues:[{message:"Could not parse input as JSON."}]};return V2(_,"ndjson",$,[])}let W;if(Array.isArray(V))W=f2(V);else if(x2(V))W=k2(V);else if(q0(V))W=[V];else W=[{value:V}];return V2(W,"json",$,[])}function X2(Z){return/-/.test(Z)&&/^[\s|:-]+$/.test(Z)}function m0(Z){let $=Z.trim().split(/\r?\n/).map((U)=>U.trim()).filter(Boolean);return $.length>=2&&$[0].includes("|")&&X2($[1])}function h2(Z){let $=Z.trim();if($.startsWith("|"))$=$.slice(1);if($.endsWith("|"))$=$.slice(0,-1);return $.split(/(?<!\\)\|/).map((U)=>U.replace(/\\\|/g,"|").trim())}function g2(Z){return/[",\n]/.test(Z)?`"${Z.replace(/"/g,'""')}"`:Z}function v0(Z){let $=Z.trim().split(/\r?\n/).map((W)=>W.trim()).filter(Boolean),U=$[0],V=$.slice(1).filter((W)=>!X2(W));return[U,...V].map((W)=>h2(W).map(g2).join(",")).join(`
|
|
11
|
+
`)}function W2(Z){let $=Z.trim();if($==="")return"csv";if($.startsWith("["))return"json";if($.startsWith("{"))try{return JSON.parse($),"json"}catch{let U=$.split(/\r?\n/).map((V)=>V.trim()).filter(Boolean);if(U.length>1&&U.every((V)=>V.startsWith("{")))return"ndjson";return"json"}return"csv"}function S0(Z,$={}){if(!$.format&&m0(Z))return R0(v0(Z),$);if(($.format??W2(Z))==="csv")return R0(Z,$);return w0(Z,$)}async function w2(Z,$){let U=Z.writable.getWriter(),V=U.write($).then(()=>U.close()).catch(()=>{}),W=new Uint8Array(await new Response(Z.readable).arrayBuffer());return await V,W}async function m2(Z){return w2(new CompressionStream("gzip"),Z)}function v2(Z){let $="";for(let U of Z)$+=String.fromCharCode(U);return btoa($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function X0(Z){let $=new TextEncoder().encode(JSON.stringify(Z));return v2(await m2($))}function p0(Z){let $=Z.dataset;if(!$||$.columns.length===0)return Z;let U=$.columns,V=U.map((_)=>$.rows.map((I)=>I[_.name]??null)),W={v:1,c:U,d:V,b:Z.blocks};if(Z.datasetRef!==void 0)W.r=Z.datasetRef;if(Z.source!==void 0)W.s=Z.source;return W}var C0=8000;async function c0(Z){return X0(p0(Z))}function H0(Z,$,U){let V=U?.edit?"?edit=1":"";return`/playground/${Z}${V}#${$}`}async function l0(Z){return X0(Z)}async function d0(Z){return X0(Z)}async function i0(Z){return X0(Z)}var r2="https://embd.sh",o2="aurora-dark";function y0(Z,$){return`${(Z??r2).replace(/\/+$/,"")}${$}`}async function a2(Z,$={}){let U=typeof Z==="string"?Z:JSON.stringify(Z),{dataset:V}=S0(U);if(V.columns.length===0)throw Error("chartUrl: could not parse any columns from the data");let W=e0(V,$.themeId??o2);if($.kind)W.chart={...W.chart,kind:$.kind};if($.title!==void 0)W.chart={...W.chart,options:{...W.chart.options,title:$.title}};let I=await c0({dataset:V,blocks:[W]});if(!$.allowOversized&&I.length>C0)throw Error(`chartUrl: encoded payload is ${I.length} chars, over the ${C0}-char share limit. Reduce the data, or pass { allowOversized: true } and host it instead.`);return y0($.origin,H0("chart",I,{edit:$.edit}))}async function t2(Z,$={}){let U=await l0({kind:"markdown",source:Z,theme:$.theme});return y0($.origin,H0("markdown",U,{edit:$.edit}))}async function s2(Z,$={}){let U=await d0({kind:"kpi",...Z,theme:Z.theme??$.theme});return y0($.origin,H0("kpi",U,{edit:$.edit}))}async function e2(Z,$={}){let U=await i0({kind:"qr",...Z,theme:Z.theme??$.theme});return y0($.origin,H0("qr",U,{edit:$.edit}))}var M2={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://embd.sh/schema/chart-spec.schema.json",title:"embd chart spec",description:"The chart configuration inside an embd embed. A share link is { dataset, source?, blocks: [{ id, type: 'chart', chart: <this>, themeId }] } encoded into the URL; most agents should prefer chartUrl(data) and never hand-write this. The optional envelope-level `source` (see $defs/source) attaches a live data URL that the viewer refetches on load (CONNECTED-DATA, ADR-0012) — it is a sibling of `dataset`/`blocks`, NOT a field of this chart spec.",type:"object",required:["kind","encodings","options"],additionalProperties:!1,$defs:{source:{type:"object",description:"CONNECTED-DATA live source, carried at the AppState envelope level beside `dataset` (ADR-0012). The inline `dataset` snapshot is still mandatory; on view the viewer refetches this URL and swaps fresh data in when its shape still matches. Mutually exclusive with `datasetRef`.",required:["url"],additionalProperties:!1,properties:{url:{type:"string",description:"PUBLIC https URL with no embedded credentials. Fetched uncredentialed (no cookies, no auth, no custom headers)."},format:{enum:["csv","json"],description:"Force the parser; omit to format-sniff the fetched bytes."}}}},properties:{kind:{description:"Chart type.",enum:["line","area","bar","stacked-bar","stacked-area","bar-horizontal","scatter","pie","donut","heatmap","radar"]},encodings:{type:"object",description:"Which dataset columns map to which visual roles.",required:["x","y"],additionalProperties:!1,properties:{x:{type:"string",description:"Column mapped to the X axis (category/time)."},y:{type:"array",items:{type:"string"},description:"One or more numeric columns, one series each."},series:{type:"string",description:"Optional column whose distinct values split the data into series."},facet:{type:"string",description:"Optional column whose distinct values fan out into a grid of subplots."}}},options:{type:"object",description:"Visual customization. All fields optional.",additionalProperties:!1,properties:{title:{type:"string"},showLegend:{type:"boolean"},smooth:{type:"boolean",description:"Line/area smoothing."},showDataZoom:{type:"boolean",description:"Show a zoom slider for dense data."},xAxisLabel:{type:"string"},yAxisLabel:{type:"string"},colors:{type:"array",items:{type:"string"},description:"Palette override (hex strings)."},seriesColors:{type:"object",additionalProperties:{type:"string"},description:"Per-series color overrides, keyed by series name."},background:{description:"Chart background: a CSS color string, or a serializable linear gradient.",oneOf:[{type:"string"},{type:"object",required:["type","colorStops"],additionalProperties:!1,properties:{type:{const:"linear"},x:{type:"number"},y:{type:"number"},x2:{type:"number"},y2:{type:"number"},colorStops:{type:"array",items:{type:"object",required:["offset","color"],properties:{offset:{type:"number",minimum:0,maximum:1},color:{type:"string"}}}}}}]}}}}};var F2=M2.properties.kind.enum;var Z$=/^\s*(?:application\/(?:ld\+)?json|text\/(?:template|x-template|html|plain))\s*$/i,Y$=/\son(?:abort|animation(?:end|iteration|start)|blur|canplay|change|click|contextmenu|copy|cut|dblclick|drag\w*|drop|durationchange|ended|error|focus(?:in|out)?|hashchange|input|invalid|key(?:down|press|up)|load(?:eddata|edmetadata|start)?|message|mouse\w+|paste|play(?:ing)?|pointer\w+|progress|ratechange|reset|resize|scroll|seek\w+|select|submit|suspend|timeupdate|toggle|touch\w+|transitionend|volumechange|waiting|wheel)\s*=/i,J$=/<script\b([^>]*)>/i,U$=/\btype\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i,V$=/\b(?:href|src|action|formaction)\s*=\s*(?:"|')?\s*javascript:/i,X$=/<form\b/i,W$=/\btarget\s*=\s*(?:"_blank"|'_blank'|_blank\b)/i,G$=/\bwindow\s*\.\s*open\s*\(/i;function M$(Z){return Z.replace(/<!--[\s\S]*?-->/g,($)=>$.replace(/[^\n]/g," "))}function F$(Z,$){let U=1;for(let V=0;V<$;V++)if(Z.charCodeAt(V)===10)U++;return U}function Q$(Z,$,U){let V=Z.slice($,$+80).split(`
|
|
12
|
+
`)[0],W=V.indexOf(">"),_=W>=0&&W+1>=U?W+1:Math.max(U,24),I=V.slice(0,_).trim();return I.length>60?`${I.slice(0,57)}…`:I}function P$(Z){let $=U$.exec(Z);if(!$)return!0;let U=$[1]??$[2]??$[3]??"";return!Z$.test(U)}function Q2(Z){let $=M$(Z),U=new Map,V=(I,G,f)=>{if(U.has(I))return;U.set(I,{feature:I,line:F$($,G),excerpt:Q$($,G,f)})},W=new RegExp(J$.source,"gi");for(let I=W.exec($);I;I=W.exec($))if(P$(I[1]??"")){V("script",I.index,I[0].length);break}let _=[["inline-handler",Y$],["javascript-url",V$],["form",X$]];for(let[I,G]of _){let f=G.exec($);if(f)V(I,f.index,f[0].length)}for(let I of[W$,G$]){let G=I.exec($);if(G)V("popup",G.index,G[0].length)}return[...U.values()].sort((I,G)=>I.line-G.line)}var K$={script:"scripts do not run","inline-handler":"inline event handlers never fire","javascript-url":"javascript: URLs do nothing",form:"forms cannot submit",popup:"links cannot open a new tab or window"};function P2(Z){if(Z.length===0)return null;return["Hosted HTML renders in a sandbox with no JavaScript, so parts of this page will not work:",...Z.map((U)=>` line ${U.line}: ${K$[U.feature]} — ${U.excerpt}`),"","Layout, CSS (including animations), images, fonts and inline SVG all render normally.","Rewrite anything interactive as static markup, or pre-render it — an embd chart can be","embedded as inline SVG."].join(`
|
|
13
|
+
`)}function n0(Z){return P2(Q2(Z))}function T0(Z){return{content:[{type:"text",text:Z}]}}function x0(Z){return{content:[{type:"text",text:s0(Z)}],isError:!0}}async function K2(Z,$){try{let U=await Z.createChart($),V=U.status==="draft"?"The chart was saved as a draft and is not publicly visible yet.":"The chart is published — anyone with the URL can view it.",W=[`Created chart "${U.title||"Untitled"}" (${U.kind}, ${U.status}).`,"",`Chart id: ${U.id}`,`Hosted URL: ${U.url}`,`Embed URL: ${U.embedUrl}`,"","Iframe embed snippet:",U.iframe,"",V].join(`
|
|
14
|
+
`);return T0(W)}catch(U){return x0(U)}}async function z2(Z,$){try{let U=await Z.createDoc($),V=U.status==="draft"?"The doc was saved as a draft and is not publicly visible yet.":"The doc is published — anyone with the URL can view it.",W=$.format==="html"?n0($.content):null,_=[`Created doc "${U.title||"Untitled"}" (${U.kind}, ${U.status}).`,"",`Doc id: ${U.id}`,`Hosted URL: ${U.url}`,`Embed URL: ${U.embedUrl}`,"","Iframe embed snippet:",U.iframe,"",V,...W?["",W]:[]].join(`
|
|
15
|
+
`);return T0(_)}catch(U){return x0(U)}}async function B2(Z){try{let $=await Z.listCharts();if($.length===0)return T0("No embeds yet. Use the create_chart or create_doc tools to make one.");let U=$.map((V)=>`${V.id} — ${V.kind} — ${V.status} — ${V.title||"Untitled"} — ${V.url}`);return T0(U.join(`
|
|
16
|
+
`))}catch($){return x0($)}}async function H2(Z,$){try{return await Z.deleteChart($),T0(`Deleted chart ${$}. Its hosted page and any embedded iframes will no longer load.`)}catch(U){return x0(U)}}var z$=O2.version,B$="line, area, bar, stacked-bar, stacked-area, bar-horizontal, scatter, pie, donut, heatmap, radar",H$="aurora-dark (default), aurora-light, simple-dark, simple-light, vibrant-dark, vibrant-light, neon-dark, neon-light";function z3(Z){let $=new I2({name:"embd",version:z$});return $.registerTool("create_chart",{title:"Create an embd chart",description:"Turn tabular data into a hosted, shareable, embeddable chart on embd.sh. Use this when you have data (CSV text, query results, rows of records) and the user wants a chart they can link to, share, or embed in a website, Notion page, or README. Pass `data` as raw CSV text (first row must be headers) or as an array of flat JSON row objects "+"that all share the same keys. Column roles are inferred automatically — by default the first "+"non-numeric column becomes the X axis and every numeric column becomes a measure — so `x`, `y`, "+"and `split` are only needed to override that. Returns the hosted chart URL, an iframe embed snippet, and the chart id. The chart is PUBLIC (viewable by anyone with the URL) as soon as it is published, which is the default; pass publish: false to save a private draft instead.",inputSchema:C.object({data:C.union([C.string(),C.array(C.record(C.string(),C.unknown()))]).describe('The tabular data to chart: CSV text (first row = column headers) or an array of flat row objects with identical keys, e.g. [{"month":"Jan","sales":120}, ...].'),kind:C.string().optional().describe(`Chart type: one of ${B$}. Default: line.`),title:C.string().optional().describe("Chart title shown on the hosted page."),x:C.string().optional().describe("Column name for the X axis (category/time). Default: the first non-numeric column, else the first column."),y:C.union([C.string(),C.array(C.string())]).optional().describe("Measure column name(s) for the Y axis. Default: all numeric columns."),split:C.string().optional().describe('Column whose values split the data into one series per value (e.g. a "region" column).'),theme:C.string().optional().describe(`Visual theme id: one of ${H$}.`),publish:C.boolean().optional().describe("Publish immediately (default true). Published charts are publicly viewable by anyone with the URL. Pass false to save a private draft.")})},async(U)=>K2(Z,U)),$.registerTool("create_doc",{title:"Publish an embd doc",description:"Publish HTML or markdown as a hosted, shareable, embeddable page on embd.sh. "+"Use this when the deliverable is a rendered document — a report, write-up, formatted notes, "+"or a self-contained HTML page you have already generated — and the user wants a link they can "+"share or an iframe they can embed in a website, Notion page, or README. Use create_chart instead when you have tabular data that should become a chart; use create_doc when you already have the final HTML or markdown content. IMPORTANT: hosted HTML is rendered in a sandboxed iframe with JavaScript DISABLED. Scripts never run, inline event handlers never fire, and forms cannot submit. Generate self-contained STATIC HTML: layout, CSS (including animations and media "+"queries), images, web fonts and inline SVG all work normally — pre-render anything "+"that would otherwise need JavaScript. Markdown is rendered with a clean, readable default stylesheet. `content` is limited to 100,000 characters. Returns the hosted page URL, an iframe embed snippet, and the doc id. The page is PUBLIC (viewable by anyone with the URL) as soon as it is published, which is the default; pass publish: false to save a private draft instead.",inputSchema:C.object({content:C.string().describe("The document source: raw HTML (a fragment or a full page) or markdown text. Max 100,000 characters."),format:C.enum(["html","markdown"]).describe("How to interpret and render `content`: html or markdown."),title:C.string().optional().describe("Document title shown on the hosted page."),publish:C.boolean().optional().describe("Publish immediately (default true). Published docs are publicly viewable by anyone with the URL. Pass false to save a private draft.")})},async(U)=>z2(Z,U)),$.registerTool("list_charts",{title:"List your embd charts and docs",description:"List every embed owned by the configured embd API key — charts and docs (html/markdown pages) "+'alike — newest first, one per line formatted as "id — kind — status — title — url" (for docs, '+"kind is html or markdown). Use this to recall the URL of a previously created chart or doc, or to find an id before calling delete_chart.",inputSchema:C.object({})},async()=>B2(Z)),$.registerTool("delete_chart",{title:"Delete an embd chart or doc",description:"Permanently delete one of your embd embeds (chart or doc) by id. The hosted page and any "+"iframes embedding it stop working immediately, and this cannot be undone — confirm with the "+"user before deleting. Use list_charts first if you do not know the id.",inputSchema:C.object({id:C.string().describe("The id to delete (from create_chart, create_doc, or list_charts).")})},async({id:U})=>H2(Z,U)),$}
|
|
17
|
+
export{I$ as l,b0 as m,D2 as n,s0 as o,L2 as p,a2 as q,t2 as r,s2 as s,e2 as t,K2 as u,z2 as v,B2 as w,H2 as x,z$ as y,z3 as z};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import{q as o,r,s as e,t as ZZ,y as $Z}from"./bin-5b95b3jx.js";import{D as G,E as MZ,F as C,G as z,H as v,I as S,J as c,K as l,L as s}from"./bin-2pd22980.js";var VZ=["line","area","bar","stacked-bar","stacked-area","bar-horizontal","scatter","pie","donut","heatmap","radar"],E=["stage","slate","dusk","paper","mist","sepia"];function H(Z,$){return{content:[{type:"text",text:Z}],structuredContent:{url:Z,kind:$}}}function k(Z){return{content:[{type:"text",text:Z instanceof Error?Z.message:String(Z)}],isError:!0}}async function LZ(Z,$={}){try{let Q=await o(Z.data,{origin:$.origin,kind:Z.kind,title:Z.title,themeId:Z.theme});return H(Q,"chart")}catch(Q){return k(Q)}}async function UZ(Z,$={}){try{let Q=await r(Z.content,{origin:$.origin,theme:Z.theme});return H(Q,"markdown")}catch(Q){return k(Q)}}async function fZ(Z,$={}){try{let Q=await e(Z,{origin:$.origin});return H(Q,"kpi")}catch(Q){return k(Q)}}async function AZ(Z,$={}){try{let Q=await ZZ(Z,{origin:$.origin});return H(Q,"qr")}catch(Q){return k(Q)}}var O={readOnlyHint:!0,destructiveHint:!1,openWorldHint:!1},_Z=["create_kpi"];function QZ(Z={}){let $=new s({name:"embd",version:$Z});if($.registerTool("create_chart",{title:"Create a shareable embd chart link",description:"Turn tabular data into a beautiful, shareable chart and return a self-contained embd.sh URL. "+"No account, no upload, no API call — the chart data is encoded directly into the returned link, "+"so it works anywhere and needs no backend. Use this when you have data (CSV text or an array of flat JSON row objects) and the user wants a chart they can link to, share, or embed. "+"Column roles are inferred automatically (first non-numeric column → X axis, numeric columns → "+"series). Because the data rides in the URL, there is a size limit — if the data is too large the "+"tool returns an error asking you to reduce it; very large datasets need the hosted embd server instead.",inputSchema:G.object({data:G.union([G.string(),G.array(G.record(G.string(),G.unknown()))]).describe('CSV text (first row = headers) or an array of flat row objects with identical keys, e.g. [{"month":"Jan","sales":120}, ...].'),kind:G.enum(VZ).optional().describe("Chart type. Default: inferred from the data (usually line or bar)."),title:G.string().optional().describe("Chart title."),theme:G.string().optional().describe("Theme id (e.g. aurora-dark, aurora-light). Default: aurora-dark.")}),annotations:O},async(Q)=>LZ(Q,Z)),$.registerTool("create_doc",{title:"Create a shareable embd markdown doc link",description:"Render Markdown into a clean, shareable page and return a self-contained embd.sh URL. "+"No account and no upload — the Markdown source is encoded into the link. Use this for a report, "+"write-up, or formatted notes the user wants to share as a link. Markdown only (HTML documents require the hosted embd server). Large documents may exceed the URL size limit and return an error.",inputSchema:G.object({content:G.string().describe("The Markdown source text."),theme:G.enum(E).optional().describe("Reading theme. Default: stage.")}),annotations:O},async(Q)=>UZ(Q,Z)),!_Z.includes("create_kpi"))$.registerTool("create_kpi",{title:"Create a shareable embd KPI/stat link",description:"Build a big-number KPI card (value + label, optional change indicator, caption and sparkline) and "+"return a self-contained embd.sh URL. No account or upload — the card is encoded into the link. "+'Values are pre-formatted strings (you format them, e.g. "$1.2M", "98%").',inputSchema:G.object({value:G.string().describe('The big value, pre-formatted (e.g. "$1.2M", "98%").'),label:G.string().describe('What it measures (e.g. "Monthly revenue").'),caption:G.string().optional().describe("Optional sub-line (context or timeframe)."),delta:G.object({value:G.string().describe('Displayed change, e.g. "12%" or "340".'),dir:G.enum(["up","down","flat"]).describe("Arrow direction."),good:G.boolean().optional().describe("Whether this direction reads as positive (drives color). Default: up=good.")}).optional().describe("Optional change indicator."),sparkline:G.array(G.number()).optional().describe("Optional trend series (numbers) drawn behind the value."),theme:G.enum(E).optional().describe("Reading theme. Default: stage.")}),annotations:O},async(Q)=>fZ(Q,Z));return $.registerTool("create_qr",{title:"Create a shareable embd QR-code link",description:"Generate a styled QR code for a URL or text and return a self-contained embd.sh URL that renders it. No account or upload. Supports an optional heading, caption, foreground/background hex colors, and a small center emoji icon.",inputSchema:G.object({content:G.string().describe("What the QR encodes (a URL, text, …)."),label:G.string().optional().describe("Optional heading above the code."),caption:G.string().optional().describe("Optional sub-line below it."),fg:G.string().optional().describe("Module (foreground) color as a 6-digit hex."),bg:G.string().optional().describe("Background color as a 6-digit hex."),icon:G.string().optional().describe("A small center emoji icon."),theme:G.enum(E).optional().describe("Reading theme. Default: stage.")}),annotations:O},async(Q)=>AZ(Q,Z)),$}import{createServer as hZ}from"node:http";import{Http2ServerRequest as YZ,constants as DZ}from"http2";import{Http2ServerRequest as I}from"http2";import{Readable as WZ}from"stream";import vZ from"crypto";var V=class extends Error{constructor(Z,$){super(Z,$);this.name="RequestError"}},NZ=(Z)=>{if(Z instanceof V)return Z;return new V(Z.message,{cause:Z})},TZ=global.Request,N=class extends TZ{constructor(Z,$){if(typeof Z==="object"&&_ in Z)Z=Z[_]();if(typeof $?.body?.getReader<"u")$.duplex??="half";super(Z,$)}},zZ=(Z)=>{let $=[],Q=Z.rawHeaders;for(let W=0;W<Q.length;W+=2){let{[W]:X,[W+1]:Y}=Q;if(X.charCodeAt(0)!==58)$.push([X,Y])}return new Headers($)},jZ=Symbol("wrapBodyStream"),PZ=(Z,$,Q,W,X)=>{let Y={method:Z,headers:Q,signal:X.signal};if(Z==="TRACE"){Y.method="GET";let j=new N($,Y);return Object.defineProperty(j,"method",{get(){return"TRACE"}}),j}if(!(Z==="GET"||Z==="HEAD"))if("rawBody"in W&&W.rawBody instanceof Buffer)Y.body=new ReadableStream({start(j){j.enqueue(W.rawBody),j.close()}});else if(W[jZ]){let j;Y.body=new ReadableStream({async pull(x){try{j||=WZ.toWeb(W).getReader();let{done:B,value:K}=await j.read();if(B)x.close();else x.enqueue(K)}catch(B){x.error(B)}}})}else Y.body=WZ.toWeb(W);return new N($,Y)},_=Symbol("getRequestCache"),xZ=Symbol("requestCache"),w=Symbol("incomingKey"),y=Symbol("urlKey"),OZ=Symbol("headersKey"),A=Symbol("abortControllerKey"),HZ=Symbol("getAbortController"),T={get method(){return this[w].method||"GET"},get url(){return this[y]},get headers(){return this[OZ]||=zZ(this[w])},[HZ](){return this[_](),this[A]},[_](){return this[A]||=new AbortController,this[xZ]||=PZ(this.method,this[y],this.headers,this[w],this[A])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach((Z)=>{Object.defineProperty(T,Z,{get(){return this[_]()[Z]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach((Z)=>{Object.defineProperty(T,Z,{value:function(){return this[_]()[Z]()}})});Object.defineProperty(T,Symbol.for("nodejs.util.inspect.custom"),{value:function(Z,$,Q){let W={method:this.method,url:this.url,headers:this.headers,nativeRequest:this[xZ]};return`Request (lightweight) ${Q(W,{...$,depth:Z==null?null:Z-1})}`}});Object.setPrototypeOf(T,N.prototype);var kZ=(Z,$)=>{let Q=Object.create(T);Q[w]=Z;let W=Z.url||"";if(W[0]!=="/"&&(W.startsWith("http://")||W.startsWith("https://"))){if(Z instanceof I)throw new V("Absolute URL for :path is not allowed in HTTP/2");try{let x=new URL(W);Q[y]=x.href}catch(x){throw new V("Invalid absolute URL",{cause:x})}return Q}let X=(Z instanceof I?Z.authority:Z.headers.host)||$;if(!X)throw new V("Missing host header");let Y;if(Z instanceof I){if(Y=Z.scheme,!(Y==="http"||Y==="https"))throw new V("Unsupported scheme")}else Y=Z.socket&&Z.socket.encrypted?"https":"http";let j=new URL(`${Y}://${X}${W}`);if(j.hostname.length!==X.length&&j.hostname!==X.replace(/:\d+$/,""))throw new V("Invalid host header");return Q[y]=j.href,Q},R=Symbol("responseCache"),f=Symbol("getResponseCache"),L=Symbol("cache"),p=global.Response,D=class Z{#$;#Z;[f](){return delete this[L],this[R]||=new p(this.#$,this.#Z)}constructor($,Q){let W;if(this.#$=$,Q instanceof Z){let X=Q[R];if(X){this.#Z=X,this[f]();return}else this.#Z=Q.#Z,W=new Headers(Q.#Z.headers)}else this.#Z=Q;if(typeof $==="string"||typeof $?.getReader<"u"||$ instanceof Blob||$ instanceof Uint8Array)this[L]=[Q?.status||200,$,W||Q?.headers]}get headers(){let $=this[L];if($){if(!($[2]instanceof Headers))$[2]=new Headers($[2]||{"content-type":"text/plain; charset=UTF-8"});return $[2]}return this[f]().headers}get status(){return this[L]?.[0]??this[f]().status}get ok(){let $=this.status;return $>=200&&$<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach((Z)=>{Object.defineProperty(D.prototype,Z,{get(){return this[f]()[Z]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach((Z)=>{Object.defineProperty(D.prototype,Z,{value:function(){return this[f]()[Z]()}})});Object.defineProperty(D.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(Z,$,Q){let W={status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[R]};return`Response (lightweight) ${Q(W,{...$,depth:Z==null?null:Z-1})}`}});Object.setPrototypeOf(D,p);Object.setPrototypeOf(D.prototype,p.prototype);async function wZ(Z){return Promise.race([Z,Promise.resolve().then(()=>Promise.resolve(void 0))])}function GZ(Z,$,Q){let W=(x)=>{Z.cancel(x).catch(()=>{})};return $.on("close",W),$.on("error",W),(Q??Z.read()).then(j,X),Z.closed.finally(()=>{$.off("close",W),$.off("error",W)});function X(x){if(x)$.destroy(x)}function Y(){Z.read().then(j,X)}function j({done:x,value:B}){try{if(x)$.end();else if(!$.write(B))$.once("drain",Y);else return Z.read().then(j,X)}catch(K){X(K)}}}function yZ(Z,$){if(Z.locked)throw TypeError("ReadableStream is locked.");else if($.destroyed)return;return GZ(Z.getReader(),$)}var h=(Z)=>{let $={};if(!(Z instanceof Headers))Z=new Headers(Z??void 0);let Q=[];for(let[W,X]of Z)if(W==="set-cookie")Q.push(X);else $[W]=X;if(Q.length>0)$["set-cookie"]=Q;return $["content-type"]??="text/plain; charset=UTF-8",$},CZ="x-hono-already-sent";if(typeof global.crypto>"u")global.crypto=vZ;var u=Symbol("outgoingEnded"),XZ=Symbol("incomingDraining"),SZ=500,EZ=67108864,b=(Z)=>{let $=Z;if(Z.destroyed||$[XZ])return;if($[XZ]=!0,Z instanceof YZ){try{Z.stream?.close?.(DZ.NGHTTP2_NO_ERROR)}catch{}return}let Q=0,W=()=>{clearTimeout(Y),Z.off("data",j),Z.off("end",W),Z.off("error",W)},X=()=>{W();let x=Z.socket;if(x&&!x.destroyed)x.destroySoon()},Y=setTimeout(X,SZ);Y.unref?.();let j=(x)=>{if(Q+=x.length,Q>EZ)X()};Z.on("data",j),Z.on("end",W),Z.on("error",W),Z.resume()},IZ=()=>new Response(null,{status:400}),BZ=(Z)=>new Response(null,{status:Z instanceof Error&&(Z.name==="TimeoutError"||Z.constructor.name==="TimeoutError")?504:500}),q=(Z,$)=>{let Q=Z instanceof Error?Z:Error("unknown error",{cause:Z});if(Q.code==="ERR_STREAM_PREMATURE_CLOSE")console.info("The user aborted a request.");else{if(console.error(Z),!$.headersSent)$.writeHead(500,{"Content-Type":"text/plain"});$.end(`Error: ${Q.message}`),$.destroy(Q)}},KZ=(Z)=>{if("flushHeaders"in Z&&Z.writable)Z.flushHeaders()},FZ=async(Z,$)=>{let[Q,W,X]=Z[L],Y=!1;if(!X)X={"content-type":"text/plain; charset=UTF-8"};else if(X instanceof Headers)Y=X.has("content-length"),X=h(X);else if(Array.isArray(X)){let j=new Headers(X);Y=j.has("content-length"),X=h(j)}else for(let j in X)if(j.length===14&&j.toLowerCase()==="content-length"){Y=!0;break}if(!Y){if(typeof W==="string")X["Content-Length"]=Buffer.byteLength(W);else if(W instanceof Uint8Array)X["Content-Length"]=W.byteLength;else if(W instanceof Blob)X["Content-Length"]=W.size}if($.writeHead(Q,X),typeof W==="string"||W instanceof Uint8Array)$.end(W);else if(W instanceof Blob)$.end(new Uint8Array(await W.arrayBuffer()));else KZ($),await yZ(W,$)?.catch((j)=>q(j,$));$[u]?.()},bZ=(Z)=>typeof Z.then==="function",RZ=async(Z,$,Q={})=>{if(bZ(Z))if(Q.errorHandler)try{Z=await Z}catch(X){let Y=await Q.errorHandler(X);if(!Y)return;Z=Y}else Z=await Z.catch(BZ);if(L in Z)return FZ(Z,$);let W=h(Z.headers);if(Z.body){let X=Z.body.getReader(),Y=[],j=!1,x=void 0;if(W["transfer-encoding"]!=="chunked"){let B=2;for(let K=0;K<B;K++){x||=X.read();let M=await wZ(x).catch((U)=>{console.error(U),j=!0});if(!M){if(K===1){await new Promise((U)=>setTimeout(U)),B=3;continue}break}if(x=void 0,M.value)Y.push(M.value);if(M.done){j=!0;break}}if(j&&!("content-length"in W))W["content-length"]=Y.reduce((K,M)=>K+M.length,0)}if($.writeHead(Z.status,W),Y.forEach((B)=>{$.write(B)}),j)$.end();else{if(Y.length===0)KZ($);await GZ(X,$,x)}}else if(W[CZ]);else $.writeHead(Z.status,W),$.end();$[u]?.()},m=(Z,$={})=>{let Q=$.autoCleanupIncoming??!0;if($.overrideGlobalObjects!==!1&&global.Request!==N)Object.defineProperty(global,"Request",{value:N}),Object.defineProperty(global,"Response",{value:D});return async(W,X)=>{let Y,j;try{j=kZ(W,$.hostname);let x=!Q||W.method==="GET"||W.method==="HEAD";if(!x){if(W[jZ]=!0,W.on("end",()=>{x=!0}),W instanceof YZ)X[u]=()=>{if(!x)setTimeout(()=>{if(!x)setTimeout(()=>{b(W)})})};X.on("finish",()=>{if(!x)b(W)})}if(X.on("close",()=>{if(j[A]){if(W.errored)j[A].abort(W.errored.toString());else if(!X.writableFinished)j[A].abort("Client connection prematurely closed.")}if(!x)setTimeout(()=>{if(!x)setTimeout(()=>{b(W)})})}),Y=Z(j,{incoming:W,outgoing:X}),L in Y)return FZ(Y,X)}catch(x){if(!Y)if($.errorHandler){if(Y=await $.errorHandler(j?x:NZ(x)),!Y)return}else if(!j)Y=IZ();else Y=BZ(x);else return q(x,X)}try{return await RZ(Y,X,$)}catch(x){return q(x,X)}}};class d{constructor(Z={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId="_GET_stream",this.sessionIdGenerator=Z.sessionIdGenerator,this._enableJsonResponse=Z.enableJsonResponse??!1,this._eventStore=Z.eventStore,this._onsessioninitialized=Z.onsessioninitialized,this._onsessionclosed=Z.onsessionclosed,this._allowedHosts=Z.allowedHosts,this._allowedOrigins=Z.allowedOrigins,this._enableDnsRebindingProtection=Z.enableDnsRebindingProtection??!1,this._retryInterval=Z.retryInterval}async start(){if(this._started)throw Error("Transport already started");this._started=!0}createJsonErrorResponse(Z,$,Q,W){let X={code:$,message:Q};if(W?.data!==void 0)X.data=W.data;return new Response(JSON.stringify({jsonrpc:"2.0",error:X,id:null}),{status:Z,headers:{"Content-Type":"application/json",...W?.headers}})}validateRequestHeaders(Z){if(!this._enableDnsRebindingProtection)return;if(this._allowedHosts&&this._allowedHosts.length>0){let $=Z.headers.get("host");if(!$||!this._allowedHosts.includes($)){let Q=`Invalid Host header: ${$}`;return this.onerror?.(Error(Q)),this.createJsonErrorResponse(403,-32000,Q)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let $=Z.headers.get("origin");if($&&!this._allowedOrigins.includes($)){let Q=`Invalid Origin header: ${$}`;return this.onerror?.(Error(Q)),this.createJsonErrorResponse(403,-32000,Q)}}return}async handleRequest(Z,$){if(!this.sessionIdGenerator&&this._hasHandledRequest)throw Error("Stateless transport cannot be reused across requests. Create a new transport per request.");this._hasHandledRequest=!0;let Q=this.validateRequestHeaders(Z);if(Q)return Q;switch(Z.method){case"POST":return this.handlePostRequest(Z,$);case"GET":return this.handleGetRequest(Z);case"DELETE":return this.handleDeleteRequest(Z);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(Z,$,Q,W){if(!this._eventStore)return;if(W<"2025-11-25")return;let X=await this._eventStore.storeEvent(Q,{}),Y=`id: ${X}
|
|
2
|
+
data:
|
|
3
|
+
|
|
4
|
+
`;if(this._retryInterval!==void 0)Y=`id: ${X}
|
|
5
|
+
retry: ${this._retryInterval}
|
|
6
|
+
data:
|
|
7
|
+
|
|
8
|
+
`;Z.enqueue($.encode(Y))}async handleGetRequest(Z){if(!Z.headers.get("accept")?.includes("text/event-stream"))return this.onerror?.(Error("Not Acceptable: Client must accept text/event-stream")),this.createJsonErrorResponse(406,-32000,"Not Acceptable: Client must accept text/event-stream");let Q=this.validateSession(Z);if(Q)return Q;let W=this.validateProtocolVersion(Z);if(W)return W;if(this._eventStore){let B=Z.headers.get("last-event-id");if(B)return this.replayEvents(B)}if(this._streamMapping.get(this._standaloneSseStreamId)!==void 0)return this.onerror?.(Error("Conflict: Only one SSE stream is allowed per session")),this.createJsonErrorResponse(409,-32000,"Conflict: Only one SSE stream is allowed per session");let X=new TextEncoder,Y,j=new ReadableStream({start:(B)=>{Y=B},cancel:()=>{this._streamMapping.delete(this._standaloneSseStreamId)}}),x={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"};if(this.sessionId!==void 0)x["mcp-session-id"]=this.sessionId;return this._streamMapping.set(this._standaloneSseStreamId,{controller:Y,encoder:X,cleanup:()=>{this._streamMapping.delete(this._standaloneSseStreamId);try{Y.close()}catch{}}}),new Response(j,{headers:x})}async replayEvents(Z){if(!this._eventStore)return this.onerror?.(Error("Event store not configured")),this.createJsonErrorResponse(400,-32000,"Event store not configured");try{let $;if(this._eventStore.getStreamIdForEventId){if($=await this._eventStore.getStreamIdForEventId(Z),!$)return this.onerror?.(Error("Invalid event ID format")),this.createJsonErrorResponse(400,-32000,"Invalid event ID format");if(this._streamMapping.get($)!==void 0)return this.onerror?.(Error("Conflict: Stream already has an active connection")),this.createJsonErrorResponse(409,-32000,"Conflict: Stream already has an active connection")}let Q={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"};if(this.sessionId!==void 0)Q["mcp-session-id"]=this.sessionId;let W=new TextEncoder,X,Y=new ReadableStream({start:(x)=>{X=x},cancel:()=>{}}),j=await this._eventStore.replayEventsAfter(Z,{send:async(x,B)=>{if(!this.writeSSEEvent(X,W,B,x)){this.onerror?.(Error("Failed replay events"));try{X.close()}catch{}}}});return this._streamMapping.set(j,{controller:X,encoder:W,cleanup:()=>{this._streamMapping.delete(j);try{X.close()}catch{}}}),new Response(Y,{headers:Q})}catch($){return this.onerror?.($),this.createJsonErrorResponse(500,-32000,"Error replaying events")}}writeSSEEvent(Z,$,Q,W){try{let X=`event: message
|
|
9
|
+
`;if(W)X+=`id: ${W}
|
|
10
|
+
`;return X+=`data: ${JSON.stringify(Q)}
|
|
11
|
+
|
|
12
|
+
`,Z.enqueue($.encode(X)),!0}catch(X){return this.onerror?.(X),!1}}handleUnsupportedRequest(){return this.onerror?.(Error("Method not allowed.")),new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32000,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(Z,$){try{let Q=Z.headers.get("accept");if(!Q?.includes("application/json")||!Q.includes("text/event-stream"))return this.onerror?.(Error("Not Acceptable: Client must accept both application/json and text/event-stream")),this.createJsonErrorResponse(406,-32000,"Not Acceptable: Client must accept both application/json and text/event-stream");let W=Z.headers.get("content-type");if(!W||!W.includes("application/json"))return this.onerror?.(Error("Unsupported Media Type: Content-Type must be application/json")),this.createJsonErrorResponse(415,-32000,"Unsupported Media Type: Content-Type must be application/json");let X={headers:Object.fromEntries(Z.headers.entries()),url:new URL(Z.url)},Y;if($?.parsedBody!==void 0)Y=$.parsedBody;else try{Y=await Z.json()}catch{return this.onerror?.(Error("Parse error: Invalid JSON")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}let j;try{if(Array.isArray(Y))j=Y.map((F)=>c.parse(F));else j=[c.parse(Y)]}catch{return this.onerror?.(Error("Parse error: Invalid JSON-RPC message")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let x=j.some(l);if(x){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(Error("Invalid Request: Server already initialized")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(j.length>1)return this.onerror?.(Error("Invalid Request: Only one initialization request is allowed")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");if(this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized)await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!x){let F=this.validateSession(Z);if(F)return F;let J=this.validateProtocolVersion(Z);if(J)return J}if(!j.some(z)){for(let F of j)this.onmessage?.(F,{authInfo:$?.authInfo,requestInfo:X});return new Response(null,{status:202})}let K=crypto.randomUUID(),M=j.find((F)=>l(F)),U=M?M.params.protocolVersion:Z.headers.get("mcp-protocol-version")??MZ;if(this._enableJsonResponse)return new Promise((F)=>{this._streamMapping.set(K,{resolveJson:F,cleanup:()=>{this._streamMapping.delete(K)}});for(let J of j)if(z(J))this._requestToStreamMapping.set(J.id,K);for(let J of j)this.onmessage?.(J,{authInfo:$?.authInfo,requestInfo:X})});let i=new TextEncoder,P,JZ=new ReadableStream({start:(F)=>{P=F},cancel:()=>{this._streamMapping.delete(K)}}),t={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};if(this.sessionId!==void 0)t["mcp-session-id"]=this.sessionId;for(let F of j)if(z(F))this._streamMapping.set(K,{controller:P,encoder:i,cleanup:()=>{this._streamMapping.delete(K);try{P.close()}catch{}}}),this._requestToStreamMapping.set(F.id,K);await this.writePrimingEvent(P,i,K,U);for(let F of j){let J,n;if(z(F)&&this._eventStore&&U>="2025-11-25")J=()=>{this.closeSSEStream(F.id)},n=()=>{this.closeStandaloneSSEStream()};this.onmessage?.(F,{authInfo:$?.authInfo,requestInfo:X,closeSSEStream:J,closeStandaloneSSEStream:n})}return new Response(JZ,{status:200,headers:t})}catch(Q){return this.onerror?.(Q),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(Q)})}}async handleDeleteRequest(Z){let $=this.validateSession(Z);if($)return $;let Q=this.validateProtocolVersion(Z);if(Q)return Q;return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200})}validateSession(Z){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(Error("Bad Request: Server not initialized")),this.createJsonErrorResponse(400,-32000,"Bad Request: Server not initialized");let $=Z.headers.get("mcp-session-id");if(!$)return this.onerror?.(Error("Bad Request: Mcp-Session-Id header is required")),this.createJsonErrorResponse(400,-32000,"Bad Request: Mcp-Session-Id header is required");if($!==this.sessionId)return this.onerror?.(Error("Session not found")),this.createJsonErrorResponse(404,-32001,"Session not found");return}validateProtocolVersion(Z){let $=Z.headers.get("mcp-protocol-version");if($!==null&&!C.includes($))return this.onerror?.(Error(`Bad Request: Unsupported protocol version: ${$} (supported versions: ${C.join(", ")})`)),this.createJsonErrorResponse(400,-32000,`Bad Request: Unsupported protocol version: ${$} (supported versions: ${C.join(", ")})`);return}async close(){this._streamMapping.forEach(({cleanup:Z})=>{Z()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(Z){let $=this._requestToStreamMapping.get(Z);if(!$)return;let Q=this._streamMapping.get($);if(Q)Q.cleanup()}closeStandaloneSSEStream(){let Z=this._streamMapping.get(this._standaloneSseStreamId);if(Z)Z.cleanup()}async send(Z,$){let Q=$?.relatedRequestId;if(v(Z)||S(Z))Q=Z.id;if(Q===void 0){if(v(Z)||S(Z))throw Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let Y;if(this._eventStore)Y=await this._eventStore.storeEvent(this._standaloneSseStreamId,Z);let j=this._streamMapping.get(this._standaloneSseStreamId);if(j===void 0)return;if(j.controller&&j.encoder)this.writeSSEEvent(j.controller,j.encoder,Z,Y);return}let W=this._requestToStreamMapping.get(Q);if(!W)throw Error(`No connection established for request ID: ${String(Q)}`);let X=this._streamMapping.get(W);if(!this._enableJsonResponse&&X?.controller&&X?.encoder){let Y;if(this._eventStore)Y=await this._eventStore.storeEvent(W,Z);this.writeSSEEvent(X.controller,X.encoder,Z,Y)}if(v(Z)||S(Z)){this._requestResponseMap.set(Q,Z);let Y=Array.from(this._requestToStreamMapping.entries()).filter(([x,B])=>B===W).map(([x])=>x);if(Y.every((x)=>this._requestResponseMap.has(x))){if(!X)throw Error(`No connection established for request ID: ${String(Q)}`);if(this._enableJsonResponse&&X.resolveJson){let x={"Content-Type":"application/json"};if(this.sessionId!==void 0)x["mcp-session-id"]=this.sessionId;let B=Y.map((K)=>this._requestResponseMap.get(K));if(B.length===1)X.resolveJson(new Response(JSON.stringify(B[0]),{status:200,headers:x}));else X.resolveJson(new Response(JSON.stringify(B),{status:200,headers:x}))}else X.cleanup();for(let x of Y)this._requestResponseMap.delete(x),this._requestToStreamMapping.delete(x)}}}}class g{constructor(Z={}){this._requestContext=new WeakMap,this._webStandardTransport=new d(Z),this._requestListener=m(async($)=>{let Q=this._requestContext.get($);return this._webStandardTransport.handleRequest($,{authInfo:Q?.authInfo,parsedBody:Q?.parsedBody})},{overrideGlobalObjects:!1})}get sessionId(){return this._webStandardTransport.sessionId}set onclose(Z){this._webStandardTransport.onclose=Z}get onclose(){return this._webStandardTransport.onclose}set onerror(Z){this._webStandardTransport.onerror=Z}get onerror(){return this._webStandardTransport.onerror}set onmessage(Z){this._webStandardTransport.onmessage=Z}get onmessage(){return this._webStandardTransport.onmessage}async start(){return this._webStandardTransport.start()}async close(){return this._webStandardTransport.close()}async send(Z,$){return this._webStandardTransport.send(Z,$)}async handleRequest(Z,$,Q){let W=Z.auth;await m(async(Y)=>{return this._webStandardTransport.handleRequest(Y,{authInfo:W,parsedBody:Q})},{overrideGlobalObjects:!1})(Z,$)}closeSSEStream(Z){this._webStandardTransport.closeSSEStream(Z)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}}var qZ=4194304,pZ={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Accept, Mcp-Session-Id, Mcp-Protocol-Version","Access-Control-Expose-Headers":"Mcp-Session-Id","Access-Control-Max-Age":"86400"};function uZ(Z){for(let[$,Q]of Object.entries(pZ))Z.setHeader($,Q)}function a(Z,$,Q){let W=JSON.stringify(Q);Z.writeHead($,{"Content-Type":"application/json"}),Z.end(W)}async function mZ(Z){let $=[],Q=0;for await(let W of Z){let X=W;if(Q+=X.byteLength,Q>qZ)throw Error("Request body too large");$.push(X)}if(Q===0)return;return JSON.parse(Buffer.concat($).toString("utf8"))}function cZ(Z={}){let $=Z.mcpPath??"/mcp",Q=Z.allowedHosts?.filter((Y)=>Y.length>0)??[],W=Q.length>0;return(Y,j)=>{X(Y,j).catch((x)=>{if(!j.headersSent)a(j,500,{jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:null});else j.end();console.error("embd MCP HTTP handler error:",x)})};async function X(Y,j){if(uZ(j),Y.method==="OPTIONS"){j.writeHead(204).end();return}let x=new URL(Y.url??"/","http://localhost");if(x.pathname==="/"||x.pathname==="/health"){j.writeHead(200,{"Content-Type":"text/plain; charset=utf-8"}),j.end(`embd MCP server (stateless). POST ${$}
|
|
13
|
+
`);return}if(x.pathname!==$){a(j,404,{jsonrpc:"2.0",error:{code:-32601,message:`Not found. The MCP endpoint is ${$}.`},id:null});return}let B;if(Y.method==="POST")try{B=await mZ(Y)}catch{a(j,400,{jsonrpc:"2.0",error:{code:-32700,message:"Parse error: invalid or oversized JSON body"},id:null});return}let K=QZ(Z),M=new g({sessionIdGenerator:void 0,enableJsonResponse:!0,allowedHosts:Q,enableDnsRebindingProtection:W});j.on("close",()=>{M.close(),K.close()}),await K.connect(M),await M.handleRequest(Y,j,B)}}function B0(Z={}){return hZ(cZ(Z))}
|
|
14
|
+
export{LZ as e,UZ as f,fZ as g,AZ as h,QZ as i,cZ as j,B0 as k};
|