blink 0.1.65 → 0.1.67
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/dist/browser/api/index.browser.cjs +1 -0
- package/dist/browser/api/index.browser.d.cts +2 -0
- package/dist/browser/api/index.browser.d.ts +2 -0
- package/dist/browser/api/index.browser.js +1 -0
- package/dist/browser/client-BbZudkEc.js +21 -0
- package/dist/{index-y1u5VC2_.d.ts → browser/client-Co98ZOqj.d.cts} +3 -22
- package/dist/browser/client-DFaZjb1-.cjs +21 -0
- package/dist/{index-DXNEroA1.d.cts → browser/client-J5gD4j_a.d.ts} +3 -22
- package/dist/browser/http/index.cjs +1 -0
- package/dist/{http/api.d.cts → browser/http/index.d.cts} +21 -18
- package/dist/{http/api.d.ts → browser/http/index.d.ts} +21 -18
- package/dist/browser/http/index.js +1 -0
- package/dist/browser/index.browser-BwGhLjB7.cjs +1 -0
- package/dist/{index-BdS2C_9A.d.cts → browser/index.browser-CHLe3dau.d.cts} +15 -91
- package/dist/{index-E064W90j.d.ts → browser/index.browser-Db4eudpn.d.ts} +15 -91
- package/dist/browser/index.browser-Dj8kjB6X.js +1 -0
- package/dist/browser/react/index.cjs +1 -0
- package/dist/browser/react/index.d.cts +31 -0
- package/dist/browser/react/index.d.ts +31 -0
- package/dist/browser/react/index.js +1 -0
- package/dist/cli/{dev-knS68Vac.js → dev-BAQJ4XqP.js} +63 -80
- package/dist/cli/index.js +6 -6
- package/dist/node/api/index.node.cjs +30 -0
- package/dist/node/api/index.node.d.cts +82 -0
- package/dist/node/api/index.node.d.ts +82 -0
- package/dist/node/api/index.node.js +30 -0
- package/dist/node/index.browser-D1y2mwdW.d.ts +281 -0
- package/dist/node/index.browser-wBJ4jcnM.d.cts +281 -0
- package/dist/node/test.d.cts +88 -0
- package/dist/node/test.d.ts +88 -0
- package/package.json +42 -18
- package/dist/api/index.cjs +0 -24
- package/dist/api/index.d.cts +0 -2
- package/dist/api/index.d.ts +0 -2
- package/dist/api/index.js +0 -24
- package/dist/http/api.cjs +0 -1
- package/dist/http/api.js +0 -1
- package/dist/http/index.cjs +0 -1
- package/dist/http/index.d.cts +0 -3
- package/dist/http/index.d.ts +0 -3
- package/dist/http/index.js +0 -1
- package/dist/http-CU96NOdn.js +0 -21
- package/dist/http-DXLJkJIR.cjs +0 -21
- package/dist/test.d.cts +0 -12
- package/dist/test.d.ts +0 -12
- /package/dist/{build → node/build}/index.cjs +0 -0
- /package/dist/{build → node/build}/index.d.cts +0 -0
- /package/dist/{build → node/build}/index.d.ts +0 -0
- /package/dist/{build → node/build}/index.js +0 -0
- /package/dist/{chunk-___ucjiX.js → node/chunk-___ucjiX.js} +0 -0
- /package/dist/{chunk-hhQzssFb.cjs → node/chunk-hhQzssFb.cjs} +0 -0
- /package/dist/{test.cjs → node/test.cjs} +0 -0
- /package/dist/{test.js → node/test.js} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{APIServerURLEnvironmentVariable as e,Client as t,StreamResponseFormatHeader as n,checkOptionalParameter as r,convertResponseToUIMessageStream as i,decodeURIComponent_ as a,getPath as o,getPathNoStrict as s,getPattern as c,getQueryParam as l,getQueryParams as u,mergePath as d,parse as f,splitPath as p,splitRoutingPath as m,streamSSE as h,tryDecode as g}from"../client-BbZudkEc.js";function ee(e){let t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){let e=this.getReader(),t=!1;async function n(n){t=!0;try{n&&await e.cancel?.()}finally{try{e.releaseLock()}catch{}}}return{async next(){if(t)return{done:!0,value:void 0};let{done:r,value:i}=await e.read();return r?(await n(!0),{done:!0,value:void 0}):{done:!1,value:i}},async return(){return await n(!0),{done:!0,value:void 0}},async throw(e){throw await n(!0),e}}},t}var _=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},te=Symbol(),ne=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=e instanceof x?e.raw.headers:e.headers,a=i.get(`Content-Type`);return a?.startsWith(`multipart/form-data`)||a?.startsWith(`application/x-www-form-urlencoded`)?re(e,{all:n,dot:r}):{}};async function re(e,t){let n=await e.formData();return n?v(n,t):{}}function v(e,t){let n=Object.create(null);return e.forEach((e,r)=>{let i=t.all||r.endsWith(`[]`);i?y(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{let r=e.includes(`.`);r&&(ie(n,e,t),delete n[e])}),n}var y=(e,t,n)=>{e[t]===void 0?t.endsWith(`[]`)?e[t]=[n]:e[t]=n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},ie=(e,t,n)=>{let r=e,i=t.split(`.`);i.forEach((e,t)=>{t===i.length-1?r[e]=n:((!r[e]||typeof r[e]!=`object`||Array.isArray(r[e])||r[e]instanceof File)&&(r[e]=Object.create(null)),r=r[e])})},b=e=>g(e,a),x=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#matchResult=n,this.#validatedData={}}param(e){return e?this.#getDecodedParam(e):this.#getAllDecodedParams()}#getDecodedParam(e){let t=this.#matchResult[0][this.routeIndex][1][e],n=this.#getParamValue(t);return n&&/\%/.test(n)?b(n):n}#getAllDecodedParams(){let e={},t=Object.keys(this.#matchResult[0][this.routeIndex][1]);for(let n of t){let t=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=/\%/.test(t)?b(t):t)}return e}#getParamValue(e){return this.#matchResult[1]?this.#matchResult[1][e]:e}query(e){return l(this.url,e)}queries(e){return u(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return this.bodyCache.parsedBody??=await ne(this,e)}#cachedBody=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let i=Object.keys(t)[0];return i?t[i].then(t=>(i===`json`&&(t=JSON.stringify(t)),new Response(t)[e]())):t[e]=n[e]()};json(){return this.#cachedBody(`text`).then(e=>JSON.parse(e))}text(){return this.#cachedBody(`text`)}arrayBuffer(){return this.#cachedBody(`arrayBuffer`)}blob(){return this.#cachedBody(`blob`)}formData(){return this.#cachedBody(`formData`)}addValidatedData(e,t){this.#validatedData[e]=t}valid(e){return this.#validatedData[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[te](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},ae={Stringify:1,BeforeStream:2,Stream:3},S=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},C=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>C(e,t,!1,r,i))).then(()=>i[0]));return n?S(await o,a):o},w=`text/plain; charset=UTF-8`,T=(e,t)=>({"Content-Type":e,...t}),oe=class{#rawRequest;#req;env={};#var;finalized=!1;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(e,t){this.#rawRequest=e,t&&(this.#executionCtx=t.executionCtx,this.env=t.env,this.#notFoundHandler=t.notFoundHandler,this.#path=t.path,this.#matchResult=t.matchResult)}get req(){return this.#req??=new x(this.#rawRequest,this.#path,this.#matchResult),this.#req}get event(){if(this.#executionCtx&&`respondWith`in this.#executionCtx)return this.#executionCtx;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;throw Error(`This context has no ExecutionContext`)}get res(){return this.#res||=new Response(null,{headers:this.#preparedHeaders??=new Headers})}set res(e){if(this.#res&&e){e=new Response(e.body,e);for(let[t,n]of this.#res.headers.entries()){if(t===`content-type`)continue;if(t===`set-cookie`){let t=this.#res.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}}this.#res=e,this.finalized=!0}render=(...e)=>(this.#renderer??=e=>this.html(e),this.#renderer(...e));setLayout=e=>this.#layout=e;getLayout=()=>this.#layout;setRenderer=e=>{this.#renderer=e};header=(e,t,n)=>{this.finalized&&(this.#res=new Response(this.#res.body,this.#res));let r=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#status=e};set=(e,t)=>{this.#var??=new Map,this.#var.set(e,t)};get=e=>this.#var?this.#var.get(e):void 0;get var(){return this.#var?Object.fromEntries(this.#var):{}}#newResponse(e,t,n){let r=this.#res?new Headers(this.#res.headers):this.#preparedHeaders??new Headers;if(typeof t==`object`&&`headers`in t){let e=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[t,n]of e)t.toLowerCase()===`set-cookie`?r.append(t,n):r.set(t,n)}if(n)for(let[e,t]of Object.entries(n))if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}let i=typeof t==`number`?t:t?.status??this.#status;return new Response(e,{status:i,headers:r})}newResponse=(...e)=>this.#newResponse(...e);body=(e,t,n)=>this.#newResponse(e,t,n);text=(e,t,n)=>!this.#preparedHeaders&&!this.#status&&!t&&!n&&!this.finalized?new Response(e):this.#newResponse(e,t,T(w,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,T(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,T(`text/html; charset=UTF-8`,n));return typeof e==`object`?C(e,ae.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#notFoundHandler??=()=>new Response,this.#notFoundHandler(this))},E=`ALL`,se=`all`,D=[`get`,`post`,`put`,`delete`,`options`,`patch`],O=`Can not add a route since the matcher is already built.`,k=class extends Error{},ce=`__COMPOSED_HANDLER`,le=e=>e.text(`404 Not Found`,404),A=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},j=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#path=`/`;routes=[];constructor(e={}){let t=[...D,se];t.forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#path=t:this.#addRoute(e,this.#path,t),n.forEach(t=>{this.#addRoute(e,this.#path,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#path=r;for(let t of[e].flat())n.map(e=>{this.#addRoute(t.toUpperCase(),this.#path,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#path=e:(this.#path=`*`,t.unshift(e)),t.forEach(e=>{this.#addRoute(E,this.#path,e)}),this);let{strict:n,...r}=e;Object.assign(this,r),this.getPath=n??!0?e.getPath??o:s}#clone(){let e=new j({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#notFoundHandler=this.#notFoundHandler,e.routes=this.routes,e}#notFoundHandler=le;errorHandler=A;route(e,t){let n=this.basePath(e);return t.routes.map(e=>{let r;t.errorHandler===A?r=e.handler:(r=async(n,r)=>(await _([],t.errorHandler)(n,()=>e.handler(n,r))).res,r[ce]=e.handler),n.#addRoute(e.method,e.path,r)}),this}basePath(e){let t=this.#clone();return t._basePath=d(this._basePath,e),t}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#notFoundHandler=e,this);mount(e,t,n){let r,i;n&&(typeof n==`function`?i=n:(i=n.optionHandler,r=n.replaceRequest===!1?e=>e:n.replaceRequest));let a=i?e=>{let t=i(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};r||=(()=>{let t=d(this._basePath,e),n=t===`/`?0:t.length;return e=>{let t=new URL(e.url);return t.pathname=t.pathname.slice(n)||`/`,new Request(t,e)}})();let o=async(e,n)=>{let i=await t(r(e.req.raw),...a(e));if(i)return i;await n()};return this.#addRoute(E,d(e,`*`),o),this}#addRoute(e,t,n){e=e.toUpperCase(),t=d(this._basePath,t);let r={basePath:this._basePath,path:t,method:e,handler:n};this.router.add(e,t,[n,r]),this.routes.push(r)}#handleError(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#dispatch(e,t,n,r){if(r===`HEAD`)return(async()=>new Response(null,await this.#dispatch(e,t,n,`GET`)))();let i=this.getPath(e,{env:n}),a=this.router.match(r,i),o=new oe(e,{path:i,matchResult:a,env:n,executionCtx:t,notFoundHandler:this.#notFoundHandler});if(a[0].length===1){let e;try{e=a[0][0][0][0](o,async()=>{o.res=await this.#notFoundHandler(o)})}catch(e){return this.#handleError(e,o)}return e instanceof Promise?e.then(e=>e||(o.finalized?o.res:this.#notFoundHandler(o))).catch(e=>this.#handleError(e,o)):e??this.#notFoundHandler(o)}let s=_(a[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let e=await s(o);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#handleError(e,o)}})()}fetch=(e,...t)=>this.#dispatch(e,t[1],t[0],e.method);request=(e,t,n,r)=>e instanceof Request?this.fetch(t?new Request(e,t):e,n,r):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${d(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#dispatch(e.request,e,void 0,e.request.method))})}},M=`[^/]+`,N=`.*`,P=`(?:|/.*)`,F=Symbol(),I=new Set(`.\\+*[^]$()`);function L(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===N||e===P?1:t===N||t===P?-1:e===M?1:t===M?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var R=class{#index;#varIndex;#children=Object.create(null);insert(e,t,n,r,i){if(e.length===0){if(this.#index!==void 0)throw F;if(i)return;this.#index=t;return}let[a,...o]=e,s=a===`*`?o.length===0?[``,``,N]:[``,``,M]:a===`/*`?[``,``,P]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(s){let e=s[1],t=s[2]||M;if(e&&s[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))))throw F;if(c=this.#children[t],!c){if(Object.keys(this.#children).some(e=>e!==N&&e!==P))throw F;if(i)return;c=this.#children[t]=new R,e!==``&&(c.#varIndex=r.varIndex++)}!i&&e!==``&&n.push([e,c.#varIndex])}else if(c=this.#children[a],!c){if(Object.keys(this.#children).some(e=>e.length>1&&e!==N&&e!==P))throw F;if(i)return;c=this.#children[a]=new R}c.insert(o,t,n,r,i)}buildRegExpStr(){let e=Object.keys(this.#children).sort(L),t=e.map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:I.has(e)?`\\${e}`:e)+t.buildRegExpStr()});return typeof this.#index==`number`&&t.unshift(`#${this.#index}`),t.length===0?``:t.length===1?t[0]:`(?:`+t.join(`|`)+`)`}},z=class{#context={varIndex:0};#root=new R;insert(e,t,n){let r=[],i=[];for(let t=0;;){let n=!1;if(e=e.replace(/\{[^}]+\}/g,e=>{let r=`@\\${t}`;return i[t]=[r,e],t++,n=!0,r}),!n)break}let a=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=i.length-1;e>=0;e--){let[t]=i[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,i[e][1]);break}}return this.#root.insert(a,t,r,this.#context,n),r}buildRegExp(){let e=this.#root.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},B=[],V=[/^$/,[],Object.create(null)],H=Object.create(null);function U(e){return H[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function ue(){H=Object.create(null)}function de(e){let t=new z,n=[];if(e.length===0)return V;let r=e.map(e=>[!/\*|\/:/.test(e[0]),...e]).sort(([e,t],[n,r])=>e?1:n?-1:t.length-r.length),i=Object.create(null);for(let e=0,a=-1,o=r.length;e<o;e++){let[o,s,c]=r[e];o?i[s]=[c.map(([e])=>[e,Object.create(null)]),B]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===F?new k(s):e}o||(n[a]=c.map(([e,t])=>{let n=Object.create(null);for(--t;t>=0;t--){let[e,r]=l[t];n[e]=r}return[e,n]}))}let[a,o,s]=t.buildRegExp();for(let e=0,t=n.length;e<t;e++)for(let t=0,r=n[e].length;t<r;t++){let r=n[e][t]?.[1];if(!r)continue;let i=Object.keys(r);for(let e=0,t=i.length;e<t;e++)r[i[e]]=s[r[i[e]]]}let c=[];for(let e in o)c[e]=n[o[e]];return[a,c,i]}function W(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(U(n).test(t))return[...e[n]]}}var fe=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[E]:Object.create(null)},this.#routes={[E]:Object.create(null)}}add(e,t,n){let i=this.#middleware,a=this.#routes;if(!i||!a)throw Error(O);i[e]||[i,a].forEach(t=>{t[e]=Object.create(null),Object.keys(t[E]).forEach(n=>{t[e][n]=[...t[E][n]]})}),t===`/*`&&(t=`*`);let o=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let r=U(t);e===E?Object.keys(i).forEach(e=>{i[e][t]||=W(i[e],t)||W(i[E],t)||[]}):i[e][t]||=W(i[e],t)||W(i[E],t)||[],Object.keys(i).forEach(t=>{(e===E||e===t)&&Object.keys(i[t]).forEach(e=>{r.test(e)&&i[t][e].push([n,o])})}),Object.keys(a).forEach(t=>{(e===E||e===t)&&Object.keys(a[t]).forEach(e=>r.test(e)&&a[t][e].push([n,o]))});return}let s=r(t)||[t];for(let t=0,r=s.length;t<r;t++){let c=s[t];Object.keys(a).forEach(s=>{(e===E||e===s)&&(a[s][c]||=[...W(i[s],c)||W(i[E],c)||[]],a[s][c].push([n,o-r+t+1]))})}}match(e,t){ue();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[E],i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],B];let o=a.indexOf(``,1);return[r[1][o],a]},this.match(e,t)}#buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach(t=>{e[t]||=this.#buildMatcher(t)}),this.#middleware=this.#routes=void 0,e}#buildMatcher(e){let t=[],n=e===E;return[this.#middleware,this.#routes].forEach(r=>{let i=r[e]?Object.keys(r[e]).map(t=>[t,r[e][t]]):[];i.length===0?e!==E&&t.push(...Object.keys(r[E]).map(e=>[e,r[E][e]])):(n||=!0,t.push(...i))}),n?de(t):null}},pe=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(O);this.#routes.push([e,t,n])}match(e,t){if(!this.#routes)throw Error(`Fatal error`);let n=this.#routers,r=this.#routes,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof k)continue;throw e}this.match=i.match.bind(i),this.#routers=[i],this.#routes=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#routes||this.#routers.length!==1)throw Error(`No active router has been determined yet.`);return this.#routers[0]}},G=Object.create(null),K=class{#methods;#children;#patterns;#order=0;#params=G;constructor(e,t,n){if(this.#children=n||Object.create(null),this.#methods=[],e&&t){let n=Object.create(null);n[e]={handler:t,possibleKeys:[],score:0},this.#methods=[n]}this.#patterns=[]}insert(e,t,n){this.#order=++this.#order;let r=this,i=m(t),a=[];for(let e=0,t=i.length;e<t;e++){let t=i[e],n=i[e+1],o=c(t,n),s=Array.isArray(o)?o[0]:t;if(s in r.#children){r=r.#children[s],o&&a.push(o[1]);continue}r.#children[s]=new K,o&&(r.#patterns.push(o),a.push(o[1])),r=r.#children[s]}return r.#methods.push({[e]:{handler:n,possibleKeys:a.filter((e,t,n)=>n.indexOf(e)===t),score:this.#order}}),r}#getHandlerSets(e,t,n,r){let i=[];for(let a=0,o=e.#methods.length;a<o;a++){let o=e.#methods[a],s=o[t]||o[E],c={};if(s!==void 0&&(s.params=Object.create(null),i.push(s),n!==G||r&&r!==G))for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e],i=c[s.score];s.params[t]=r?.[t]&&!i?r[t]:n[t]??r?.[t],c[s.score]=!0}}return i}search(e,t){let n=[];this.#params=G;let r=this,i=[r],a=p(t),o=[];for(let t=0,r=a.length;t<r;t++){let s=a[t],c=t===r-1,l=[];for(let r=0,u=i.length;r<u;r++){let u=i[r],d=u.#children[s];d&&(d.#params=u.#params,c?(d.#children[`*`]&&n.push(...this.#getHandlerSets(d.#children[`*`],e,u.#params)),n.push(...this.#getHandlerSets(d,e,u.#params))):l.push(d));for(let r=0,i=u.#patterns.length;r<i;r++){let i=u.#patterns[r],d=u.#params===G?{}:{...u.#params};if(i===`*`){let t=u.#children[`*`];t&&(n.push(...this.#getHandlerSets(t,e,u.#params)),t.#params=d,l.push(t));continue}let[f,p,m]=i;if(!s&&!(m instanceof RegExp))continue;let h=u.#children[f],g=a.slice(t).join(`/`);if(m instanceof RegExp){let t=m.exec(g);if(t){if(d[p]=t[0],n.push(...this.#getHandlerSets(h,e,u.#params,d)),Object.keys(h.#children).length){h.#params=d;let e=t[0].match(/\//)?.length??0,n=o[e]||=[];n.push(h)}continue}}(m===!0||m.test(s))&&(d[p]=s,c?(n.push(...this.#getHandlerSets(h,e,d,u.#params)),h.#children[`*`]&&n.push(...this.#getHandlerSets(h.#children[`*`],e,d,u.#params))):(h.#params=d,l.push(h)))}}i=l.concat(o.shift()??[])}return n.length>1&&n.sort((e,t)=>e.score-t.score),[n.map(({handler:e,params:t})=>[e,t])]}},me=class{name=`TrieRouter`;#node;constructor(){this.#node=new K}add(e,t,n){let i=r(t);if(i){for(let t=0,r=i.length;t<r;t++)this.#node.insert(e,i[t],n);return}this.#node.insert(e,t,n)}match(e,t){return this.#node.search(e,t)}},q=class extends j{constructor(e={}){super(e),this.router=e.router??new pe({routers:[new fe,new me]})}},he=(e,t,n)=>{let r=e.req.raw.headers.get(`Cookie`);if(typeof t==`string`){if(!r)return;let e=t;n===`secure`?e=`__Secure-`+t:n===`host`&&(e=`__Host-`+t);let i=f(r,e);return i[e]}if(!r)return{};let i=f(r);return i},J=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){if(this.res){let e=new Response(this.res.body,{status:this.status,headers:this.res.headers});return e}return new Response(this.message,{status:this.status})}},ge=(e,t)=>{let n=new Response(e,{headers:{"Content-Type":t}});return n.formData()},_e=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,ve=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,ye=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,Y=(e,t)=>async(n,r)=>{let i={},a=n.req.header(`Content-Type`);switch(e){case`json`:if(!a||!_e.test(a))break;try{i=await n.req.json()}catch{throw new J(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(ve.test(a)||ye.test(a)))break;let e;if(n.req.bodyCache.formData)e=await n.req.bodyCache.formData;else try{let t=await n.req.arrayBuffer();e=await ge(t,a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new J(400,{message:t})}let t={};e.forEach((e,n)=>{n.endsWith(`[]`)?(t[n]??=[]).push(e):Array.isArray(t[n])?t[n].push(e):n in t?t[n]=[t[n],e]:t[n]=e}),i=t;break}case`query`:i=Object.fromEntries(Object.entries(n.req.queries()).map(([e,t])=>t.length===1?[e,t[0]]:[e,t]));break;case`param`:i=n.req.param();break;case`header`:i=n.req.header();break;case`cookie`:i=he(n);break}let o=await t(i,n);if(o instanceof Response)return o;n.req.addValidatedData(e,o),await r()};const X=(e,t)=>e.json({error:t},400),Z=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>128?{key:t,err:`Key is too long. Max length is 128 characters.`}:{key:t}},Q=()=>new q,be=Q().get(`/kv/:key`,async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let r=await e.env.storage.kv.get(t);return e.json({value:r},200)}).post(`/kv/:key`,Y(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>1024?X(t,`Value is too long. Max length is 1024 characters.`):{value:n}:X(t,`Value must be a string`):X(t,`Value is required`)}),async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let{value:r}=e.req.valid(`json`);return await e.env.storage.kv.set(t,r),e.body(null,204)}).delete(`/kv/:key`,async e=>{let{key:t,err:n}=Z(e);return n?X(e,n):(await e.env.storage.kv.del(t),e.body(null,204))}),$=e=>{let t=e.req.param(`id`);return t?t.length>128?{id:t,err:`ID is too long. Max length is 128 characters.`}:{id:t}:{id:t,err:`ID is required`}},xe=Q().basePath(`/:id`).post(`/`,async e=>{let{id:t,err:n}=$(e);if(n)return X(e,n);let r=await e.env.chat.upsert(t);return e.json({id:r.id},200)}).post(`/sendMessages`,Y(`json`,(e,t)=>{let n=e.messages;if(!n)return X(t,`Messages are required`);if(!Array.isArray(n))return X(t,`Messages must be an array`);if(n.length===0)return X(t,`Messages must not be empty`);let r=e.behavior;return r!==`enqueue`&&r!==`interrupt`&&r!==`append`?X(t,`Invalid behavior`):{messages:n,behavior:r}}),async e=>{let{id:t,err:n}=$(e);if(n)return X(e,n);let{messages:r,behavior:i}=e.req.valid(`json`);try{await e.env.chat.sendMessages(t,{messages:r,behavior:i})}catch(t){return X(e,t instanceof Error?t.message:`Unknown error`)}return e.body(null,204)}),Se=new q().route(`/storage`,be).route(`/chat`,xe);export{e as APIServerURLEnvironmentVariable,t as Client,n as StreamResponseFormatHeader,Se as api,i as convertResponseToUIMessageStream,ee as createAsyncIterableStream,h as streamSSE};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=require(`./client-DFaZjb1-.cjs`);let t=require(`ai`);t=e.__toESM(t);const n=Object.freeze({upsert:async t=>{let n=await e.client.chat[`:id`].$post({param:{id:t}});if(n.status!==200){let e=await n.json();throw Error(e.error)}return{id:t}},message:async(t,n,r)=>{let i=await e.client.chat[`:id`].sendMessages.$post({param:{id:t},json:{messages:[n],behavior:r?.behavior??`enqueue`}});if(i.status!==204){let e=await i.json();throw Error(e.error)}}}),r=Object.freeze({kv:Object.freeze({get:async t=>{let n=await e.client.storage.kv[`:key`].$get({param:{key:t}});if(n.status!==200){let e=await n.json();throw Error(e.error)}let r=await n.json();return r.value},set:async(t,n)=>{let r=await e.client.storage.kv[`:key`].$post({param:{key:t},json:{value:n}});if(r.status!==204){let e=await r.json();throw Error(e.error)}},del:async t=>{let n=await e.client.storage.kv[`:key`].$delete({param:{key:t}});if(n.status!==204){let e=await n.json();throw Error(e.error)}}})});function i(e){return typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`}var a=class extends Error{constructor(e,t){super(e),this.response=t}};function o(e){return e}const s={withContext(e,t){let n={};for(let r of Object.keys(e)){let i=e[r];n[r]=i.withContext(t)}return n},with(e,t){let n={};for(let r of Object.keys(e)){let i=e[r];n[r]=i.withContext(t)}return n},async withApproval(e){let n={};for(let[t,r]of Object.entries(e.tools)){let e=r.execute;n[t]={...r,execute:async(t,n)=>{if(r.autoApprove&&e){let i=await r.autoApprove(t);if(i)return e(t,n)}let i={type:`tool-approval`,outcome:`pending`};return i}}}let r=e.messages[e.messages.length-1];if(!r?.parts)return n;let o=[];for(let n of r.parts){if(!(0,t.isToolUIPart)(n))continue;let r=(0,t.getToolName)(n),i=e.tools[r];if(!i||n.state!==`output-available`||!i.execute||!c(n.output))continue;n.output.outcome===`approved`&&o.push({toolName:(0,t.getToolName)(n),tool:i,input:n.input,toolCallId:n.toolCallId})}if(o.length>0){let n=(0,t.createUIMessageStream)({execute:async({writer:n})=>{n.write({type:`start-step`}),await Promise.all(o.map(async r=>{if(!r.tool.execute)throw Error(`Tool does not support execute.`);n.write({type:`tool-input-available`,toolCallId:r.toolCallId,toolName:r.toolName,input:r.input});try{let a=await r.tool.execute(r.input,{toolCallId:r.toolCallId,messages:(0,t.convertToModelMessages)(e.messages,{tools:e.tools}),abortSignal:e.abortSignal});if(i(a))for await(let e of a)n.write({type:`tool-output-available`,toolCallId:r.toolCallId,output:e,preliminary:!0});n.write({type:`tool-output-available`,toolCallId:r.toolCallId,output:a})}catch(e){n.write({type:`tool-output-error`,toolCallId:r.toolCallId,errorText:e instanceof Error?e.message:String(e)})}})),n.write({type:`finish`})}});throw new a(`Executing tools`,n)}return n},prefix(e,t){let n={};for(let[r,i]of Object.entries(e))n[`${t}${r}`]=i;return n}};function c(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool-approval`}function l(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n!==void 0&&n.role===`user`&&!(typeof n.metadata!=`object`||n.metadata===null)&&`options`in n.metadata)return n.metadata.options}}function u(t,n){let r=new Headers(t.headers);return r.set(e.StreamResponseFormatHeader,n),new Response(t.body,{status:t.status,statusText:t.statusText,headers:r})}Object.defineProperty(exports,`chat`,{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,`isToolApprovalOutput`,{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,`lastUIOptions`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,`storage`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,`toolWithApproval`,{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,`tools`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`withResponseFormat`,{enumerable:!0,get:function(){return u}});
|
|
@@ -1,7 +1,4 @@
|
|
|
1
|
-
import * as _ai_sdk_provider0 from "@ai-sdk/provider";
|
|
2
|
-
import * as ai0 from "ai";
|
|
3
1
|
import { AsyncIterableStream, InferToolInput, InferToolOutput, InferUIMessageChunk, Tool, ToolSet, UIDataTypes, UIMessage, UIMessagePart, UITools } from "ai";
|
|
4
|
-
import http from "http";
|
|
5
2
|
|
|
6
3
|
//#region src/api/chat.d.ts
|
|
7
4
|
interface Chat {
|
|
@@ -28,6 +25,19 @@ declare const chat: Readonly<{
|
|
|
28
25
|
message: (id: string, message: Message, options?: MessageOptions) => Promise<void>;
|
|
29
26
|
}>;
|
|
30
27
|
//#endregion
|
|
28
|
+
//#region src/api/storage.d.ts
|
|
29
|
+
/**
|
|
30
|
+
* Storage allows agents to persist data.
|
|
31
|
+
* Every agent has it's own persistent storage namespace.
|
|
32
|
+
*/
|
|
33
|
+
declare const storage: Readonly<{
|
|
34
|
+
kv: Readonly<{
|
|
35
|
+
get: (key: string) => Promise<string | undefined>;
|
|
36
|
+
set: (key: string, value: string) => Promise<void>;
|
|
37
|
+
del: (key: string) => Promise<void>;
|
|
38
|
+
}>;
|
|
39
|
+
}>;
|
|
40
|
+
//#endregion
|
|
31
41
|
//#region src/api/tools.d.ts
|
|
32
42
|
/**
|
|
33
43
|
* ToolWithContext is a tool that supports the "withContext" method.
|
|
@@ -127,20 +137,7 @@ interface ToolApprovalOutput {
|
|
|
127
137
|
*/
|
|
128
138
|
declare function isToolApprovalOutput(output: unknown): output is ToolApprovalOutput;
|
|
129
139
|
//#endregion
|
|
130
|
-
//#region src/api/
|
|
131
|
-
/**
|
|
132
|
-
* Storage allows agents to persist data.
|
|
133
|
-
* Every agent has it's own persistent storage namespace.
|
|
134
|
-
*/
|
|
135
|
-
declare const storage: Readonly<{
|
|
136
|
-
kv: Readonly<{
|
|
137
|
-
get: (key: string) => Promise<string | undefined>;
|
|
138
|
-
set: (key: string, value: string) => Promise<void>;
|
|
139
|
-
del: (key: string) => Promise<void>;
|
|
140
|
-
}>;
|
|
141
|
-
}>;
|
|
142
|
-
//#endregion
|
|
143
|
-
//#region src/api/index.d.ts
|
|
140
|
+
//#region src/api/index.browser.d.ts
|
|
144
141
|
/**
|
|
145
142
|
* SendMessagesResponse is the response of the sendMessages function.
|
|
146
143
|
* It can be a stream of messages or an arbitrary response.
|
|
@@ -278,80 +275,7 @@ interface AgentOptions<MESSAGE extends UIMessage = UIMessage> {
|
|
|
278
275
|
*/
|
|
279
276
|
provideUIOptions?(options: ProvideOptionsRequest<MESSAGE>): Promise<OptionsSchema<ExtractUIOptions<MESSAGE>>> | OptionsSchema<ExtractUIOptions<MESSAGE>>;
|
|
280
277
|
}
|
|
281
|
-
interface Agent {
|
|
282
|
-
/**
|
|
283
|
-
* fetch is the HTTP handler for the agent.
|
|
284
|
-
*
|
|
285
|
-
* @param request The request to handle.
|
|
286
|
-
* @returns A response to the request.
|
|
287
|
-
*/
|
|
288
|
-
fetch(request: Request): Promise<Response> | Response;
|
|
289
|
-
/**
|
|
290
|
-
* serve starts the agent as an unauthenticated HTTP server.
|
|
291
|
-
* This is required for use in the Blink Cloud or with the Blink CLI.
|
|
292
|
-
*
|
|
293
|
-
* @param options Optional options for the server.
|
|
294
|
-
* @returns A Node.JS HTTP server.
|
|
295
|
-
*/
|
|
296
|
-
serve(options?: ServeOptions): http.Server;
|
|
297
|
-
}
|
|
298
|
-
type ServeOptions = {
|
|
299
|
-
readonly host?: string;
|
|
300
|
-
readonly port?: number;
|
|
301
|
-
};
|
|
302
|
-
/**
|
|
303
|
-
* agent creates an HTTP handler that when served
|
|
304
|
-
* speaks the Blink agent protocol.
|
|
305
|
-
*
|
|
306
|
-
* Call `.serve()` to serve the agent for use in
|
|
307
|
-
* the Blink Cloud or with the Blink CLI.
|
|
308
|
-
*/
|
|
309
|
-
declare function agent<MESSAGE extends UIMessage = UIMessage>(agent: AgentOptions<MESSAGE>): Agent;
|
|
310
278
|
type StreamResponseFormat = "ui-message" | "openai-chat" | "openai-response" | "anthropic" | "google" | "xai";
|
|
311
279
|
declare function withResponseFormat(response: Response, format: StreamResponseFormat): Response;
|
|
312
|
-
/**
|
|
313
|
-
* model returns an AI SDK model that is authenticated through Blink.
|
|
314
|
-
*
|
|
315
|
-
* Blink's AI Gateway uses Vercel's AI Gateway under-the-hood, and passes
|
|
316
|
-
* through billing cost without any upcharge.
|
|
317
|
-
*
|
|
318
|
-
* Feel free to use any provide you'd like.
|
|
319
|
-
*
|
|
320
|
-
* @param modelName - See: https://vercel.com/ai-gateway/models
|
|
321
|
-
* @returns An AI SDK model that is authenticated through Blink.
|
|
322
|
-
*/
|
|
323
|
-
declare const model: (modelName: string) => _ai_sdk_provider0.LanguageModelV2;
|
|
324
|
-
declare const _default: {
|
|
325
|
-
agent: typeof agent;
|
|
326
|
-
chat: Readonly<{
|
|
327
|
-
upsert: (id: string) => Promise<Chat>;
|
|
328
|
-
message: (id: string, message: Message, options?: MessageOptions) => Promise<void>;
|
|
329
|
-
}>;
|
|
330
|
-
storage: Readonly<{
|
|
331
|
-
kv: Readonly<{
|
|
332
|
-
get: (key: string) => Promise<string | undefined>;
|
|
333
|
-
set: (key: string, value: string) => Promise<void>;
|
|
334
|
-
del: (key: string) => Promise<void>;
|
|
335
|
-
}>;
|
|
336
|
-
}>;
|
|
337
|
-
tools: {
|
|
338
|
-
withContext<const TOOLS extends {
|
|
339
|
-
[x: string]: ai0.Tool & {
|
|
340
|
-
withContext(context: unknown): ai0.Tool;
|
|
341
|
-
};
|
|
342
|
-
}>(tools: TOOLS, context: ContextFromTools<TOOLS>): { [K in keyof TOOLS]: ai0.Tool };
|
|
343
|
-
with<const TOOLS extends {
|
|
344
|
-
[x: string]: ai0.Tool & {
|
|
345
|
-
withContext(context: unknown): ai0.Tool;
|
|
346
|
-
};
|
|
347
|
-
}>(tools: TOOLS, context: ContextFromTools<TOOLS>): { [K in keyof TOOLS]: ai0.Tool };
|
|
348
|
-
withApproval<TOOLSET extends ai0.ToolSet, TOOLS extends ToolSetWithApproval<TOOLSET>, MESSAGE extends UIMessage>(options: {
|
|
349
|
-
messages: MESSAGE[];
|
|
350
|
-
tools: TOOLS;
|
|
351
|
-
abortSignal?: AbortSignal;
|
|
352
|
-
}): Promise<TOOLS>;
|
|
353
|
-
prefix(tools: ai0.ToolSet, prefix: string): ai0.ToolSet;
|
|
354
|
-
};
|
|
355
|
-
};
|
|
356
280
|
//#endregion
|
|
357
|
-
export {
|
|
281
|
+
export { AgentOptions, Chat, ChatBehavior, ContextFromTools, ExperimentalCompletion, ExperimentalProvideCompletionsOptions, ExperimentalProvideCompletionsResponse, ExtractUIOptions, Message, MessageOptions, OptionSelect, OptionSelectValue, Options, OptionsSchema, ProvideOptionsRequest, SendMessagesOptions, SendMessagesResponse, StreamResponseFormat, ToolApprovalOutput, ToolSetWithApproval, ToolWithApproval, ToolWithContext, WithUIOptions, chat, isToolApprovalOutput, lastUIOptions, storage, toolWithApproval, tools, withResponseFormat };
|
|
@@ -1,7 +1,4 @@
|
|
|
1
|
-
import http from "http";
|
|
2
|
-
import * as ai0 from "ai";
|
|
3
1
|
import { AsyncIterableStream, InferToolInput, InferToolOutput, InferUIMessageChunk, Tool, ToolSet, UIDataTypes, UIMessage, UIMessagePart, UITools } from "ai";
|
|
4
|
-
import * as _ai_sdk_provider0 from "@ai-sdk/provider";
|
|
5
2
|
|
|
6
3
|
//#region src/api/chat.d.ts
|
|
7
4
|
interface Chat {
|
|
@@ -28,6 +25,19 @@ declare const chat: Readonly<{
|
|
|
28
25
|
message: (id: string, message: Message, options?: MessageOptions) => Promise<void>;
|
|
29
26
|
}>;
|
|
30
27
|
//#endregion
|
|
28
|
+
//#region src/api/storage.d.ts
|
|
29
|
+
/**
|
|
30
|
+
* Storage allows agents to persist data.
|
|
31
|
+
* Every agent has it's own persistent storage namespace.
|
|
32
|
+
*/
|
|
33
|
+
declare const storage: Readonly<{
|
|
34
|
+
kv: Readonly<{
|
|
35
|
+
get: (key: string) => Promise<string | undefined>;
|
|
36
|
+
set: (key: string, value: string) => Promise<void>;
|
|
37
|
+
del: (key: string) => Promise<void>;
|
|
38
|
+
}>;
|
|
39
|
+
}>;
|
|
40
|
+
//#endregion
|
|
31
41
|
//#region src/api/tools.d.ts
|
|
32
42
|
/**
|
|
33
43
|
* ToolWithContext is a tool that supports the "withContext" method.
|
|
@@ -127,20 +137,7 @@ interface ToolApprovalOutput {
|
|
|
127
137
|
*/
|
|
128
138
|
declare function isToolApprovalOutput(output: unknown): output is ToolApprovalOutput;
|
|
129
139
|
//#endregion
|
|
130
|
-
//#region src/api/
|
|
131
|
-
/**
|
|
132
|
-
* Storage allows agents to persist data.
|
|
133
|
-
* Every agent has it's own persistent storage namespace.
|
|
134
|
-
*/
|
|
135
|
-
declare const storage: Readonly<{
|
|
136
|
-
kv: Readonly<{
|
|
137
|
-
get: (key: string) => Promise<string | undefined>;
|
|
138
|
-
set: (key: string, value: string) => Promise<void>;
|
|
139
|
-
del: (key: string) => Promise<void>;
|
|
140
|
-
}>;
|
|
141
|
-
}>;
|
|
142
|
-
//#endregion
|
|
143
|
-
//#region src/api/index.d.ts
|
|
140
|
+
//#region src/api/index.browser.d.ts
|
|
144
141
|
/**
|
|
145
142
|
* SendMessagesResponse is the response of the sendMessages function.
|
|
146
143
|
* It can be a stream of messages or an arbitrary response.
|
|
@@ -278,80 +275,7 @@ interface AgentOptions<MESSAGE extends UIMessage = UIMessage> {
|
|
|
278
275
|
*/
|
|
279
276
|
provideUIOptions?(options: ProvideOptionsRequest<MESSAGE>): Promise<OptionsSchema<ExtractUIOptions<MESSAGE>>> | OptionsSchema<ExtractUIOptions<MESSAGE>>;
|
|
280
277
|
}
|
|
281
|
-
interface Agent {
|
|
282
|
-
/**
|
|
283
|
-
* fetch is the HTTP handler for the agent.
|
|
284
|
-
*
|
|
285
|
-
* @param request The request to handle.
|
|
286
|
-
* @returns A response to the request.
|
|
287
|
-
*/
|
|
288
|
-
fetch(request: Request): Promise<Response> | Response;
|
|
289
|
-
/**
|
|
290
|
-
* serve starts the agent as an unauthenticated HTTP server.
|
|
291
|
-
* This is required for use in the Blink Cloud or with the Blink CLI.
|
|
292
|
-
*
|
|
293
|
-
* @param options Optional options for the server.
|
|
294
|
-
* @returns A Node.JS HTTP server.
|
|
295
|
-
*/
|
|
296
|
-
serve(options?: ServeOptions): http.Server;
|
|
297
|
-
}
|
|
298
|
-
type ServeOptions = {
|
|
299
|
-
readonly host?: string;
|
|
300
|
-
readonly port?: number;
|
|
301
|
-
};
|
|
302
|
-
/**
|
|
303
|
-
* agent creates an HTTP handler that when served
|
|
304
|
-
* speaks the Blink agent protocol.
|
|
305
|
-
*
|
|
306
|
-
* Call `.serve()` to serve the agent for use in
|
|
307
|
-
* the Blink Cloud or with the Blink CLI.
|
|
308
|
-
*/
|
|
309
|
-
declare function agent<MESSAGE extends UIMessage = UIMessage>(agent: AgentOptions<MESSAGE>): Agent;
|
|
310
278
|
type StreamResponseFormat = "ui-message" | "openai-chat" | "openai-response" | "anthropic" | "google" | "xai";
|
|
311
279
|
declare function withResponseFormat(response: Response, format: StreamResponseFormat): Response;
|
|
312
|
-
/**
|
|
313
|
-
* model returns an AI SDK model that is authenticated through Blink.
|
|
314
|
-
*
|
|
315
|
-
* Blink's AI Gateway uses Vercel's AI Gateway under-the-hood, and passes
|
|
316
|
-
* through billing cost without any upcharge.
|
|
317
|
-
*
|
|
318
|
-
* Feel free to use any provide you'd like.
|
|
319
|
-
*
|
|
320
|
-
* @param modelName - See: https://vercel.com/ai-gateway/models
|
|
321
|
-
* @returns An AI SDK model that is authenticated through Blink.
|
|
322
|
-
*/
|
|
323
|
-
declare const model: (modelName: string) => _ai_sdk_provider0.LanguageModelV2;
|
|
324
|
-
declare const _default: {
|
|
325
|
-
agent: typeof agent;
|
|
326
|
-
chat: Readonly<{
|
|
327
|
-
upsert: (id: string) => Promise<Chat>;
|
|
328
|
-
message: (id: string, message: Message, options?: MessageOptions) => Promise<void>;
|
|
329
|
-
}>;
|
|
330
|
-
storage: Readonly<{
|
|
331
|
-
kv: Readonly<{
|
|
332
|
-
get: (key: string) => Promise<string | undefined>;
|
|
333
|
-
set: (key: string, value: string) => Promise<void>;
|
|
334
|
-
del: (key: string) => Promise<void>;
|
|
335
|
-
}>;
|
|
336
|
-
}>;
|
|
337
|
-
tools: {
|
|
338
|
-
withContext<const TOOLS extends {
|
|
339
|
-
[x: string]: ai0.Tool & {
|
|
340
|
-
withContext(context: unknown): ai0.Tool;
|
|
341
|
-
};
|
|
342
|
-
}>(tools: TOOLS, context: ContextFromTools<TOOLS>): { [K in keyof TOOLS]: ai0.Tool };
|
|
343
|
-
with<const TOOLS extends {
|
|
344
|
-
[x: string]: ai0.Tool & {
|
|
345
|
-
withContext(context: unknown): ai0.Tool;
|
|
346
|
-
};
|
|
347
|
-
}>(tools: TOOLS, context: ContextFromTools<TOOLS>): { [K in keyof TOOLS]: ai0.Tool };
|
|
348
|
-
withApproval<TOOLSET extends ai0.ToolSet, TOOLS extends ToolSetWithApproval<TOOLSET>, MESSAGE extends UIMessage>(options: {
|
|
349
|
-
messages: MESSAGE[];
|
|
350
|
-
tools: TOOLS;
|
|
351
|
-
abortSignal?: AbortSignal;
|
|
352
|
-
}): Promise<TOOLS>;
|
|
353
|
-
prefix(tools: ai0.ToolSet, prefix: string): ai0.ToolSet;
|
|
354
|
-
};
|
|
355
|
-
};
|
|
356
280
|
//#endregion
|
|
357
|
-
export {
|
|
281
|
+
export { AgentOptions, Chat, ChatBehavior, ContextFromTools, ExperimentalCompletion, ExperimentalProvideCompletionsOptions, ExperimentalProvideCompletionsResponse, ExtractUIOptions, Message, MessageOptions, OptionSelect, OptionSelectValue, Options, OptionsSchema, ProvideOptionsRequest, SendMessagesOptions, SendMessagesResponse, StreamResponseFormat, ToolApprovalOutput, ToolSetWithApproval, ToolWithApproval, ToolWithContext, WithUIOptions, chat, isToolApprovalOutput, lastUIOptions, storage, toolWithApproval, tools, withResponseFormat };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{StreamResponseFormatHeader as e,client as t}from"./client-BbZudkEc.js";import{convertToModelMessages as n,createUIMessageStream as r,getToolName as i,isToolUIPart as a}from"ai";const o=Object.freeze({upsert:async e=>{let n=await t.chat[`:id`].$post({param:{id:e}});if(n.status!==200){let e=await n.json();throw Error(e.error)}return{id:e}},message:async(e,n,r)=>{let i=await t.chat[`:id`].sendMessages.$post({param:{id:e},json:{messages:[n],behavior:r?.behavior??`enqueue`}});if(i.status!==204){let e=await i.json();throw Error(e.error)}}}),s=Object.freeze({kv:Object.freeze({get:async e=>{let n=await t.storage.kv[`:key`].$get({param:{key:e}});if(n.status!==200){let e=await n.json();throw Error(e.error)}let r=await n.json();return r.value},set:async(e,n)=>{let r=await t.storage.kv[`:key`].$post({param:{key:e},json:{value:n}});if(r.status!==204){let e=await r.json();throw Error(e.error)}},del:async e=>{let n=await t.storage.kv[`:key`].$delete({param:{key:e}});if(n.status!==204){let e=await n.json();throw Error(e.error)}}})});function c(e){return typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`}var l=class extends Error{constructor(e,t){super(e),this.response=t}};function u(e){return e}const d={withContext(e,t){let n={};for(let r of Object.keys(e)){let i=e[r];n[r]=i.withContext(t)}return n},with(e,t){let n={};for(let r of Object.keys(e)){let i=e[r];n[r]=i.withContext(t)}return n},async withApproval(e){let t={};for(let[n,r]of Object.entries(e.tools)){let e=r.execute;t[n]={...r,execute:async(t,n)=>{if(r.autoApprove&&e){let i=await r.autoApprove(t);if(i)return e(t,n)}let i={type:`tool-approval`,outcome:`pending`};return i}}}let o=e.messages[e.messages.length-1];if(!o?.parts)return t;let s=[];for(let t of o.parts){if(!a(t))continue;let n=i(t),r=e.tools[n];if(!r||t.state!==`output-available`||!r.execute||!f(t.output))continue;t.output.outcome===`approved`&&s.push({toolName:i(t),tool:r,input:t.input,toolCallId:t.toolCallId})}if(s.length>0){let t=r({execute:async({writer:t})=>{t.write({type:`start-step`}),await Promise.all(s.map(async r=>{if(!r.tool.execute)throw Error(`Tool does not support execute.`);t.write({type:`tool-input-available`,toolCallId:r.toolCallId,toolName:r.toolName,input:r.input});try{let i=await r.tool.execute(r.input,{toolCallId:r.toolCallId,messages:n(e.messages,{tools:e.tools}),abortSignal:e.abortSignal});if(c(i))for await(let e of i)t.write({type:`tool-output-available`,toolCallId:r.toolCallId,output:e,preliminary:!0});t.write({type:`tool-output-available`,toolCallId:r.toolCallId,output:i})}catch(e){t.write({type:`tool-output-error`,toolCallId:r.toolCallId,errorText:e instanceof Error?e.message:String(e)})}})),t.write({type:`finish`})}});throw new l(`Executing tools`,t)}return t},prefix(e,t){let n={};for(let[r,i]of Object.entries(e))n[`${t}${r}`]=i;return n}};function f(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool-approval`}function p(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n!==void 0&&n.role===`user`&&!(typeof n.metadata!=`object`||n.metadata===null)&&`options`in n.metadata)return n.metadata.options}}function m(t,n){let r=new Headers(t.headers);return r.set(e,n),new Response(t.body,{status:t.status,statusText:t.statusText,headers:r})}export{o as chat,f as isToolApprovalOutput,p as lastUIOptions,s as storage,u as toolWithApproval,d as tools,m as withResponseFormat};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=require(`../client-DFaZjb1-.cjs`),t=require(`../index.browser-BwGhLjB7.cjs`);let n=require(`react`);n=e.__toESM(n);function r({agent:e,capabilities:r,messages:i}){let[a,o]=(0,n.useState)(void 0),[s,c]=(0,n.useState)(!0),[l,u]=(0,n.useState)(void 0),d=(0,n.useMemo)(()=>t.lastUIOptions(i),[i]),[f,p]=(0,n.useState)(void 0),m=(0,n.useCallback)((e,t)=>{if(!l)return!1;let n=l[e];return n?n.values.some(e=>e.id===t):!1},[l]);(0,n.useEffect)(()=>{if(!d&&!l){p(void 0);return}p(e=>{let t={...d,...e};for(let[e,n]of Object.entries(t))m(e,n)||delete t[e];for(let[e,n]of Object.entries(l??{}))t[e]||(t[e]=n.defaultValue);return t})},[d,l,m]),(0,n.useEffect)(()=>{if(r&&!r.options||!e){u(void 0),p(void 0),o(void 0);return}let t=new AbortController;return c(!0),o(void 0),e.provideUIOptions(f?{selectedOptions:f}:{},{signal:t.signal}).then(e=>{t.signal.aborted||u(t=>JSON.stringify(t)===JSON.stringify(e)?t:e)}).catch(e=>{t.signal.aborted||o(e instanceof Error?e:Error(String(e)))}).finally(()=>{c(!1)}),()=>{t.abort()}},[e,r,f]);let h=(0,n.useCallback)((e,t)=>{m(e,t)&&p(n=>n?{...n,[e]:t}:{[e]:t})},[m]);return{schema:l,options:f,setOption:h,loading:s,error:a}}exports.useOptions=r;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { Options, OptionsSchema } from "../index.browser-CHLe3dau.cjs";
|
|
2
|
+
import { CapabilitiesResponse, Client } from "../client-Co98ZOqj.cjs";
|
|
3
|
+
import { UIMessage } from "ai";
|
|
4
|
+
|
|
5
|
+
//#region src/react/use-options.d.ts
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* useOptions is a hook that provides the selectable and selected options
|
|
9
|
+
* for a given agent.
|
|
10
|
+
*
|
|
11
|
+
* @param agent - The agent to use.
|
|
12
|
+
* @param messages - The messages to use.
|
|
13
|
+
* @returns The selectable and selected options.
|
|
14
|
+
*/
|
|
15
|
+
declare function useOptions({
|
|
16
|
+
agent,
|
|
17
|
+
capabilities,
|
|
18
|
+
messages
|
|
19
|
+
}: {
|
|
20
|
+
agent?: Pick<Client, "provideUIOptions">;
|
|
21
|
+
capabilities?: CapabilitiesResponse;
|
|
22
|
+
messages: UIMessage[];
|
|
23
|
+
}): {
|
|
24
|
+
schema: OptionsSchema<Options> | undefined;
|
|
25
|
+
options: Options | undefined;
|
|
26
|
+
setOption: (id: string, value: string) => void;
|
|
27
|
+
loading: boolean;
|
|
28
|
+
error: Error | undefined;
|
|
29
|
+
};
|
|
30
|
+
//#endregion
|
|
31
|
+
export { useOptions };
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { Options, OptionsSchema } from "../index.browser-Db4eudpn.js";
|
|
2
|
+
import { CapabilitiesResponse, Client } from "../client-J5gD4j_a.js";
|
|
3
|
+
import { UIMessage } from "ai";
|
|
4
|
+
|
|
5
|
+
//#region src/react/use-options.d.ts
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* useOptions is a hook that provides the selectable and selected options
|
|
9
|
+
* for a given agent.
|
|
10
|
+
*
|
|
11
|
+
* @param agent - The agent to use.
|
|
12
|
+
* @param messages - The messages to use.
|
|
13
|
+
* @returns The selectable and selected options.
|
|
14
|
+
*/
|
|
15
|
+
declare function useOptions({
|
|
16
|
+
agent,
|
|
17
|
+
capabilities,
|
|
18
|
+
messages
|
|
19
|
+
}: {
|
|
20
|
+
agent?: Pick<Client, "provideUIOptions">;
|
|
21
|
+
capabilities?: CapabilitiesResponse;
|
|
22
|
+
messages: UIMessage[];
|
|
23
|
+
}): {
|
|
24
|
+
schema: OptionsSchema<Options> | undefined;
|
|
25
|
+
options: Options | undefined;
|
|
26
|
+
setOption: (id: string, value: string) => void;
|
|
27
|
+
loading: boolean;
|
|
28
|
+
error: Error | undefined;
|
|
29
|
+
};
|
|
30
|
+
//#endregion
|
|
31
|
+
export { useOptions };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"../client-BbZudkEc.js";import{lastUIOptions as e}from"../index.browser-Dj8kjB6X.js";import{useCallback as t,useEffect as n,useMemo as r,useState as i}from"react";function a({agent:a,capabilities:o,messages:s}){let[c,l]=i(void 0),[u,d]=i(!0),[f,p]=i(void 0),m=r(()=>e(s),[s]),[h,g]=i(void 0),_=t((e,t)=>{if(!f)return!1;let n=f[e];return n?n.values.some(e=>e.id===t):!1},[f]);n(()=>{if(!m&&!f){g(void 0);return}g(e=>{let t={...m,...e};for(let[e,n]of Object.entries(t))_(e,n)||delete t[e];for(let[e,n]of Object.entries(f??{}))t[e]||(t[e]=n.defaultValue);return t})},[m,f,_]),n(()=>{if(o&&!o.options||!a){p(void 0),g(void 0),l(void 0);return}let e=new AbortController;return d(!0),l(void 0),a.provideUIOptions(h?{selectedOptions:h}:{},{signal:e.signal}).then(t=>{e.signal.aborted||p(e=>JSON.stringify(e)===JSON.stringify(t)?e:t)}).catch(t=>{e.signal.aborted||l(t instanceof Error?t:Error(String(t)))}).finally(()=>{d(!1)}),()=>{e.abort()}},[a,o,h]);let v=t((e,t)=>{_(e,t)&&g(n=>n?{...n,[e]:t}:{[e]:t})},[_]);return{schema:f,options:h,setOption:v,loading:u,error:c}}export{a as useOptions};
|