@waniwani/sdk 0.4.7-beta.1 → 0.4.7

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.
@@ -298,6 +298,12 @@ interface ChatOptions {
298
298
  interface NextJsHandlerOptions {
299
299
  /** Chat handler configuration */
300
300
  chat?: ChatOptions;
301
+ /**
302
+ * Identifies this chatbar instance in analytics.
303
+ * Use a descriptive name like "hamilton-support" or "pricing-page".
304
+ * Shows up as `source` on tracked events.
305
+ */
306
+ source: string;
301
307
  /**
302
308
  * Enable verbose debug logging for all handler steps.
303
309
  * Logs request details, response codes, resolved URLs, and caught errors.
@@ -336,6 +342,6 @@ interface NextJsHandlerResult {
336
342
  * });
337
343
  * ```
338
344
  */
339
- declare function toNextJsHandler(client: WaniWaniClient, options?: NextJsHandlerOptions): NextJsHandlerResult;
345
+ declare function toNextJsHandler(client: WaniWaniClient, options: NextJsHandlerOptions): NextJsHandlerResult;
340
346
 
341
347
  export { type NextJsHandlerOptions, type NextJsHandlerResult, toNextJsHandler };
@@ -1,10 +1,10 @@
1
- function S(t,e){return e?(...o)=>console.log(`[waniwani:${t}]`,...o):()=>{}}var y=class extends Error{constructor(o,a){super(o);this.status=a;this.name="WaniWaniError"}};function O(t){let e=t.headers,o=e.get("x-vercel-ip-city")??e.get("cf-ipcity")??void 0,a=o?$(o):void 0,n=e.get("x-vercel-ip-country")??e.get("cf-ipcountry")??void 0,m=e.get("x-vercel-ip-country-region")??void 0,f=e.get("x-vercel-ip-latitude")??e.get("cf-iplatitude")??void 0,s=e.get("x-vercel-ip-longitude")??e.get("cf-iplongitude")??void 0,r=e.get("x-vercel-ip-timezone")??e.get("cf-iptimezone")??void 0,i=e.get("x-real-ip")??e.get("x-forwarded-for")?.split(",")[0]?.trim()??e.get("cf-connecting-ip")??void 0;return{city:a,country:n,countryRegion:m,latitude:f,longitude:s,timezone:r,ip:i}}function $(t){try{return decodeURIComponent(t)}catch{return t}}function T(t){if(!t)return!1;let e=Array.isArray(t.content)&&t.content.length>0,o=typeof t.structuredContent=="object"&&t.structuredContent!==null&&Object.keys(t.structuredContent).length>0;return e||o}function I(t){if(!T(t))return"";let e=["## Widget Model Context","This hidden context was supplied by an MCP App via `ui/update-model-context`.","Use it for the next assistant turn only. If it includes flow continuation or tool-call instructions, follow them exactly."];if(t.content?.length){let o=t.content.map(a=>a.type==="text"&&typeof a.text=="string"?a.text.trim():JSON.stringify(a,null,2)).filter(Boolean).join(`
1
+ function v(t,e){return e?(...r)=>console.log(`[waniwani:${t}]`,...r):()=>{}}var x=class extends Error{constructor(r,a){super(r);this.status=a;this.name="WaniWaniError"}};function I(t){let e=t.headers,r=e.get("x-vercel-ip-city")??e.get("cf-ipcity")??void 0,a=r?D(r):void 0,n=e.get("x-vercel-ip-country")??e.get("cf-ipcountry")??void 0,m=e.get("x-vercel-ip-country-region")??void 0,f=e.get("x-vercel-ip-latitude")??e.get("cf-iplatitude")??void 0,s=e.get("x-vercel-ip-longitude")??e.get("cf-iplongitude")??void 0,c=e.get("x-vercel-ip-timezone")??e.get("cf-iptimezone")??void 0,o=e.get("x-real-ip")??e.get("x-forwarded-for")?.split(",")[0]?.trim()??e.get("cf-connecting-ip")??void 0;return{city:a,country:n,countryRegion:m,latitude:f,longitude:s,timezone:c,ip:o}}function D(t){try{return decodeURIComponent(t)}catch{return t}}function H(t){if(!t)return!1;let e=Array.isArray(t.content)&&t.content.length>0,r=typeof t.structuredContent=="object"&&t.structuredContent!==null&&Object.keys(t.structuredContent).length>0;return e||r}function N(t){if(!H(t))return"";let e=["## Widget Model Context","This hidden context was supplied by an MCP App via `ui/update-model-context`.","Use it for the next assistant turn only. If it includes flow continuation or tool-call instructions, follow them exactly."];if(t.content?.length){let r=t.content.map(a=>a.type==="text"&&typeof a.text=="string"?a.text.trim():JSON.stringify(a,null,2)).filter(Boolean).join(`
2
2
 
3
- `);o&&e.push(`Content blocks:
4
- ${o}`)}return t.structuredContent&&Object.keys(t.structuredContent).length>0&&e.push(`Structured content JSON:
3
+ `);r&&e.push(`Content blocks:
4
+ ${r}`)}return t.structuredContent&&Object.keys(t.structuredContent).length>0&&e.push(`Structured content JSON:
5
5
  ${JSON.stringify(t.structuredContent,null,2)}`),e.join(`
6
6
 
7
- `)}function N(t,e){if(!T(e))return t;let o=I(e);return o?[t,o].filter(Boolean).join(`
7
+ `)}function W(t,e){if(!H(e))return t;let r=N(e);return r?[t,r].filter(Boolean).join(`
8
8
 
9
- `):t}function W(t){let{apiKey:e,baseUrl:o,systemPrompt:a,maxSteps:n,beforeRequest:m,mcpServerUrl:f,resolveConfig:s,debug:r}=t,i=S("chat",r);return async function(g){i("\u2192 POST",g.url);try{let c=await g.json(),l=c.messages??[],d=c.sessionId,M=c.modelContext,u=a,h=c.visitorContext??null,U=O(g),R={geo:U,client:h};if(i("body parsed \u2014 messages:",l.length,"sessionId:",d??"(none)","geo:",JSON.stringify(U)),m){i("running beforeRequest hook");try{let p=await m({messages:l,sessionId:d,modelContext:M,request:g,visitor:R});p&&(p.messages&&(l=p.messages),p.systemPrompt!==void 0&&(u=p.systemPrompt),p.sessionId!==void 0&&(d=p.sessionId),p.modelContext!==void 0&&(M=p.modelContext)),i("beforeRequest hook done \u2014 messages:",l.length,"sessionId:",d??"(none)")}catch(p){console.error("[waniwani:chat] beforeRequest hook error:",p);let A=p instanceof y?p.status:400,_=p instanceof Error?p.message:"Request rejected";return i("\u2190 returning",A,"from hook error"),Response.json({error:_},{status:A})}}let w=f??(await s()).mcpServerUrl;i("mcpServerUrl:",w),u=N(u,M);let H=`${o}/api/mcp/chat`;i("forwarding to",H);let j=g.headers.get("user-agent"),C=await fetch(H,{method:"POST",headers:{"Content-Type":"application/json",...e?{Authorization:`Bearer ${e}`}:{},...j?{"X-Client-User-Agent":j}:{}},body:JSON.stringify({messages:l,mcpServerUrl:w,sessionId:d,systemPrompt:u,maxSteps:n,visitor:R}),signal:g.signal});if(i("upstream response status:",C.status),!C.ok){let p=await C.text().catch(()=>"");return i("\u2190 returning",C.status,"upstream error:",p),new Response(p,{status:C.status,headers:{"Content-Type":C.headers.get("Content-Type")??"application/json"}})}let k=new Headers({"Content-Type":C.headers.get("Content-Type")??"text/event-stream"}),E=C.headers.get("x-session-id");return E&&k.set("x-session-id",E),i("\u2190 streaming response",C.status,"body null?",C.body===null),new Response(C.body,{status:C.status,headers:k})}catch(c){console.error("[waniwani:chat] handler error:",c);let l=c instanceof Error?c.message:"Unknown error occurred",d=c instanceof y?c.status:500;return i("\u2190 returning",d,"from caught error"),Response.json({error:l},{status:d})}}}function J(t){let{mcpServerUrl:e,resolveConfig:o,debug:a}=t,n=S("resource",a);return async function(f){n("\u2192 GET",f.toString());try{let s=f.searchParams.get("uri");if(n("uri:",s??"(missing)"),!s)return n("\u2190 400 missing uri"),Response.json({error:"Missing uri query parameter"},{status:400});let r=e??(await o()).mcpServerUrl;n("mcpServerUrl:",r);let i,x;try{[{createMCPClient:i},{StreamableHTTPClientTransport:x}]=await Promise.all([import("@ai-sdk/mcp"),import("@modelcontextprotocol/sdk/client/streamableHttp.js")]),n("MCP deps loaded")}catch(c){return console.error("[waniwani:resource] MCP deps import failed:",c),Response.json({error:"MCP resource handler requires @ai-sdk/mcp and @modelcontextprotocol/sdk. Install them to enable resource serving."},{status:501})}n("creating MCP client for",r);let g=await i({transport:new x(new URL(r))});try{n("reading resource:",s);let c=await g.readResource({uri:s});n("resource contents count:",c.contents.length);let l=c.contents[0];if(!l)return n("\u2190 404 resource not found"),Response.json({error:"Resource not found"},{status:404});let d;return"text"in l&&typeof l.text=="string"?d=l.text:"blob"in l&&typeof l.blob=="string"&&(d=atob(l.blob)),d?(n("\u2190 200 HTML length:",d.length),new Response(d,{headers:{"Content-Type":"text/html","Cache-Control":"private, max-age=300"}})):(n("\u2190 404 resource has no content, keys:",Object.keys(l)),Response.json({error:"Resource has no content"},{status:404}))}finally{await g.close(),n("MCP client closed")}}catch(s){console.error("[waniwani:resource] handler error:",s);let r=s instanceof Error?s.message:"Unknown error occurred",i=s instanceof y?s.status:500;return n("\u2190 returning",i,"from caught error"),Response.json({error:r},{status:i})}}}function L(t){let{mcpServerUrl:e,resolveConfig:o,debug:a}=t,n=S("tool",a);return async function(f){n("\u2192 POST",f.url);try{let s=await f.json(),{name:r,arguments:i}=s,x=f.headers.get("x-session-id")?.trim();if(!r||typeof r!="string")return n("\u2190 400 missing tool name"),Response.json({error:"Missing tool name"},{status:400});n("tool:",r,"args:",JSON.stringify(i),"sessionId:",x||"(none)");let g=e??(await o()).mcpServerUrl;n("mcpServerUrl:",g);let c,l;try{[{Client:c},{StreamableHTTPClientTransport:l}]=await Promise.all([import("@modelcontextprotocol/sdk/client/index.js"),import("@modelcontextprotocol/sdk/client/streamableHttp.js")]),n("MCP deps loaded")}catch(u){return console.error("[waniwani:tool] MCP deps import failed:",u),Response.json({error:"MCP tool handler requires @modelcontextprotocol/sdk. Install it to enable tool calls."},{status:501})}n("creating MCP client for",g);let d=new l(new URL(g)),M=new c({name:"waniwani-tool-caller",version:"1.0.0"});await M.connect(d);try{n("calling tool:",r);let u=await M.callTool({name:r,arguments:i??{},...x?{_meta:{"waniwani/sessionId":x}}:{}});return n("tool result received"),Response.json({content:u.content,structuredContent:u.structuredContent,_meta:u._meta,isError:u.isError})}finally{await M.close(),n("MCP client closed")}}catch(s){console.error("[waniwani:tool] handler error:",s);let r=s instanceof Error?s.message:"Unknown error occurred",i=s instanceof y?s.status:500;return n("\u2190 returning",i,"from caught error"),Response.json({error:r},{status:i})}}}var D=300*1e3;function B(t,e){let o=null,a=null;return async function(){if(o&&Date.now()<o.expiresAt)return o.config;if(a)return a;a=(async()=>{if(!e)throw new y("WANIWANI_API_KEY is required for createChatHandler",401);let m=await fetch(`${t}/api/mcp/environments/config`,{method:"GET",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});if(!m.ok){let s=await m.text().catch(()=>"");throw new y(`Failed to resolve MCP environment config: ${m.status} ${s}`,m.status)}let f=await m.json();return o={config:f,expiresAt:Date.now()+D},f})();try{return await a}finally{a=null}}}function v(t,e){return new Response(JSON.stringify(t),{headers:{"Content-Type":"application/json"},status:e})}function G(t={}){let{apiKey:e=process.env.WANIWANI_API_KEY,baseUrl:o="https://app.waniwani.ai",systemPrompt:a,maxSteps:n=5,beforeRequest:m,mcpServerUrl:f,debug:s=!1}=t,r=S("router",s),i=B(o,e),x=W({apiKey:e,baseUrl:o,systemPrompt:a,maxSteps:n,beforeRequest:m,mcpServerUrl:f,resolveConfig:i,debug:s}),g=J({mcpServerUrl:f,resolveConfig:i,debug:s}),c=L({mcpServerUrl:f,resolveConfig:i,debug:s});async function l(){return v({debug:s},200)}async function d(u){r("\u2192 GET",u.url);try{let h=new URL(u.url),R=h.pathname.replace(/\/$/,"").split("/").filter(Boolean).at(-1);if(r("pathname:",h.pathname,"subRoute:",R),R==="resource"){r("dispatching to resource handler");let w=await g(h);return r("\u2190 resource handler returned",w.status),w}if(R==="config"){r("dispatching to config handler");let w=await l();return r("\u2190 config handler returned",w.status),w}return r("\u2190 404 no matching sub-route for",R),v({error:"Not found"},404)}catch(h){console.error("[waniwani:router] GET handler error:",h);let U=h instanceof Error?h.message:"Unknown error occurred";return r("\u2190 500 from caught error"),v({error:U},500)}}async function M(u){r("\u2192 POST",u.url);try{let h=new URL(u.url),R=h.pathname.replace(/\/$/,"").split("/").filter(Boolean).at(-1);if(r("pathname:",h.pathname,"subRoute:",R),R==="tool"){r("dispatching to tool handler");let w=await c(u);return r("\u2190 tool handler returned",w.status),w}return r("dispatching to chat handler"),x(u)}catch(h){console.error("[waniwani:router] POST handler error:",h);let U=h instanceof Error?h.message:"Unknown error occurred";return r("\u2190 500 from caught error"),v({error:U},500)}}return{handleChat:x,handleResource:g,handleTool:c,routeGet:d,routePost:M}}function ve(t,e){let{apiKey:o,baseUrl:a}=t._config,n=e?.debug??process.env.WANIWANI_DEBUG==="1",m=G({...e?.chat,apiKey:o,baseUrl:a,debug:n});return{POST:m.routePost,GET:m.routeGet}}export{ve as toNextJsHandler};
9
+ `):t}function J(t){let{apiKey:e,baseUrl:r,source:a,systemPrompt:n,maxSteps:m,beforeRequest:f,mcpServerUrl:s,resolveConfig:c,debug:o}=t,l=v("chat",o);return async function(d){l("\u2192 POST",d.url);try{let i=await d.json(),p=i.messages??[],h=i.sessionId,C=i.modelContext,y=n,g=i.visitorContext??null,S=I(d),P={geo:S,client:g};if(l("body parsed \u2014 messages:",p.length,"sessionId:",h??"(none)","geo:",JSON.stringify(S)),f){l("running beforeRequest hook");try{let u=await f({messages:p,sessionId:h,modelContext:C,request:d,visitor:P});u&&(u.messages&&(p=u.messages),u.systemPrompt!==void 0&&(y=u.systemPrompt),u.sessionId!==void 0&&(h=u.sessionId),u.modelContext!==void 0&&(C=u.modelContext)),l("beforeRequest hook done \u2014 messages:",p.length,"sessionId:",h??"(none)")}catch(u){console.error("[waniwani:chat] beforeRequest hook error:",u);let O=u instanceof x?u.status:400,$=u instanceof Error?u.message:"Request rejected";return l("\u2190 returning",O,"from hook error"),Response.json({error:$},{status:O})}}let R=s??(await c()).mcpServerUrl;l("mcpServerUrl:",R),y=W(y,C);let j=`${r}/api/mcp/chat`;l("forwarding to",j);let k=d.headers.get("user-agent"),w=await fetch(j,{method:"POST",headers:{"Content-Type":"application/json",...e?{Authorization:`Bearer ${e}`}:{},...k?{"X-Client-User-Agent":k}:{}},body:JSON.stringify({messages:p,mcpServerUrl:R,sessionId:h,source:a,systemPrompt:y,maxSteps:m,visitor:P}),signal:d.signal});if(l("upstream response status:",w.status),!w.ok){let u=await w.text().catch(()=>"");return l("\u2190 returning",w.status,"upstream error:",u),new Response(u,{status:w.status,headers:{"Content-Type":w.headers.get("Content-Type")??"application/json"}})}let E=new Headers({"Content-Type":w.headers.get("Content-Type")??"text/event-stream"}),A=w.headers.get("x-session-id");return A&&E.set("x-session-id",A),l("\u2190 streaming response",w.status,"body null?",w.body===null),new Response(w.body,{status:w.status,headers:E})}catch(i){console.error("[waniwani:chat] handler error:",i);let p=i instanceof Error?i.message:"Unknown error occurred",h=i instanceof x?i.status:500;return l("\u2190 returning",h,"from caught error"),Response.json({error:p},{status:h})}}}function L(t){let{mcpServerUrl:e,resolveConfig:r,debug:a}=t,n=v("resource",a);return async function(f){n("\u2192 GET",f.toString());try{let s=f.searchParams.get("uri");if(n("uri:",s??"(missing)"),!s)return n("\u2190 400 missing uri"),Response.json({error:"Missing uri query parameter"},{status:400});let c=e??(await r()).mcpServerUrl;n("mcpServerUrl:",c);let o,l;try{[{createMCPClient:o},{StreamableHTTPClientTransport:l}]=await Promise.all([import("@ai-sdk/mcp"),import("@modelcontextprotocol/sdk/client/streamableHttp.js")]),n("MCP deps loaded")}catch(d){return console.error("[waniwani:resource] MCP deps import failed:",d),Response.json({error:"MCP resource handler requires @ai-sdk/mcp and @modelcontextprotocol/sdk. Install them to enable resource serving."},{status:501})}n("creating MCP client for",c);let b=await o({transport:new l(new URL(c))});try{n("reading resource:",s);let d=await b.readResource({uri:s});n("resource contents count:",d.contents.length);let i=d.contents[0];if(!i)return n("\u2190 404 resource not found"),Response.json({error:"Resource not found"},{status:404});let p;return"text"in i&&typeof i.text=="string"?p=i.text:"blob"in i&&typeof i.blob=="string"&&(p=atob(i.blob)),p?(n("\u2190 200 HTML length:",p.length),new Response(p,{headers:{"Content-Type":"text/html","Cache-Control":"private, max-age=300"}})):(n("\u2190 404 resource has no content, keys:",Object.keys(i)),Response.json({error:"Resource has no content"},{status:404}))}finally{await b.close(),n("MCP client closed")}}catch(s){console.error("[waniwani:resource] handler error:",s);let c=s instanceof Error?s.message:"Unknown error occurred",o=s instanceof x?s.status:500;return n("\u2190 returning",o,"from caught error"),Response.json({error:c},{status:o})}}}function B(t){let{mcpServerUrl:e,resolveConfig:r,debug:a}=t,n=v("tool",a);return async function(f){n("\u2192 POST",f.url);try{let s=await f.json(),{name:c,arguments:o}=s,l=f.headers.get("x-session-id")?.trim();if(!c||typeof c!="string")return n("\u2190 400 missing tool name"),Response.json({error:"Missing tool name"},{status:400});n("tool:",c,"args:",JSON.stringify(o),"sessionId:",l||"(none)");let b=e??(await r()).mcpServerUrl;n("mcpServerUrl:",b);let d,i;try{[{Client:d},{StreamableHTTPClientTransport:i}]=await Promise.all([import("@modelcontextprotocol/sdk/client/index.js"),import("@modelcontextprotocol/sdk/client/streamableHttp.js")]),n("MCP deps loaded")}catch(C){return console.error("[waniwani:tool] MCP deps import failed:",C),Response.json({error:"MCP tool handler requires @modelcontextprotocol/sdk. Install it to enable tool calls."},{status:501})}n("creating MCP client for",b);let p=new i(new URL(b)),h=new d({name:"waniwani-tool-caller",version:"1.0.0"});await h.connect(p);try{n("calling tool:",c);let C=await h.callTool({name:c,arguments:o??{},...l?{_meta:{"waniwani/sessionId":l}}:{}});return n("tool result received"),Response.json({content:C.content,structuredContent:C.structuredContent,_meta:C._meta,isError:C.isError})}finally{await h.close(),n("MCP client closed")}}catch(s){console.error("[waniwani:tool] handler error:",s);let c=s instanceof Error?s.message:"Unknown error occurred",o=s instanceof x?s.status:500;return n("\u2190 returning",o,"from caught error"),Response.json({error:c},{status:o})}}}var q=300*1e3;function G(t,e){let r=null,a=null;return async function(){if(r&&Date.now()<r.expiresAt)return r.config;if(a)return a;a=(async()=>{if(!e)throw new x("WANIWANI_API_KEY is required for createChatHandler",401);let m=await fetch(`${t}/api/mcp/environments/config`,{method:"GET",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});if(!m.ok){let s=await m.text().catch(()=>"");throw new x(`Failed to resolve MCP environment config: ${m.status} ${s}`,m.status)}let f=await m.json();return r={config:f,expiresAt:Date.now()+q},f})();try{return await a}finally{a=null}}}function T(t,e){return new Response(JSON.stringify(t),{headers:{"Content-Type":"application/json"},status:e})}function _(t={}){let{apiKey:e=process.env.WANIWANI_API_KEY,baseUrl:r="https://app.waniwani.ai",source:a,systemPrompt:n,maxSteps:m=5,beforeRequest:f,mcpServerUrl:s,debug:c=!1}=t,o=v("router",c),l=G(r,e),b=J({apiKey:e,baseUrl:r,source:a,systemPrompt:n,maxSteps:m,beforeRequest:f,mcpServerUrl:s,resolveConfig:l,debug:c}),d=L({mcpServerUrl:s,resolveConfig:l,debug:c}),i=B({mcpServerUrl:s,resolveConfig:l,debug:c});async function p(){return T({debug:c},200)}async function h(y){o("\u2192 GET",y.url);try{let g=new URL(y.url),P=g.pathname.replace(/\/$/,"").split("/").filter(Boolean).at(-1);if(o("pathname:",g.pathname,"subRoute:",P),P==="resource"){o("dispatching to resource handler");let R=await d(g);return o("\u2190 resource handler returned",R.status),R}if(P==="config"){o("dispatching to config handler");let R=await p();return o("\u2190 config handler returned",R.status),R}return o("\u2190 404 no matching sub-route for",P),T({error:"Not found"},404)}catch(g){console.error("[waniwani:router] GET handler error:",g);let S=g instanceof Error?g.message:"Unknown error occurred";return o("\u2190 500 from caught error"),T({error:S},500)}}async function C(y){o("\u2192 POST",y.url);try{let g=new URL(y.url),P=g.pathname.replace(/\/$/,"").split("/").filter(Boolean).at(-1);if(o("pathname:",g.pathname,"subRoute:",P),P==="tool"){o("dispatching to tool handler");let R=await i(y);return o("\u2190 tool handler returned",R.status),R}return o("dispatching to chat handler"),b(y)}catch(g){console.error("[waniwani:router] POST handler error:",g);let S=g instanceof Error?g.message:"Unknown error occurred";return o("\u2190 500 from caught error"),T({error:S},500)}}return{handleChat:b,handleResource:d,handleTool:i,routeGet:h,routePost:C}}function Te(t,e){let{apiKey:r,baseUrl:a}=t._config,n=e?.debug??process.env.WANIWANI_DEBUG==="1",m=_({...e?.chat,apiKey:r,baseUrl:a,source:e?.source,debug:n});return{POST:m.routePost,GET:m.routeGet}}export{Te as toNextJsHandler};
10
10
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/utils/logger.ts","../../../src/error.ts","../../../src/chat/server/geo.ts","../../../src/shared/model-context.ts","../../../src/chat/server/model-context.ts","../../../src/chat/server/handle-chat.ts","../../../src/chat/server/handle-resource.ts","../../../src/chat/server/handle-tool.ts","../../../src/chat/server/mcp-config-resolver.ts","../../../src/chat/server/api-handler.ts","../../../src/chat/server/next-js/index.ts"],"sourcesContent":["/**\n * Creates a namespaced logger that writes to console.log when enabled,\n * or is a no-op when disabled.\n *\n * @example\n * const log = createLogger(\"chat\", debug);\n * log(\"→ POST\", request.url); // [waniwani:chat] → POST ...\n */\nexport function createLogger(\n\tnamespace: string,\n\tenabled: boolean,\n): (...args: unknown[]) => void {\n\treturn enabled\n\t\t? (...args: unknown[]) => console.log(`[waniwani:${namespace}]`, ...args)\n\t\t: () => {};\n}\n","// WaniWani SDK - Errors\n\nexport class WaniWaniError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic status: number,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"WaniWaniError\";\n\t}\n}\n","// Geo — Extract location metadata from platform request headers\n\n/**\n * Server-side geolocation extracted from platform headers (Vercel, Cloudflare).\n * All fields are optional — in local dev, no headers are present.\n */\nexport interface GeoLocation {\n\tcity?: string;\n\tcountry?: string;\n\tcountryRegion?: string;\n\tlatitude?: string;\n\tlongitude?: string;\n\ttimezone?: string;\n\tip?: string;\n}\n\n/**\n * Extracts geolocation from server-side request headers.\n *\n * Supports Vercel (`x-vercel-ip-*`), Cloudflare (`cf-ip*`, `cf-connecting-ip`),\n * and generic IP headers (`x-real-ip`, `x-forwarded-for`).\n *\n * Returns a `GeoLocation` with all fields optional (empty object in local dev).\n */\nexport function extractGeoFromHeaders(request: Request): GeoLocation {\n\tconst h = request.headers;\n\n\t// Vercel URL-encodes city names (e.g. \"S%C3%A3o%20Paulo\")\n\tconst rawCity = h.get(\"x-vercel-ip-city\") ?? h.get(\"cf-ipcity\") ?? undefined;\n\tconst city = rawCity ? safeDecodeURI(rawCity) : undefined;\n\n\tconst country =\n\t\th.get(\"x-vercel-ip-country\") ?? h.get(\"cf-ipcountry\") ?? undefined;\n\tconst countryRegion = h.get(\"x-vercel-ip-country-region\") ?? undefined;\n\tconst latitude =\n\t\th.get(\"x-vercel-ip-latitude\") ?? h.get(\"cf-iplatitude\") ?? undefined;\n\tconst longitude =\n\t\th.get(\"x-vercel-ip-longitude\") ?? h.get(\"cf-iplongitude\") ?? undefined;\n\tconst timezone =\n\t\th.get(\"x-vercel-ip-timezone\") ?? h.get(\"cf-iptimezone\") ?? undefined;\n\tconst ip =\n\t\th.get(\"x-real-ip\") ??\n\t\th.get(\"x-forwarded-for\")?.split(\",\")[0]?.trim() ??\n\t\th.get(\"cf-connecting-ip\") ??\n\t\tundefined;\n\n\treturn { city, country, countryRegion, latitude, longitude, timezone, ip };\n}\n\nfunction safeDecodeURI(value: string): string {\n\ttry {\n\t\treturn decodeURIComponent(value);\n\t} catch {\n\t\treturn value;\n\t}\n}\n","import type { ContentBlock } from \"@modelcontextprotocol/sdk/types.js\";\n\nexport type ModelContextContentBlock = ContentBlock;\n\nexport type ModelContextUpdate = {\n\tcontent?: ModelContextContentBlock[];\n\tstructuredContent?: Record<string, unknown>;\n};\n\nexport function hasModelContext(\n\tvalue: ModelContextUpdate | null | undefined,\n): value is ModelContextUpdate {\n\tif (!value) {\n\t\treturn false;\n\t}\n\tconst hasContent = Array.isArray(value.content) && value.content.length > 0;\n\tconst hasStructuredContent =\n\t\ttypeof value.structuredContent === \"object\" &&\n\t\tvalue.structuredContent !== null &&\n\t\tObject.keys(value.structuredContent).length > 0;\n\treturn hasContent || hasStructuredContent;\n}\n\nexport function mergeModelContext(\n\tcurrent: ModelContextUpdate | null | undefined,\n\tnext: ModelContextUpdate | null | undefined,\n): ModelContextUpdate | null {\n\tif (!hasModelContext(current) && !hasModelContext(next)) {\n\t\treturn null;\n\t}\n\tif (!hasModelContext(current)) {\n\t\treturn {\n\t\t\t...(next?.content ? { content: [...next.content] } : {}),\n\t\t\t...(next?.structuredContent\n\t\t\t\t? { structuredContent: { ...next.structuredContent } }\n\t\t\t\t: {}),\n\t\t};\n\t}\n\tif (!hasModelContext(next)) {\n\t\treturn {\n\t\t\t...(current.content ? { content: [...current.content] } : {}),\n\t\t\t...(current.structuredContent\n\t\t\t\t? { structuredContent: { ...current.structuredContent } }\n\t\t\t\t: {}),\n\t\t};\n\t}\n\n\treturn {\n\t\t...(current.content || next.content\n\t\t\t? { content: [...(current.content ?? []), ...(next.content ?? [])] }\n\t\t\t: {}),\n\t\t...(current.structuredContent || next.structuredContent\n\t\t\t? {\n\t\t\t\t\tstructuredContent: {\n\t\t\t\t\t\t...(current.structuredContent ?? {}),\n\t\t\t\t\t\t...(next.structuredContent ?? {}),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n\nexport function formatModelContextForPrompt(\n\tvalue: ModelContextUpdate | null | undefined,\n): string {\n\tif (!hasModelContext(value)) {\n\t\treturn \"\";\n\t}\n\n\tconst sections: string[] = [\n\t\t\"## Widget Model Context\",\n\t\t\"This hidden context was supplied by an MCP App via `ui/update-model-context`.\",\n\t\t\"Use it for the next assistant turn only. If it includes flow continuation or tool-call instructions, follow them exactly.\",\n\t];\n\n\tif (value.content?.length) {\n\t\tconst renderedBlocks = value.content\n\t\t\t.map((block) => {\n\t\t\t\tif (block.type === \"text\" && typeof block.text === \"string\") {\n\t\t\t\t\treturn block.text.trim();\n\t\t\t\t}\n\t\t\t\treturn JSON.stringify(block, null, 2);\n\t\t\t})\n\t\t\t.filter(Boolean)\n\t\t\t.join(\"\\n\\n\");\n\t\tif (renderedBlocks) {\n\t\t\tsections.push(`Content blocks:\\n${renderedBlocks}`);\n\t\t}\n\t}\n\n\tif (\n\t\tvalue.structuredContent &&\n\t\tObject.keys(value.structuredContent).length > 0\n\t) {\n\t\tsections.push(\n\t\t\t`Structured content JSON:\\n${JSON.stringify(value.structuredContent, null, 2)}`,\n\t\t);\n\t}\n\n\treturn sections.join(\"\\n\\n\");\n}\n","import {\n\tformatModelContextForPrompt,\n\thasModelContext,\n\ttype ModelContextUpdate,\n} from \"../../shared/model-context\";\n\nexport function applyModelContextToSystemPrompt(\n\tsystemPrompt: string | undefined,\n\tmodelContext: ModelContextUpdate | undefined,\n): string | undefined {\n\tif (!hasModelContext(modelContext)) {\n\t\treturn systemPrompt;\n\t}\n\n\tconst widgetContext = formatModelContextForPrompt(modelContext);\n\tif (!widgetContext) {\n\t\treturn systemPrompt;\n\t}\n\n\treturn [systemPrompt, widgetContext].filter(Boolean).join(\"\\n\\n\");\n}\n","// Handle Chat - Proxies chat requests to the WaniWani API\n\nimport { WaniWaniError } from \"../../error\";\nimport { createLogger } from \"../../utils/logger.js\";\nimport type {\n\tApiHandlerDeps,\n\tClientVisitorContext,\n\tVisitorMeta,\n} from \"./@types\";\nimport { extractGeoFromHeaders } from \"./geo\";\nimport { applyModelContextToSystemPrompt } from \"./model-context\";\n\nexport function createChatRequestHandler(deps: ApiHandlerDeps) {\n\tconst {\n\t\tapiKey,\n\t\tbaseUrl,\n\t\tsystemPrompt,\n\t\tmaxSteps,\n\t\tbeforeRequest,\n\t\tmcpServerUrl: mcpServerUrlOverride,\n\t\tresolveConfig,\n\t\tdebug,\n\t} = deps;\n\n\tconst log = createLogger(\"chat\", debug);\n\n\treturn async function handleChat(request: Request): Promise<Response> {\n\t\tlog(\"→ POST\", request.url);\n\t\ttry {\n\t\t\t// 1. Parse request body\n\t\t\tconst body = await request.json();\n\t\t\tlet messages = body.messages ?? [];\n\t\t\tlet sessionId: string | undefined = body.sessionId;\n\t\t\tlet modelContext = body.modelContext;\n\t\t\tlet effectiveSystemPrompt = systemPrompt;\n\n\t\t\t// Extract visitor context (client-side + server-side geo)\n\t\t\tconst clientVisitorContext: ClientVisitorContext | null =\n\t\t\t\tbody.visitorContext ?? null;\n\t\t\tconst geo = extractGeoFromHeaders(request);\n\t\t\tconst visitor: VisitorMeta = { geo, client: clientVisitorContext };\n\n\t\t\tlog(\n\t\t\t\t\"body parsed — messages:\",\n\t\t\t\tmessages.length,\n\t\t\t\t\"sessionId:\",\n\t\t\t\tsessionId ?? \"(none)\",\n\t\t\t\t\"geo:\",\n\t\t\t\tJSON.stringify(geo),\n\t\t\t);\n\n\t\t\t// 2. Run beforeRequest hook\n\t\t\tif (beforeRequest) {\n\t\t\t\tlog(\"running beforeRequest hook\");\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await beforeRequest({\n\t\t\t\t\t\tmessages,\n\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\tmodelContext,\n\t\t\t\t\t\trequest,\n\t\t\t\t\t\tvisitor,\n\t\t\t\t\t});\n\n\t\t\t\t\tif (result) {\n\t\t\t\t\t\tif (result.messages) {\n\t\t\t\t\t\t\tmessages = result.messages;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (result.systemPrompt !== undefined) {\n\t\t\t\t\t\t\teffectiveSystemPrompt = result.systemPrompt;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (result.sessionId !== undefined) {\n\t\t\t\t\t\t\tsessionId = result.sessionId;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (result.modelContext !== undefined) {\n\t\t\t\t\t\t\tmodelContext = result.modelContext;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tlog(\n\t\t\t\t\t\t\"beforeRequest hook done — messages:\",\n\t\t\t\t\t\tmessages.length,\n\t\t\t\t\t\t\"sessionId:\",\n\t\t\t\t\t\tsessionId ?? \"(none)\",\n\t\t\t\t\t);\n\t\t\t\t} catch (hookError) {\n\t\t\t\t\tconsole.error(\"[waniwani:chat] beforeRequest hook error:\", hookError);\n\t\t\t\t\tconst status =\n\t\t\t\t\t\thookError instanceof WaniWaniError ? hookError.status : 400;\n\t\t\t\t\tconst message =\n\t\t\t\t\t\thookError instanceof Error ? hookError.message : \"Request rejected\";\n\t\t\t\t\tlog(\"← returning\", status, \"from hook error\");\n\t\t\t\t\treturn Response.json({ error: message }, { status });\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// 3. Resolve MCP server URL\n\t\t\tconst mcpServerUrl =\n\t\t\t\tmcpServerUrlOverride ?? (await resolveConfig()).mcpServerUrl;\n\t\t\tlog(\"mcpServerUrl:\", mcpServerUrl);\n\t\t\teffectiveSystemPrompt = applyModelContextToSystemPrompt(\n\t\t\t\teffectiveSystemPrompt,\n\t\t\t\tmodelContext,\n\t\t\t);\n\n\t\t\t// 4. Forward to WaniWani API\n\t\t\tconst upstreamUrl = `${baseUrl}/api/mcp/chat`;\n\t\t\tlog(\"forwarding to\", upstreamUrl);\n\t\t\tconst clientUserAgent = request.headers.get(\"user-agent\");\n\n\t\t\tconst response = await fetch(upstreamUrl, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),\n\t\t\t\t\t...(clientUserAgent\n\t\t\t\t\t\t? { \"X-Client-User-Agent\": clientUserAgent }\n\t\t\t\t\t\t: {}),\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tmessages,\n\t\t\t\t\tmcpServerUrl,\n\t\t\t\t\tsessionId,\n\t\t\t\t\tsystemPrompt: effectiveSystemPrompt,\n\t\t\t\t\tmaxSteps,\n\t\t\t\t\tvisitor,\n\t\t\t\t}),\n\t\t\t\tsignal: request.signal,\n\t\t\t});\n\n\t\t\tlog(\"upstream response status:\", response.status);\n\n\t\t\tif (!response.ok) {\n\t\t\t\tconst errorBody = await response.text().catch(() => \"\");\n\t\t\t\tlog(\"← returning\", response.status, \"upstream error:\", errorBody);\n\t\t\t\treturn new Response(errorBody, {\n\t\t\t\t\tstatus: response.status,\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t\"Content-Type\":\n\t\t\t\t\t\t\tresponse.headers.get(\"Content-Type\") ?? \"application/json\",\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// 5. Stream the response back\n\t\t\tconst headers = new Headers({\n\t\t\t\t\"Content-Type\":\n\t\t\t\t\tresponse.headers.get(\"Content-Type\") ?? \"text/event-stream\",\n\t\t\t});\n\t\t\tconst upstreamSessionId = response.headers.get(\"x-session-id\");\n\t\t\tif (upstreamSessionId) {\n\t\t\t\theaders.set(\"x-session-id\", upstreamSessionId);\n\t\t\t}\n\n\t\t\tlog(\n\t\t\t\t\"← streaming response\",\n\t\t\t\tresponse.status,\n\t\t\t\t\"body null?\",\n\t\t\t\tresponse.body === null,\n\t\t\t);\n\t\t\treturn new Response(response.body, {\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconsole.error(\"[waniwani:chat] handler error:\", error);\n\t\t\tconst message =\n\t\t\t\terror instanceof Error ? error.message : \"Unknown error occurred\";\n\t\t\tconst status = error instanceof WaniWaniError ? error.status : 500;\n\t\t\tlog(\"← returning\", status, \"from caught error\");\n\t\t\treturn Response.json({ error: message }, { status });\n\t\t}\n\t};\n}\n","// Handle Resource - Serves MCP resource content (HTML widgets)\n\nimport { WaniWaniError } from \"../../error\";\nimport { createLogger } from \"../../utils/logger.js\";\nimport type { ResourceHandlerDeps } from \"./@types\";\n\nexport function createResourceHandler(deps: ResourceHandlerDeps) {\n\tconst { mcpServerUrl: mcpServerUrlOverride, resolveConfig, debug } = deps;\n\n\tconst log = createLogger(\"resource\", debug);\n\n\treturn async function handleResource(url: URL): Promise<Response> {\n\t\tlog(\"→ GET\", url.toString());\n\t\ttry {\n\t\t\tconst uri = url.searchParams.get(\"uri\");\n\t\t\tlog(\"uri:\", uri ?? \"(missing)\");\n\n\t\t\tif (!uri) {\n\t\t\t\tlog(\"← 400 missing uri\");\n\t\t\t\treturn Response.json(\n\t\t\t\t\t{ error: \"Missing uri query parameter\" },\n\t\t\t\t\t{ status: 400 },\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst mcpServerUrl =\n\t\t\t\tmcpServerUrlOverride ?? (await resolveConfig()).mcpServerUrl;\n\t\t\tlog(\"mcpServerUrl:\", mcpServerUrl);\n\n\t\t\t// Dynamic imports — these are optional peer dependencies\n\t\t\tlet createMCPClient: typeof import(\"@ai-sdk/mcp\")[\"createMCPClient\"];\n\t\t\tlet StreamableHTTPClientTransport: typeof import(\"@modelcontextprotocol/sdk/client/streamableHttp.js\")[\"StreamableHTTPClientTransport\"];\n\n\t\t\ttry {\n\t\t\t\t[{ createMCPClient }, { StreamableHTTPClientTransport }] =\n\t\t\t\t\tawait Promise.all([\n\t\t\t\t\t\timport(\"@ai-sdk/mcp\"),\n\t\t\t\t\t\timport(\"@modelcontextprotocol/sdk/client/streamableHttp.js\"),\n\t\t\t\t\t]);\n\t\t\t\tlog(\"MCP deps loaded\");\n\t\t\t} catch (importError) {\n\t\t\t\tconsole.error(\n\t\t\t\t\t\"[waniwani:resource] MCP deps import failed:\",\n\t\t\t\t\timportError,\n\t\t\t\t);\n\t\t\t\treturn Response.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror:\n\t\t\t\t\t\t\t\"MCP resource handler requires @ai-sdk/mcp and @modelcontextprotocol/sdk. Install them to enable resource serving.\",\n\t\t\t\t\t},\n\t\t\t\t\t{ status: 501 },\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlog(\"creating MCP client for\", mcpServerUrl);\n\t\t\tconst mcp = await createMCPClient({\n\t\t\t\ttransport: new StreamableHTTPClientTransport(new URL(mcpServerUrl)),\n\t\t\t});\n\n\t\t\ttry {\n\t\t\t\tlog(\"reading resource:\", uri);\n\t\t\t\tconst result = await mcp.readResource({ uri });\n\t\t\t\tlog(\"resource contents count:\", result.contents.length);\n\n\t\t\t\tconst content = result.contents[0];\n\t\t\t\tif (!content) {\n\t\t\t\t\tlog(\"← 404 resource not found\");\n\t\t\t\t\treturn Response.json(\n\t\t\t\t\t\t{ error: \"Resource not found\" },\n\t\t\t\t\t\t{ status: 404 },\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tlet html: string | undefined;\n\t\t\t\tif (\"text\" in content && typeof content.text === \"string\") {\n\t\t\t\t\thtml = content.text;\n\t\t\t\t} else if (\"blob\" in content && typeof content.blob === \"string\") {\n\t\t\t\t\thtml = atob(content.blob);\n\t\t\t\t}\n\n\t\t\t\tif (!html) {\n\t\t\t\t\tlog(\"← 404 resource has no content, keys:\", Object.keys(content));\n\t\t\t\t\treturn Response.json(\n\t\t\t\t\t\t{ error: \"Resource has no content\" },\n\t\t\t\t\t\t{ status: 404 },\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tlog(\"← 200 HTML length:\", html.length);\n\t\t\t\treturn new Response(html, {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t\"Content-Type\": \"text/html\",\n\t\t\t\t\t\t\"Cache-Control\": \"private, max-age=300\",\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} finally {\n\t\t\t\tawait mcp.close();\n\t\t\t\tlog(\"MCP client closed\");\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconsole.error(\"[waniwani:resource] handler error:\", error);\n\t\t\tconst message =\n\t\t\t\terror instanceof Error ? error.message : \"Unknown error occurred\";\n\t\t\tconst status = error instanceof WaniWaniError ? error.status : 500;\n\t\t\tlog(\"← returning\", status, \"from caught error\");\n\t\t\treturn Response.json({ error: message }, { status });\n\t\t}\n\t};\n}\n","// Handle Tool - Calls MCP server tools directly and returns JSON results\n\nimport { WaniWaniError } from \"../../error\";\nimport { createLogger } from \"../../utils/logger.js\";\nimport type { ResourceHandlerDeps } from \"./@types\";\n\nexport function createToolHandler(deps: ResourceHandlerDeps) {\n\tconst { mcpServerUrl: mcpServerUrlOverride, resolveConfig, debug } = deps;\n\n\tconst log = createLogger(\"tool\", debug);\n\n\treturn async function handleTool(request: Request): Promise<Response> {\n\t\tlog(\"→ POST\", request.url);\n\t\ttry {\n\t\t\tconst body = await request.json();\n\t\t\tconst { name, arguments: args } = body as {\n\t\t\t\tname: string;\n\t\t\t\targuments: Record<string, unknown>;\n\t\t\t};\n\t\t\tconst requestSessionId = request.headers.get(\"x-session-id\")?.trim();\n\n\t\t\tif (!name || typeof name !== \"string\") {\n\t\t\t\tlog(\"← 400 missing tool name\");\n\t\t\t\treturn Response.json({ error: \"Missing tool name\" }, { status: 400 });\n\t\t\t}\n\n\t\t\tlog(\n\t\t\t\t\"tool:\",\n\t\t\t\tname,\n\t\t\t\t\"args:\",\n\t\t\t\tJSON.stringify(args),\n\t\t\t\t\"sessionId:\",\n\t\t\t\trequestSessionId || \"(none)\",\n\t\t\t);\n\n\t\t\tconst mcpServerUrl =\n\t\t\t\tmcpServerUrlOverride ?? (await resolveConfig()).mcpServerUrl;\n\t\t\tlog(\"mcpServerUrl:\", mcpServerUrl);\n\n\t\t\t// Dynamic imports — these are optional peer dependencies\n\t\t\tlet Client: typeof import(\"@modelcontextprotocol/sdk/client/index.js\")[\"Client\"];\n\t\t\tlet StreamableHTTPClientTransport: typeof import(\"@modelcontextprotocol/sdk/client/streamableHttp.js\")[\"StreamableHTTPClientTransport\"];\n\n\t\t\ttry {\n\t\t\t\t[{ Client }, { StreamableHTTPClientTransport }] = await Promise.all([\n\t\t\t\t\timport(\"@modelcontextprotocol/sdk/client/index.js\"),\n\t\t\t\t\timport(\"@modelcontextprotocol/sdk/client/streamableHttp.js\"),\n\t\t\t\t]);\n\t\t\t\tlog(\"MCP deps loaded\");\n\t\t\t} catch (importError) {\n\t\t\t\tconsole.error(\"[waniwani:tool] MCP deps import failed:\", importError);\n\t\t\t\treturn Response.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror:\n\t\t\t\t\t\t\t\"MCP tool handler requires @modelcontextprotocol/sdk. Install it to enable tool calls.\",\n\t\t\t\t\t},\n\t\t\t\t\t{ status: 501 },\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlog(\"creating MCP client for\", mcpServerUrl);\n\t\t\tconst transport = new StreamableHTTPClientTransport(\n\t\t\t\tnew URL(mcpServerUrl),\n\t\t\t);\n\t\t\tconst client = new Client({\n\t\t\t\tname: \"waniwani-tool-caller\",\n\t\t\t\tversion: \"1.0.0\",\n\t\t\t});\n\t\t\tawait client.connect(transport);\n\n\t\t\ttry {\n\t\t\t\tlog(\"calling tool:\", name);\n\t\t\t\tconst result = await client.callTool({\n\t\t\t\t\tname,\n\t\t\t\t\targuments: args ?? {},\n\t\t\t\t\t...(requestSessionId\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t_meta: {\n\t\t\t\t\t\t\t\t\t\"waniwani/sessionId\": requestSessionId,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t} as {\n\t\t\t\t\tname: string;\n\t\t\t\t\targuments: Record<string, unknown>;\n\t\t\t\t\t_meta?: Record<string, unknown>;\n\t\t\t\t});\n\t\t\t\tlog(\"tool result received\");\n\n\t\t\t\treturn Response.json({\n\t\t\t\t\tcontent: result.content,\n\t\t\t\t\tstructuredContent: result.structuredContent,\n\t\t\t\t\t_meta: result._meta,\n\t\t\t\t\tisError: result.isError,\n\t\t\t\t});\n\t\t\t} finally {\n\t\t\t\tawait client.close();\n\t\t\t\tlog(\"MCP client closed\");\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconsole.error(\"[waniwani:tool] handler error:\", error);\n\t\t\tconst message =\n\t\t\t\terror instanceof Error ? error.message : \"Unknown error occurred\";\n\t\t\tconst status = error instanceof WaniWaniError ? error.status : 500;\n\t\t\tlog(\"← returning\", status, \"from caught error\");\n\t\t\treturn Response.json({ error: message }, { status });\n\t\t}\n\t};\n}\n","// MCP Config Resolver - Lazy-loads and caches MCP environment config\n\nimport { WaniWaniError } from \"../../error\";\n\ninterface McpEnvironmentConfig {\n\tmcpServerUrl: string;\n}\n\nconst TTL_MS = 5 * 60 * 1000; // 5 minutes\n\nexport function createMcpConfigResolver(\n\tbaseUrl: string,\n\tapiKey: string | undefined,\n) {\n\tlet cached: { config: McpEnvironmentConfig; expiresAt: number } | null = null;\n\tlet inflight: Promise<McpEnvironmentConfig> | null = null;\n\n\treturn async function resolve(): Promise<McpEnvironmentConfig> {\n\t\tif (cached && Date.now() < cached.expiresAt) {\n\t\t\treturn cached.config;\n\t\t}\n\n\t\t// Deduplicate concurrent requests (cold start scenario)\n\t\tif (inflight) {\n\t\t\treturn inflight;\n\t\t}\n\n\t\tinflight = (async () => {\n\t\t\tif (!apiKey) {\n\t\t\t\tthrow new WaniWaniError(\n\t\t\t\t\t\"WANIWANI_API_KEY is required for createChatHandler\",\n\t\t\t\t\t401,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst response = await fetch(`${baseUrl}/api/mcp/environments/config`, {\n\t\t\t\tmethod: \"GET\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tif (!response.ok) {\n\t\t\t\tconst body = await response.text().catch(() => \"\");\n\t\t\t\tthrow new WaniWaniError(\n\t\t\t\t\t`Failed to resolve MCP environment config: ${response.status} ${body}`,\n\t\t\t\t\tresponse.status,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst data = (await response.json()) as McpEnvironmentConfig;\n\t\t\tcached = { config: data, expiresAt: Date.now() + TTL_MS };\n\t\t\treturn data;\n\t\t})();\n\n\t\ttry {\n\t\t\treturn await inflight;\n\t\t} finally {\n\t\t\tinflight = null;\n\t\t}\n\t};\n}\n","// API Handler - Composes chat and resource handlers into a unified API handler\n\nimport { createLogger } from \"../../utils/logger.js\";\nimport type { ApiHandler, ApiHandlerOptions } from \"./@types\";\nimport { createChatRequestHandler } from \"./handle-chat\";\nimport { createResourceHandler } from \"./handle-resource\";\nimport { createToolHandler } from \"./handle-tool\";\nimport { createMcpConfigResolver } from \"./mcp-config-resolver\";\n\n/**\n * Create a JSON response with the given data and status code.\n * @param data - The data to be serialized to JSON.\n * @param status - The HTTP status code to be returned.\n * @returns A Response object with the JSON data and the given status code.\n */\nfunction jsonResponse(data: object, status: number): Response {\n\treturn new Response(JSON.stringify(data), {\n\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\tstatus,\n\t});\n}\n\n/**\n * Create a framework-agnostic API handler for chat and MCP resources.\n *\n * Returns an object with handler methods that can be wired into\n * any framework (Next.js, Hono, Express, etc.):\n *\n * - `handleChat(request)` → proxies chat messages to WaniWani API\n * - `handleResource(url)` → serves MCP resource content (HTML widgets)\n * - `routeGet(request)` → routes GET sub-paths (e.g. /resource)\n *\n * @example\n * ```typescript\n * import { waniwani } from \"@waniwani/sdk\";\n * import { toNextJsHandler } from \"@waniwani/sdk/next-js\";\n *\n * const wani = waniwani();\n *\n * export const { GET, POST, dynamic } = toNextJsHandler(wani, {\n * chat: { systemPrompt: \"You are a helpful assistant.\" },\n * });\n * ```\n */\nexport function createApiHandler(options: ApiHandlerOptions = {}): ApiHandler {\n\tconst {\n\t\tapiKey = process.env.WANIWANI_API_KEY,\n\t\tbaseUrl = \"https://app.waniwani.ai\",\n\t\tsystemPrompt,\n\t\tmaxSteps = 5,\n\t\tbeforeRequest,\n\t\tmcpServerUrl,\n\t\tdebug = false,\n\t} = options;\n\n\tconst log = createLogger(\"router\", debug);\n\n\tconst resolveConfig = createMcpConfigResolver(baseUrl, apiKey);\n\n\tconst handleChat = createChatRequestHandler({\n\t\tapiKey,\n\t\tbaseUrl,\n\t\tsystemPrompt,\n\t\tmaxSteps,\n\t\tbeforeRequest,\n\t\tmcpServerUrl,\n\t\tresolveConfig,\n\t\tdebug,\n\t});\n\n\tconst handleResource = createResourceHandler({\n\t\tmcpServerUrl,\n\t\tresolveConfig,\n\t\tdebug,\n\t});\n\n\tconst handleTool = createToolHandler({\n\t\tmcpServerUrl,\n\t\tresolveConfig,\n\t\tdebug,\n\t});\n\n\tasync function handleConfig(): Promise<Response> {\n\t\treturn jsonResponse({ debug }, 200);\n\t}\n\n\tasync function routeGet(request: Request): Promise<Response> {\n\t\tlog(\"→ GET\", request.url);\n\t\ttry {\n\t\t\tconst url = new URL(request.url);\n\t\t\tconst segments = url.pathname\n\t\t\t\t.replace(/\\/$/, \"\")\n\t\t\t\t.split(\"/\")\n\t\t\t\t.filter(Boolean);\n\t\t\tconst subRoute = segments.at(-1);\n\t\t\tlog(\"pathname:\", url.pathname, \"subRoute:\", subRoute);\n\n\t\t\tif (subRoute === \"resource\") {\n\t\t\t\tlog(\"dispatching to resource handler\");\n\t\t\t\tconst response = await handleResource(url);\n\t\t\t\tlog(\"← resource handler returned\", response.status);\n\t\t\t\treturn response;\n\t\t\t}\n\n\t\t\tif (subRoute === \"config\") {\n\t\t\t\tlog(\"dispatching to config handler\");\n\t\t\t\tconst response = await handleConfig();\n\t\t\t\tlog(\"← config handler returned\", response.status);\n\t\t\t\treturn response;\n\t\t\t}\n\n\t\t\tlog(\"← 404 no matching sub-route for\", subRoute);\n\t\t\treturn jsonResponse({ error: \"Not found\" }, 404);\n\t\t} catch (error) {\n\t\t\tconsole.error(\"[waniwani:router] GET handler error:\", error);\n\t\t\tconst message =\n\t\t\t\terror instanceof Error ? error.message : \"Unknown error occurred\";\n\t\t\tlog(\"← 500 from caught error\");\n\t\t\treturn jsonResponse({ error: message }, 500);\n\t\t}\n\t}\n\n\tasync function routePost(request: Request): Promise<Response> {\n\t\tlog(\"→ POST\", request.url);\n\t\ttry {\n\t\t\tconst url = new URL(request.url);\n\t\t\tconst segments = url.pathname\n\t\t\t\t.replace(/\\/$/, \"\")\n\t\t\t\t.split(\"/\")\n\t\t\t\t.filter(Boolean);\n\t\t\tconst subRoute = segments.at(-1);\n\t\t\tlog(\"pathname:\", url.pathname, \"subRoute:\", subRoute);\n\n\t\t\tif (subRoute === \"tool\") {\n\t\t\t\tlog(\"dispatching to tool handler\");\n\t\t\t\tconst response = await handleTool(request);\n\t\t\t\tlog(\"← tool handler returned\", response.status);\n\t\t\t\treturn response;\n\t\t\t}\n\n\t\t\t// Default: treat as chat request\n\t\t\tlog(\"dispatching to chat handler\");\n\t\t\treturn handleChat(request);\n\t\t} catch (error) {\n\t\t\tconsole.error(\"[waniwani:router] POST handler error:\", error);\n\t\t\tconst message =\n\t\t\t\terror instanceof Error ? error.message : \"Unknown error occurred\";\n\t\t\tlog(\"← 500 from caught error\");\n\t\t\treturn jsonResponse({ error: message }, 500);\n\t\t}\n\t}\n\n\treturn { handleChat, handleResource, handleTool, routeGet, routePost };\n}\n","// WaniWani SDK - Next.js Adapter\n\nimport type { WaniWaniClient } from \"../../../types.js\";\nimport { createApiHandler } from \"../api-handler.js\";\nimport type { NextJsHandlerOptions, NextJsHandlerResult } from \"./@types.js\";\n\nexport type { NextJsHandlerOptions, NextJsHandlerResult } from \"./@types.js\";\n\n/**\n * Create Next.js route handlers from a WaniWani client.\n *\n * Returns `{ GET, POST }` for use with catch-all routes.\n * Mount at `app/api/waniwani/[[...path]]/route.ts`:\n *\n * - `POST /api/waniwani` → chat (proxied to WaniWani API)\n * - `GET /api/waniwani/resource?uri=…` → MCP resource content\n *\n * @example\n * ```typescript\n * // app/api/waniwani/[[...path]]/route.ts\n * import { waniwani } from \"@waniwani/sdk\";\n * import { toNextJsHandler } from \"@waniwani/sdk/next-js\";\n *\n * const wani = waniwani();\n *\n * export const { GET, POST } = toNextJsHandler(wani, {\n * chat: {\n * systemPrompt: \"You are a helpful assistant.\",\n * mcpServerUrl: process.env.MCP_SERVER_URL!,\n * },\n * });\n * ```\n */\nexport function toNextJsHandler(\n\tclient: WaniWaniClient,\n\toptions?: NextJsHandlerOptions,\n): NextJsHandlerResult {\n\tconst { apiKey, baseUrl } = client._config;\n\n\tconst debugEnabled = options?.debug ?? process.env.WANIWANI_DEBUG === \"1\";\n\n\tconst handler = createApiHandler({\n\t\t...options?.chat,\n\t\tapiKey,\n\t\tbaseUrl,\n\t\tdebug: debugEnabled,\n\t});\n\n\treturn {\n\t\tPOST: handler.routePost,\n\t\tGET: handler.routeGet,\n\t};\n}\n"],"mappings":"AAQO,SAASA,EACfC,EACAC,EAC+B,CAC/B,OAAOA,EACJ,IAAIC,IAAoB,QAAQ,IAAI,aAAaF,CAAS,IAAK,GAAGE,CAAI,EACtE,IAAM,CAAC,CACX,CCbO,IAAMC,EAAN,cAA4B,KAAM,CACxC,YACCC,EACOC,EACN,CACD,MAAMD,CAAO,E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,CACR,CAGA,OAAAf,EAAI,6BAA6B,EAC1BI,EAAWQ,CAAO,CAC1B,OAASI,EAAO,CACf,QAAQ,MAAM,wCAAyCA,CAAK,EAC5D,IAAMC,EACLD,aAAiB,MAAQA,EAAM,QAAU,yBAC1C,OAAAhB,EAAI,8BAAyB,EACtBZ,EAAa,CAAE,MAAO6B,CAAQ,EAAG,GAAG,CAC5C,CACD,CAEA,MAAO,CAAE,WAAAb,EAAY,eAAAE,EAAgB,WAAAE,EAAY,SAAAG,EAAU,UAAAO,CAAU,CACtE,CCxHO,SAASC,GACfC,EACAC,EACsB,CACtB,GAAM,CAAE,OAAAC,EAAQ,QAAAC,CAAQ,EAAIH,EAAO,QAE7BI,EAAeH,GAAS,OAAS,QAAQ,IAAI,iBAAmB,IAEhEI,EAAUC,EAAiB,CAChC,GAAGL,GAAS,KACZ,OAAAC,EACA,QAAAC,EACA,MAAOC,CACR,CAAC,EAED,MAAO,CACN,KAAMC,EAAQ,UACd,IAAKA,EAAQ,QACd,CACD","names":["createLogger","namespace","enabled","args","WaniWaniError","message","status","extractGeoFromHeaders","request","h","rawCity","city","safeDecodeURI","country","countryRegion","latitude","longitude","timezone","ip","value","hasModelContext","value","hasContent","hasStructuredContent","formatModelContextForPrompt","value","hasModelContext","sections","renderedBlocks","block","applyModelContextToSystemPrompt","systemPrompt","modelContext","hasModelContext","widgetContext","formatModelContextForPrompt","createChatRequestHandler","deps","apiKey","baseUrl","systemPrompt","maxSteps","beforeRequest","mcpServerUrlOverride","resolveConfig","debug","log","createLogger","request","body","messages","sessionId","modelContext","effectiveSystemPrompt","clientVisitorContext","geo","extractGeoFromHeaders","visitor","result","hookError","status","WaniWaniError","message","mcpServerUrl","applyModelContextToSystemPrompt","upstreamUrl","clientUserAgent","response","errorBody","headers","upstreamSessionId","error","createResourceHandler","deps","mcpServerUrlOverride","resolveConfig","debug","log","createLogger","url","uri","mcpServerUrl","createMCPClient","StreamableHTTPClientTransport","importError","mcp","result","content","html","error","message","status","WaniWaniError","createToolHandler","deps","mcpServerUrlOverride","resolveConfig","debug","log","createLogger","request","body","name","args","requestSessionId","mcpServerUrl","Client","StreamableHTTPClientTransport","importError","transport","client","result","error","message","status","WaniWaniError","TTL_MS","createMcpConfigResolver","baseUrl","apiKey","cached","inflight","WaniWaniError","response","body","data","jsonResponse","data","status","createApiHandler","options","apiKey","baseUrl","systemPrompt","maxSteps","beforeRequest","mcpServerUrl","debug","log","createLogger","resolveConfig","createMcpConfigResolver","handleChat","createChatRequestHandler","handleResource","createResourceHandler","handleTool","createToolHandler","handleConfig","routeGet","request","url","subRoute","response","error","message","routePost","toNextJsHandler","client","options","apiKey","baseUrl","debugEnabled","handler","createApiHandler"]}
1
+ {"version":3,"sources":["../../../src/utils/logger.ts","../../../src/error.ts","../../../src/chat/server/geo.ts","../../../src/shared/model-context.ts","../../../src/chat/server/model-context.ts","../../../src/chat/server/handle-chat.ts","../../../src/chat/server/handle-resource.ts","../../../src/chat/server/handle-tool.ts","../../../src/chat/server/mcp-config-resolver.ts","../../../src/chat/server/api-handler.ts","../../../src/chat/server/next-js/index.ts"],"sourcesContent":["/**\n * Creates a namespaced logger that writes to console.log when enabled,\n * or is a no-op when disabled.\n *\n * @example\n * const log = createLogger(\"chat\", debug);\n * log(\"→ POST\", request.url); // [waniwani:chat] → POST ...\n */\nexport function createLogger(\n\tnamespace: string,\n\tenabled: boolean,\n): (...args: unknown[]) => void {\n\treturn enabled\n\t\t? (...args: unknown[]) => console.log(`[waniwani:${namespace}]`, ...args)\n\t\t: () => {};\n}\n","// WaniWani SDK - Errors\n\nexport class WaniWaniError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic status: number,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"WaniWaniError\";\n\t}\n}\n","// Geo — Extract location metadata from platform request headers\n\n/**\n * Server-side geolocation extracted from platform headers (Vercel, Cloudflare).\n * All fields are optional — in local dev, no headers are present.\n */\nexport interface GeoLocation {\n\tcity?: string;\n\tcountry?: string;\n\tcountryRegion?: string;\n\tlatitude?: string;\n\tlongitude?: string;\n\ttimezone?: string;\n\tip?: string;\n}\n\n/**\n * Extracts geolocation from server-side request headers.\n *\n * Supports Vercel (`x-vercel-ip-*`), Cloudflare (`cf-ip*`, `cf-connecting-ip`),\n * and generic IP headers (`x-real-ip`, `x-forwarded-for`).\n *\n * Returns a `GeoLocation` with all fields optional (empty object in local dev).\n */\nexport function extractGeoFromHeaders(request: Request): GeoLocation {\n\tconst h = request.headers;\n\n\t// Vercel URL-encodes city names (e.g. \"S%C3%A3o%20Paulo\")\n\tconst rawCity = h.get(\"x-vercel-ip-city\") ?? h.get(\"cf-ipcity\") ?? undefined;\n\tconst city = rawCity ? safeDecodeURI(rawCity) : undefined;\n\n\tconst country =\n\t\th.get(\"x-vercel-ip-country\") ?? h.get(\"cf-ipcountry\") ?? undefined;\n\tconst countryRegion = h.get(\"x-vercel-ip-country-region\") ?? undefined;\n\tconst latitude =\n\t\th.get(\"x-vercel-ip-latitude\") ?? h.get(\"cf-iplatitude\") ?? undefined;\n\tconst longitude =\n\t\th.get(\"x-vercel-ip-longitude\") ?? h.get(\"cf-iplongitude\") ?? undefined;\n\tconst timezone =\n\t\th.get(\"x-vercel-ip-timezone\") ?? h.get(\"cf-iptimezone\") ?? undefined;\n\tconst ip =\n\t\th.get(\"x-real-ip\") ??\n\t\th.get(\"x-forwarded-for\")?.split(\",\")[0]?.trim() ??\n\t\th.get(\"cf-connecting-ip\") ??\n\t\tundefined;\n\n\treturn { city, country, countryRegion, latitude, longitude, timezone, ip };\n}\n\nfunction safeDecodeURI(value: string): string {\n\ttry {\n\t\treturn decodeURIComponent(value);\n\t} catch {\n\t\treturn value;\n\t}\n}\n","import type { ContentBlock } from \"@modelcontextprotocol/sdk/types.js\";\n\nexport type ModelContextContentBlock = ContentBlock;\n\nexport type ModelContextUpdate = {\n\tcontent?: ModelContextContentBlock[];\n\tstructuredContent?: Record<string, unknown>;\n};\n\nexport function hasModelContext(\n\tvalue: ModelContextUpdate | null | undefined,\n): value is ModelContextUpdate {\n\tif (!value) {\n\t\treturn false;\n\t}\n\tconst hasContent = Array.isArray(value.content) && value.content.length > 0;\n\tconst hasStructuredContent =\n\t\ttypeof value.structuredContent === \"object\" &&\n\t\tvalue.structuredContent !== null &&\n\t\tObject.keys(value.structuredContent).length > 0;\n\treturn hasContent || hasStructuredContent;\n}\n\nexport function mergeModelContext(\n\tcurrent: ModelContextUpdate | null | undefined,\n\tnext: ModelContextUpdate | null | undefined,\n): ModelContextUpdate | null {\n\tif (!hasModelContext(current) && !hasModelContext(next)) {\n\t\treturn null;\n\t}\n\tif (!hasModelContext(current)) {\n\t\treturn {\n\t\t\t...(next?.content ? { content: [...next.content] } : {}),\n\t\t\t...(next?.structuredContent\n\t\t\t\t? { structuredContent: { ...next.structuredContent } }\n\t\t\t\t: {}),\n\t\t};\n\t}\n\tif (!hasModelContext(next)) {\n\t\treturn {\n\t\t\t...(current.content ? { content: [...current.content] } : {}),\n\t\t\t...(current.structuredContent\n\t\t\t\t? { structuredContent: { ...current.structuredContent } }\n\t\t\t\t: {}),\n\t\t};\n\t}\n\n\treturn {\n\t\t...(current.content || next.content\n\t\t\t? { content: [...(current.content ?? []), ...(next.content ?? [])] }\n\t\t\t: {}),\n\t\t...(current.structuredContent || next.structuredContent\n\t\t\t? {\n\t\t\t\t\tstructuredContent: {\n\t\t\t\t\t\t...(current.structuredContent ?? {}),\n\t\t\t\t\t\t...(next.structuredContent ?? {}),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n\nexport function formatModelContextForPrompt(\n\tvalue: ModelContextUpdate | null | undefined,\n): string {\n\tif (!hasModelContext(value)) {\n\t\treturn \"\";\n\t}\n\n\tconst sections: string[] = [\n\t\t\"## Widget Model Context\",\n\t\t\"This hidden context was supplied by an MCP App via `ui/update-model-context`.\",\n\t\t\"Use it for the next assistant turn only. If it includes flow continuation or tool-call instructions, follow them exactly.\",\n\t];\n\n\tif (value.content?.length) {\n\t\tconst renderedBlocks = value.content\n\t\t\t.map((block) => {\n\t\t\t\tif (block.type === \"text\" && typeof block.text === \"string\") {\n\t\t\t\t\treturn block.text.trim();\n\t\t\t\t}\n\t\t\t\treturn JSON.stringify(block, null, 2);\n\t\t\t})\n\t\t\t.filter(Boolean)\n\t\t\t.join(\"\\n\\n\");\n\t\tif (renderedBlocks) {\n\t\t\tsections.push(`Content blocks:\\n${renderedBlocks}`);\n\t\t}\n\t}\n\n\tif (\n\t\tvalue.structuredContent &&\n\t\tObject.keys(value.structuredContent).length > 0\n\t) {\n\t\tsections.push(\n\t\t\t`Structured content JSON:\\n${JSON.stringify(value.structuredContent, null, 2)}`,\n\t\t);\n\t}\n\n\treturn sections.join(\"\\n\\n\");\n}\n","import {\n\tformatModelContextForPrompt,\n\thasModelContext,\n\ttype ModelContextUpdate,\n} from \"../../shared/model-context\";\n\nexport function applyModelContextToSystemPrompt(\n\tsystemPrompt: string | undefined,\n\tmodelContext: ModelContextUpdate | undefined,\n): string | undefined {\n\tif (!hasModelContext(modelContext)) {\n\t\treturn systemPrompt;\n\t}\n\n\tconst widgetContext = formatModelContextForPrompt(modelContext);\n\tif (!widgetContext) {\n\t\treturn systemPrompt;\n\t}\n\n\treturn [systemPrompt, widgetContext].filter(Boolean).join(\"\\n\\n\");\n}\n","// Handle Chat - Proxies chat requests to the WaniWani API\n\nimport { WaniWaniError } from \"../../error\";\nimport { createLogger } from \"../../utils/logger.js\";\nimport type {\n\tApiHandlerDeps,\n\tClientVisitorContext,\n\tVisitorMeta,\n} from \"./@types\";\nimport { extractGeoFromHeaders } from \"./geo\";\nimport { applyModelContextToSystemPrompt } from \"./model-context\";\n\nexport function createChatRequestHandler(deps: ApiHandlerDeps) {\n\tconst {\n\t\tapiKey,\n\t\tbaseUrl,\n\t\tsource,\n\t\tsystemPrompt,\n\t\tmaxSteps,\n\t\tbeforeRequest,\n\t\tmcpServerUrl: mcpServerUrlOverride,\n\t\tresolveConfig,\n\t\tdebug,\n\t} = deps;\n\n\tconst log = createLogger(\"chat\", debug);\n\n\treturn async function handleChat(request: Request): Promise<Response> {\n\t\tlog(\"→ POST\", request.url);\n\t\ttry {\n\t\t\t// 1. Parse request body\n\t\t\tconst body = await request.json();\n\t\t\tlet messages = body.messages ?? [];\n\t\t\tlet sessionId: string | undefined = body.sessionId;\n\t\t\tlet modelContext = body.modelContext;\n\t\t\tlet effectiveSystemPrompt = systemPrompt;\n\n\t\t\t// Extract visitor context (client-side + server-side geo)\n\t\t\tconst clientVisitorContext: ClientVisitorContext | null =\n\t\t\t\tbody.visitorContext ?? null;\n\t\t\tconst geo = extractGeoFromHeaders(request);\n\t\t\tconst visitor: VisitorMeta = { geo, client: clientVisitorContext };\n\n\t\t\tlog(\n\t\t\t\t\"body parsed — messages:\",\n\t\t\t\tmessages.length,\n\t\t\t\t\"sessionId:\",\n\t\t\t\tsessionId ?? \"(none)\",\n\t\t\t\t\"geo:\",\n\t\t\t\tJSON.stringify(geo),\n\t\t\t);\n\n\t\t\t// 2. Run beforeRequest hook\n\t\t\tif (beforeRequest) {\n\t\t\t\tlog(\"running beforeRequest hook\");\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await beforeRequest({\n\t\t\t\t\t\tmessages,\n\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\tmodelContext,\n\t\t\t\t\t\trequest,\n\t\t\t\t\t\tvisitor,\n\t\t\t\t\t});\n\n\t\t\t\t\tif (result) {\n\t\t\t\t\t\tif (result.messages) {\n\t\t\t\t\t\t\tmessages = result.messages;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (result.systemPrompt !== undefined) {\n\t\t\t\t\t\t\teffectiveSystemPrompt = result.systemPrompt;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (result.sessionId !== undefined) {\n\t\t\t\t\t\t\tsessionId = result.sessionId;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (result.modelContext !== undefined) {\n\t\t\t\t\t\t\tmodelContext = result.modelContext;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tlog(\n\t\t\t\t\t\t\"beforeRequest hook done — messages:\",\n\t\t\t\t\t\tmessages.length,\n\t\t\t\t\t\t\"sessionId:\",\n\t\t\t\t\t\tsessionId ?? \"(none)\",\n\t\t\t\t\t);\n\t\t\t\t} catch (hookError) {\n\t\t\t\t\tconsole.error(\"[waniwani:chat] beforeRequest hook error:\", hookError);\n\t\t\t\t\tconst status =\n\t\t\t\t\t\thookError instanceof WaniWaniError ? hookError.status : 400;\n\t\t\t\t\tconst message =\n\t\t\t\t\t\thookError instanceof Error ? hookError.message : \"Request rejected\";\n\t\t\t\t\tlog(\"← returning\", status, \"from hook error\");\n\t\t\t\t\treturn Response.json({ error: message }, { status });\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// 3. Resolve MCP server URL\n\t\t\tconst mcpServerUrl =\n\t\t\t\tmcpServerUrlOverride ?? (await resolveConfig()).mcpServerUrl;\n\t\t\tlog(\"mcpServerUrl:\", mcpServerUrl);\n\t\t\teffectiveSystemPrompt = applyModelContextToSystemPrompt(\n\t\t\t\teffectiveSystemPrompt,\n\t\t\t\tmodelContext,\n\t\t\t);\n\n\t\t\t// 4. Forward to WaniWani API\n\t\t\tconst upstreamUrl = `${baseUrl}/api/mcp/chat`;\n\t\t\tlog(\"forwarding to\", upstreamUrl);\n\t\t\tconst clientUserAgent = request.headers.get(\"user-agent\");\n\n\t\t\tconst response = await fetch(upstreamUrl, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),\n\t\t\t\t\t...(clientUserAgent\n\t\t\t\t\t\t? { \"X-Client-User-Agent\": clientUserAgent }\n\t\t\t\t\t\t: {}),\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tmessages,\n\t\t\t\t\tmcpServerUrl,\n\t\t\t\t\tsessionId,\n\t\t\t\t\tsource,\n\t\t\t\t\tsystemPrompt: effectiveSystemPrompt,\n\t\t\t\t\tmaxSteps,\n\t\t\t\t\tvisitor,\n\t\t\t\t}),\n\t\t\t\tsignal: request.signal,\n\t\t\t});\n\n\t\t\tlog(\"upstream response status:\", response.status);\n\n\t\t\tif (!response.ok) {\n\t\t\t\tconst errorBody = await response.text().catch(() => \"\");\n\t\t\t\tlog(\"← returning\", response.status, \"upstream error:\", errorBody);\n\t\t\t\treturn new Response(errorBody, {\n\t\t\t\t\tstatus: response.status,\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t\"Content-Type\":\n\t\t\t\t\t\t\tresponse.headers.get(\"Content-Type\") ?? \"application/json\",\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// 5. Stream the response back\n\t\t\tconst headers = new Headers({\n\t\t\t\t\"Content-Type\":\n\t\t\t\t\tresponse.headers.get(\"Content-Type\") ?? \"text/event-stream\",\n\t\t\t});\n\t\t\tconst upstreamSessionId = response.headers.get(\"x-session-id\");\n\t\t\tif (upstreamSessionId) {\n\t\t\t\theaders.set(\"x-session-id\", upstreamSessionId);\n\t\t\t}\n\n\t\t\tlog(\n\t\t\t\t\"← streaming response\",\n\t\t\t\tresponse.status,\n\t\t\t\t\"body null?\",\n\t\t\t\tresponse.body === null,\n\t\t\t);\n\t\t\treturn new Response(response.body, {\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconsole.error(\"[waniwani:chat] handler error:\", error);\n\t\t\tconst message =\n\t\t\t\terror instanceof Error ? error.message : \"Unknown error occurred\";\n\t\t\tconst status = error instanceof WaniWaniError ? error.status : 500;\n\t\t\tlog(\"← returning\", status, \"from caught error\");\n\t\t\treturn Response.json({ error: message }, { status });\n\t\t}\n\t};\n}\n","// Handle Resource - Serves MCP resource content (HTML widgets)\n\nimport { WaniWaniError } from \"../../error\";\nimport { createLogger } from \"../../utils/logger.js\";\nimport type { ResourceHandlerDeps } from \"./@types\";\n\nexport function createResourceHandler(deps: ResourceHandlerDeps) {\n\tconst { mcpServerUrl: mcpServerUrlOverride, resolveConfig, debug } = deps;\n\n\tconst log = createLogger(\"resource\", debug);\n\n\treturn async function handleResource(url: URL): Promise<Response> {\n\t\tlog(\"→ GET\", url.toString());\n\t\ttry {\n\t\t\tconst uri = url.searchParams.get(\"uri\");\n\t\t\tlog(\"uri:\", uri ?? \"(missing)\");\n\n\t\t\tif (!uri) {\n\t\t\t\tlog(\"← 400 missing uri\");\n\t\t\t\treturn Response.json(\n\t\t\t\t\t{ error: \"Missing uri query parameter\" },\n\t\t\t\t\t{ status: 400 },\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst mcpServerUrl =\n\t\t\t\tmcpServerUrlOverride ?? (await resolveConfig()).mcpServerUrl;\n\t\t\tlog(\"mcpServerUrl:\", mcpServerUrl);\n\n\t\t\t// Dynamic imports — these are optional peer dependencies\n\t\t\tlet createMCPClient: typeof import(\"@ai-sdk/mcp\")[\"createMCPClient\"];\n\t\t\tlet StreamableHTTPClientTransport: typeof import(\"@modelcontextprotocol/sdk/client/streamableHttp.js\")[\"StreamableHTTPClientTransport\"];\n\n\t\t\ttry {\n\t\t\t\t[{ createMCPClient }, { StreamableHTTPClientTransport }] =\n\t\t\t\t\tawait Promise.all([\n\t\t\t\t\t\timport(\"@ai-sdk/mcp\"),\n\t\t\t\t\t\timport(\"@modelcontextprotocol/sdk/client/streamableHttp.js\"),\n\t\t\t\t\t]);\n\t\t\t\tlog(\"MCP deps loaded\");\n\t\t\t} catch (importError) {\n\t\t\t\tconsole.error(\n\t\t\t\t\t\"[waniwani:resource] MCP deps import failed:\",\n\t\t\t\t\timportError,\n\t\t\t\t);\n\t\t\t\treturn Response.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror:\n\t\t\t\t\t\t\t\"MCP resource handler requires @ai-sdk/mcp and @modelcontextprotocol/sdk. Install them to enable resource serving.\",\n\t\t\t\t\t},\n\t\t\t\t\t{ status: 501 },\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlog(\"creating MCP client for\", mcpServerUrl);\n\t\t\tconst mcp = await createMCPClient({\n\t\t\t\ttransport: new StreamableHTTPClientTransport(new URL(mcpServerUrl)),\n\t\t\t});\n\n\t\t\ttry {\n\t\t\t\tlog(\"reading resource:\", uri);\n\t\t\t\tconst result = await mcp.readResource({ uri });\n\t\t\t\tlog(\"resource contents count:\", result.contents.length);\n\n\t\t\t\tconst content = result.contents[0];\n\t\t\t\tif (!content) {\n\t\t\t\t\tlog(\"← 404 resource not found\");\n\t\t\t\t\treturn Response.json(\n\t\t\t\t\t\t{ error: \"Resource not found\" },\n\t\t\t\t\t\t{ status: 404 },\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tlet html: string | undefined;\n\t\t\t\tif (\"text\" in content && typeof content.text === \"string\") {\n\t\t\t\t\thtml = content.text;\n\t\t\t\t} else if (\"blob\" in content && typeof content.blob === \"string\") {\n\t\t\t\t\thtml = atob(content.blob);\n\t\t\t\t}\n\n\t\t\t\tif (!html) {\n\t\t\t\t\tlog(\"← 404 resource has no content, keys:\", Object.keys(content));\n\t\t\t\t\treturn Response.json(\n\t\t\t\t\t\t{ error: \"Resource has no content\" },\n\t\t\t\t\t\t{ status: 404 },\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tlog(\"← 200 HTML length:\", html.length);\n\t\t\t\treturn new Response(html, {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t\"Content-Type\": \"text/html\",\n\t\t\t\t\t\t\"Cache-Control\": \"private, max-age=300\",\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} finally {\n\t\t\t\tawait mcp.close();\n\t\t\t\tlog(\"MCP client closed\");\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconsole.error(\"[waniwani:resource] handler error:\", error);\n\t\t\tconst message =\n\t\t\t\terror instanceof Error ? error.message : \"Unknown error occurred\";\n\t\t\tconst status = error instanceof WaniWaniError ? error.status : 500;\n\t\t\tlog(\"← returning\", status, \"from caught error\");\n\t\t\treturn Response.json({ error: message }, { status });\n\t\t}\n\t};\n}\n","// Handle Tool - Calls MCP server tools directly and returns JSON results\n\nimport { WaniWaniError } from \"../../error\";\nimport { createLogger } from \"../../utils/logger.js\";\nimport type { ResourceHandlerDeps } from \"./@types\";\n\nexport function createToolHandler(deps: ResourceHandlerDeps) {\n\tconst { mcpServerUrl: mcpServerUrlOverride, resolveConfig, debug } = deps;\n\n\tconst log = createLogger(\"tool\", debug);\n\n\treturn async function handleTool(request: Request): Promise<Response> {\n\t\tlog(\"→ POST\", request.url);\n\t\ttry {\n\t\t\tconst body = await request.json();\n\t\t\tconst { name, arguments: args } = body as {\n\t\t\t\tname: string;\n\t\t\t\targuments: Record<string, unknown>;\n\t\t\t};\n\t\t\tconst requestSessionId = request.headers.get(\"x-session-id\")?.trim();\n\n\t\t\tif (!name || typeof name !== \"string\") {\n\t\t\t\tlog(\"← 400 missing tool name\");\n\t\t\t\treturn Response.json({ error: \"Missing tool name\" }, { status: 400 });\n\t\t\t}\n\n\t\t\tlog(\n\t\t\t\t\"tool:\",\n\t\t\t\tname,\n\t\t\t\t\"args:\",\n\t\t\t\tJSON.stringify(args),\n\t\t\t\t\"sessionId:\",\n\t\t\t\trequestSessionId || \"(none)\",\n\t\t\t);\n\n\t\t\tconst mcpServerUrl =\n\t\t\t\tmcpServerUrlOverride ?? (await resolveConfig()).mcpServerUrl;\n\t\t\tlog(\"mcpServerUrl:\", mcpServerUrl);\n\n\t\t\t// Dynamic imports — these are optional peer dependencies\n\t\t\tlet Client: typeof import(\"@modelcontextprotocol/sdk/client/index.js\")[\"Client\"];\n\t\t\tlet StreamableHTTPClientTransport: typeof import(\"@modelcontextprotocol/sdk/client/streamableHttp.js\")[\"StreamableHTTPClientTransport\"];\n\n\t\t\ttry {\n\t\t\t\t[{ Client }, { StreamableHTTPClientTransport }] = await Promise.all([\n\t\t\t\t\timport(\"@modelcontextprotocol/sdk/client/index.js\"),\n\t\t\t\t\timport(\"@modelcontextprotocol/sdk/client/streamableHttp.js\"),\n\t\t\t\t]);\n\t\t\t\tlog(\"MCP deps loaded\");\n\t\t\t} catch (importError) {\n\t\t\t\tconsole.error(\"[waniwani:tool] MCP deps import failed:\", importError);\n\t\t\t\treturn Response.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror:\n\t\t\t\t\t\t\t\"MCP tool handler requires @modelcontextprotocol/sdk. Install it to enable tool calls.\",\n\t\t\t\t\t},\n\t\t\t\t\t{ status: 501 },\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlog(\"creating MCP client for\", mcpServerUrl);\n\t\t\tconst transport = new StreamableHTTPClientTransport(\n\t\t\t\tnew URL(mcpServerUrl),\n\t\t\t);\n\t\t\tconst client = new Client({\n\t\t\t\tname: \"waniwani-tool-caller\",\n\t\t\t\tversion: \"1.0.0\",\n\t\t\t});\n\t\t\tawait client.connect(transport);\n\n\t\t\ttry {\n\t\t\t\tlog(\"calling tool:\", name);\n\t\t\t\tconst result = await client.callTool({\n\t\t\t\t\tname,\n\t\t\t\t\targuments: args ?? {},\n\t\t\t\t\t...(requestSessionId\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t_meta: {\n\t\t\t\t\t\t\t\t\t\"waniwani/sessionId\": requestSessionId,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t} as {\n\t\t\t\t\tname: string;\n\t\t\t\t\targuments: Record<string, unknown>;\n\t\t\t\t\t_meta?: Record<string, unknown>;\n\t\t\t\t});\n\t\t\t\tlog(\"tool result received\");\n\n\t\t\t\treturn Response.json({\n\t\t\t\t\tcontent: result.content,\n\t\t\t\t\tstructuredContent: result.structuredContent,\n\t\t\t\t\t_meta: result._meta,\n\t\t\t\t\tisError: result.isError,\n\t\t\t\t});\n\t\t\t} finally {\n\t\t\t\tawait client.close();\n\t\t\t\tlog(\"MCP client closed\");\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconsole.error(\"[waniwani:tool] handler error:\", error);\n\t\t\tconst message =\n\t\t\t\terror instanceof Error ? error.message : \"Unknown error occurred\";\n\t\t\tconst status = error instanceof WaniWaniError ? error.status : 500;\n\t\t\tlog(\"← returning\", status, \"from caught error\");\n\t\t\treturn Response.json({ error: message }, { status });\n\t\t}\n\t};\n}\n","// MCP Config Resolver - Lazy-loads and caches MCP environment config\n\nimport { WaniWaniError } from \"../../error\";\n\ninterface McpEnvironmentConfig {\n\tmcpServerUrl: string;\n}\n\nconst TTL_MS = 5 * 60 * 1000; // 5 minutes\n\nexport function createMcpConfigResolver(\n\tbaseUrl: string,\n\tapiKey: string | undefined,\n) {\n\tlet cached: { config: McpEnvironmentConfig; expiresAt: number } | null = null;\n\tlet inflight: Promise<McpEnvironmentConfig> | null = null;\n\n\treturn async function resolve(): Promise<McpEnvironmentConfig> {\n\t\tif (cached && Date.now() < cached.expiresAt) {\n\t\t\treturn cached.config;\n\t\t}\n\n\t\t// Deduplicate concurrent requests (cold start scenario)\n\t\tif (inflight) {\n\t\t\treturn inflight;\n\t\t}\n\n\t\tinflight = (async () => {\n\t\t\tif (!apiKey) {\n\t\t\t\tthrow new WaniWaniError(\n\t\t\t\t\t\"WANIWANI_API_KEY is required for createChatHandler\",\n\t\t\t\t\t401,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst response = await fetch(`${baseUrl}/api/mcp/environments/config`, {\n\t\t\t\tmethod: \"GET\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tif (!response.ok) {\n\t\t\t\tconst body = await response.text().catch(() => \"\");\n\t\t\t\tthrow new WaniWaniError(\n\t\t\t\t\t`Failed to resolve MCP environment config: ${response.status} ${body}`,\n\t\t\t\t\tresponse.status,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst data = (await response.json()) as McpEnvironmentConfig;\n\t\t\tcached = { config: data, expiresAt: Date.now() + TTL_MS };\n\t\t\treturn data;\n\t\t})();\n\n\t\ttry {\n\t\t\treturn await inflight;\n\t\t} finally {\n\t\t\tinflight = null;\n\t\t}\n\t};\n}\n","// API Handler - Composes chat and resource handlers into a unified API handler\n\nimport { createLogger } from \"../../utils/logger.js\";\nimport type { ApiHandler, ApiHandlerOptions } from \"./@types\";\nimport { createChatRequestHandler } from \"./handle-chat\";\nimport { createResourceHandler } from \"./handle-resource\";\nimport { createToolHandler } from \"./handle-tool\";\nimport { createMcpConfigResolver } from \"./mcp-config-resolver\";\n\n/**\n * Create a JSON response with the given data and status code.\n * @param data - The data to be serialized to JSON.\n * @param status - The HTTP status code to be returned.\n * @returns A Response object with the JSON data and the given status code.\n */\nfunction jsonResponse(data: object, status: number): Response {\n\treturn new Response(JSON.stringify(data), {\n\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\tstatus,\n\t});\n}\n\n/**\n * Create a framework-agnostic API handler for chat and MCP resources.\n *\n * Returns an object with handler methods that can be wired into\n * any framework (Next.js, Hono, Express, etc.):\n *\n * - `handleChat(request)` → proxies chat messages to WaniWani API\n * - `handleResource(url)` → serves MCP resource content (HTML widgets)\n * - `routeGet(request)` → routes GET sub-paths (e.g. /resource)\n *\n * @example\n * ```typescript\n * import { waniwani } from \"@waniwani/sdk\";\n * import { toNextJsHandler } from \"@waniwani/sdk/next-js\";\n *\n * const wani = waniwani();\n *\n * export const { GET, POST, dynamic } = toNextJsHandler(wani, {\n * chat: { systemPrompt: \"You are a helpful assistant.\" },\n * });\n * ```\n */\nexport function createApiHandler(options: ApiHandlerOptions = {}): ApiHandler {\n\tconst {\n\t\tapiKey = process.env.WANIWANI_API_KEY,\n\t\tbaseUrl = \"https://app.waniwani.ai\",\n\t\tsource,\n\t\tsystemPrompt,\n\t\tmaxSteps = 5,\n\t\tbeforeRequest,\n\t\tmcpServerUrl,\n\t\tdebug = false,\n\t} = options;\n\n\tconst log = createLogger(\"router\", debug);\n\n\tconst resolveConfig = createMcpConfigResolver(baseUrl, apiKey);\n\n\tconst handleChat = createChatRequestHandler({\n\t\tapiKey,\n\t\tbaseUrl,\n\t\tsource,\n\t\tsystemPrompt,\n\t\tmaxSteps,\n\t\tbeforeRequest,\n\t\tmcpServerUrl,\n\t\tresolveConfig,\n\t\tdebug,\n\t});\n\n\tconst handleResource = createResourceHandler({\n\t\tmcpServerUrl,\n\t\tresolveConfig,\n\t\tdebug,\n\t});\n\n\tconst handleTool = createToolHandler({\n\t\tmcpServerUrl,\n\t\tresolveConfig,\n\t\tdebug,\n\t});\n\n\tasync function handleConfig(): Promise<Response> {\n\t\treturn jsonResponse({ debug }, 200);\n\t}\n\n\tasync function routeGet(request: Request): Promise<Response> {\n\t\tlog(\"→ GET\", request.url);\n\t\ttry {\n\t\t\tconst url = new URL(request.url);\n\t\t\tconst segments = url.pathname\n\t\t\t\t.replace(/\\/$/, \"\")\n\t\t\t\t.split(\"/\")\n\t\t\t\t.filter(Boolean);\n\t\t\tconst subRoute = segments.at(-1);\n\t\t\tlog(\"pathname:\", url.pathname, \"subRoute:\", subRoute);\n\n\t\t\tif (subRoute === \"resource\") {\n\t\t\t\tlog(\"dispatching to resource handler\");\n\t\t\t\tconst response = await handleResource(url);\n\t\t\t\tlog(\"← resource handler returned\", response.status);\n\t\t\t\treturn response;\n\t\t\t}\n\n\t\t\tif (subRoute === \"config\") {\n\t\t\t\tlog(\"dispatching to config handler\");\n\t\t\t\tconst response = await handleConfig();\n\t\t\t\tlog(\"← config handler returned\", response.status);\n\t\t\t\treturn response;\n\t\t\t}\n\n\t\t\tlog(\"← 404 no matching sub-route for\", subRoute);\n\t\t\treturn jsonResponse({ error: \"Not found\" }, 404);\n\t\t} catch (error) {\n\t\t\tconsole.error(\"[waniwani:router] GET handler error:\", error);\n\t\t\tconst message =\n\t\t\t\terror instanceof Error ? error.message : \"Unknown error occurred\";\n\t\t\tlog(\"← 500 from caught error\");\n\t\t\treturn jsonResponse({ error: message }, 500);\n\t\t}\n\t}\n\n\tasync function routePost(request: Request): Promise<Response> {\n\t\tlog(\"→ POST\", request.url);\n\t\ttry {\n\t\t\tconst url = new URL(request.url);\n\t\t\tconst segments = url.pathname\n\t\t\t\t.replace(/\\/$/, \"\")\n\t\t\t\t.split(\"/\")\n\t\t\t\t.filter(Boolean);\n\t\t\tconst subRoute = segments.at(-1);\n\t\t\tlog(\"pathname:\", url.pathname, \"subRoute:\", subRoute);\n\n\t\t\tif (subRoute === \"tool\") {\n\t\t\t\tlog(\"dispatching to tool handler\");\n\t\t\t\tconst response = await handleTool(request);\n\t\t\t\tlog(\"← tool handler returned\", response.status);\n\t\t\t\treturn response;\n\t\t\t}\n\n\t\t\t// Default: treat as chat request\n\t\t\tlog(\"dispatching to chat handler\");\n\t\t\treturn handleChat(request);\n\t\t} catch (error) {\n\t\t\tconsole.error(\"[waniwani:router] POST handler error:\", error);\n\t\t\tconst message =\n\t\t\t\terror instanceof Error ? error.message : \"Unknown error occurred\";\n\t\t\tlog(\"← 500 from caught error\");\n\t\t\treturn jsonResponse({ error: message }, 500);\n\t\t}\n\t}\n\n\treturn { handleChat, handleResource, handleTool, routeGet, routePost };\n}\n","// WaniWani SDK - Next.js Adapter\n\nimport type { WaniWaniClient } from \"../../../types.js\";\nimport { createApiHandler } from \"../api-handler.js\";\nimport type { NextJsHandlerOptions, NextJsHandlerResult } from \"./@types.js\";\n\nexport type { NextJsHandlerOptions, NextJsHandlerResult } from \"./@types.js\";\n\n/**\n * Create Next.js route handlers from a WaniWani client.\n *\n * Returns `{ GET, POST }` for use with catch-all routes.\n * Mount at `app/api/waniwani/[[...path]]/route.ts`:\n *\n * - `POST /api/waniwani` → chat (proxied to WaniWani API)\n * - `GET /api/waniwani/resource?uri=…` → MCP resource content\n *\n * @example\n * ```typescript\n * // app/api/waniwani/[[...path]]/route.ts\n * import { waniwani } from \"@waniwani/sdk\";\n * import { toNextJsHandler } from \"@waniwani/sdk/next-js\";\n *\n * const wani = waniwani();\n *\n * export const { GET, POST } = toNextJsHandler(wani, {\n * chat: {\n * systemPrompt: \"You are a helpful assistant.\",\n * mcpServerUrl: process.env.MCP_SERVER_URL!,\n * },\n * });\n * ```\n */\nexport function toNextJsHandler(\n\tclient: WaniWaniClient,\n\toptions: NextJsHandlerOptions,\n): NextJsHandlerResult {\n\tconst { apiKey, baseUrl } = client._config;\n\n\tconst debugEnabled = options?.debug ?? process.env.WANIWANI_DEBUG === \"1\";\n\n\tconst handler = createApiHandler({\n\t\t...options?.chat,\n\t\tapiKey,\n\t\tbaseUrl,\n\t\tsource: options?.source,\n\t\tdebug: debugEnabled,\n\t});\n\n\treturn {\n\t\tPOST: handler.routePost,\n\t\tGET: handler.routeGet,\n\t};\n}\n"],"mappings":"AAQO,SAASA,EACfC,EACAC,EAC+B,CAC/B,OAAOA,EACJ,IAAIC,IAAoB,QAAQ,IAAI,aAAaF,CAAS,IAAK,GAAGE,CAAI,EACtE,IAAM,CAAC,CACX,CCbO,IAAMC,EAAN,cAA4B,KAAM,CACxC,YACCC,EACOC,EACN,CACD,MAAMD,CAAO,EAFN,YAAAC,EAGP,KAAK,KAAO,eACb,CACD,ECcO,SAASC,EAAsBC,EAA+B,CACpE,IAAMC,EAAID,EAAQ,QAGZE,EAAUD,EAAE,IAAI,kBAAkB,GAAKA,EAAE,IAAI,WAAW,GAAK,OAC7DE,EAAOD,EAAUE,EAAcF,CAAO,EAAI,OAE1CG,EACLJ,EAAE,IAAI,qBAAqB,GAAKA,EAAE,IAAI,cAAc,GAAK,OACpDK,EAAgBL,EAAE,IAAI,4BAA4B,GAAK,OACvDM,EACLN,EAAE,IAAI,sBAAsB,GAAKA,EAAE,IAAI,eAAe,GAAK,OACtDO,EACLP,EAAE,IAAI,uBAAuB,GAAKA,EAAE,IAAI,gBAAgB,GAAK,OACxDQ,EACLR,EAAE,IAAI,sBAAsB,GAAKA,EAAE,IAAI,eAAe,GAAK,OACtDS,EACLT,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B,IAEhEI,EAAUC,EAAiB,CAChC,GAAGL,GAAS,KACZ,OAAAC,EACA,QAAAC,EACA,OAAQF,GAAS,OACjB,MAAOG,CACR,CAAC,EAED,MAAO,CACN,KAAMC,EAAQ,UACd,IAAKA,EAAQ,QACd,CACD","names":["createLogger","namespace","enabled","args","WaniWaniError","message","status","extractGeoFromHeaders","request","h","rawCity","city","safeDecodeURI","country","countryRegion","latitude","longitude","timezone","ip","value","hasModelContext","value","hasContent","hasStructuredContent","formatModelContextForPrompt","value","hasModelContext","sections","renderedBlocks","block","applyModelContextToSystemPrompt","systemPrompt","modelContext","hasModelContext","widgetContext","formatModelContextForPrompt","createChatRequestHandler","deps","apiKey","baseUrl","source","systemPrompt","maxSteps","beforeRequest","mcpServerUrlOverride","resolveConfig","debug","log","createLogger","request","body","messages","sessionId","modelContext","effectiveSystemPrompt","clientVisitorContext","geo","extractGeoFromHeaders","visitor","result","hookError","status","WaniWaniError","message","mcpServerUrl","applyModelContextToSystemPrompt","upstreamUrl","clientUserAgent","response","errorBody","headers","upstreamSessionId","error","createResourceHandler","deps","mcpServerUrlOverride","resolveConfig","debug","log","createLogger","url","uri","mcpServerUrl","createMCPClient","StreamableHTTPClientTransport","importError","mcp","result","content","html","error","message","status","WaniWaniError","createToolHandler","deps","mcpServerUrlOverride","resolveConfig","debug","log","createLogger","request","body","name","args","requestSessionId","mcpServerUrl","Client","StreamableHTTPClientTransport","importError","transport","client","result","error","message","status","WaniWaniError","TTL_MS","createMcpConfigResolver","baseUrl","apiKey","cached","inflight","WaniWaniError","response","body","data","jsonResponse","data","status","createApiHandler","options","apiKey","baseUrl","source","systemPrompt","maxSteps","beforeRequest","mcpServerUrl","debug","log","createLogger","resolveConfig","createMcpConfigResolver","handleChat","createChatRequestHandler","handleResource","createResourceHandler","handleTool","createToolHandler","handleConfig","routeGet","request","url","subRoute","response","error","message","routePost","toNextJsHandler","client","options","apiKey","baseUrl","debugEnabled","handler","createApiHandler"]}
@@ -72,6 +72,11 @@ type BeforeRequestResult = {
72
72
  modelContext?: ModelContextUpdate;
73
73
  };
74
74
  interface ApiHandlerOptions {
75
+ /**
76
+ * Identifies this chatbar instance in analytics.
77
+ * Forwarded as `waniwani/source` in MCP request metadata.
78
+ */
79
+ source?: string;
75
80
  /**
76
81
  * Your WaniWani API key.
77
82
  * Defaults to process.env.WANIWANI_API_KEY.
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var g=class extends Error{constructor(n,r){super(n);this.status=r;this.name="WaniWaniError"}};var V="@waniwani/sdk";function S(e){let{baseUrl:t,apiKey:n}=e;function r(){if(!n)throw new Error("WANIWANI_API_KEY is not set");return n}async function s(i,a,o){let d=r(),m=`${t.replace(/\/$/,"")}${a}`,l={Authorization:`Bearer ${d}`,"X-WaniWani-SDK":V},f={method:i,headers:l};o!==void 0&&(l["Content-Type"]="application/json",f.body=JSON.stringify(o));let u=await fetch(m,f);if(!u.ok){let C=await u.text().catch(()=>"");throw new g(C||`KB API error: HTTP ${u.status}`,u.status)}return(await u.json()).data}return{async ingest(i){return s("POST","/api/mcp/kb/ingest",{files:i})},async search(i,a){return s("POST","/api/mcp/kb/search",{query:i,...a})},async sources(){return s("GET","/api/mcp/kb/sources")}}}function y(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}var P=["waniwani/sessionId","openai/sessionId","sessionId","conversationId","anthropic/sessionId"],U=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],F=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],W=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],L=["correlationId","openai/requestId"];function k(e){return e?y(e,P):void 0}function w(e){return e?y(e,U):void 0}function b(e){return e?y(e,F):void 0}function R(e){return e?y(e,W):void 0}function x(e){return e?y(e,L):void 0}var K=[{key:"waniwani/sessionId",source:"chatbar"},{key:"openai/sessionId",source:"chatgpt"},{key:"anthropic/sessionId",source:"claude"}];function M(e){if(e)for(let{key:t,source:n}of K){let r=e[t];if(typeof r=="string"&&r.length>0)return n}}var O="@waniwani/sdk";function T(e,t={}){let n=t.now??(()=>new Date),r=t.generateId??_,s=N(e),i=v(e.meta),a=v(e.metadata),o=z(e,i),d=c(e.eventId)??r(),m=Y(e.timestamp,n),l=c(e.source)??M(i)??t.source??O,f=E(e)?{...e}:void 0,u={...a};return Object.keys(i).length>0&&(u.meta=i),f&&(u.rawLegacy=f),{id:d,type:"mcp.event",name:s,source:l,timestamp:m,correlation:o,properties:j(e,s),metadata:u,rawLegacy:f}}function _(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function j(e,t){if(!E(e))return v(e.properties);let n=q(e,t),r=v(e.properties);return{...n,...r}}function q(e,t){switch(t){case"tool.called":{let n={};return c(e.toolName)&&(n.name=e.toolName),c(e.toolType)&&(n.type=e.toolType),n}case"quote.succeeded":{let n={};return typeof e.quoteAmount=="number"&&(n.amount=e.quoteAmount),c(e.quoteCurrency)&&(n.currency=e.quoteCurrency),n}case"link.clicked":{let n={};return c(e.linkUrl)&&(n.url=e.linkUrl),n}case"purchase.completed":{let n={};return typeof e.purchaseAmount=="number"&&(n.amount=e.purchaseAmount),c(e.purchaseCurrency)&&(n.currency=e.purchaseCurrency),n}default:return{}}}function N(e){return E(e)?e.eventType:e.event}function z(e,t){let n=c(e.requestId)??w(t),r=c(e.sessionId)??k(t),s=c(e.traceId)??b(t),i=c(e.externalUserId)??R(t),a=c(e.correlationId)??x(t)??n,o={};return r&&(o.sessionId=r),s&&(o.traceId=s),n&&(o.requestId=n),a&&(o.correlationId=a),i&&(o.externalUserId=i),o}function Y(e,t){if(e instanceof Date)return e.toISOString();if(typeof e=="string"){let n=new Date(e);if(!Number.isNaN(n.getTime()))return n.toISOString()}return t().toISOString()}function v(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function c(e){if(typeof e=="string"&&e.trim().length!==0)return e}function E(e){return"eventType"in e}var $="/api/mcp/events/v2/batch";var D="@waniwani/sdk",H=new Set([401,403]),X=new Set([408,425,429,500,502,503,504]);function A(e){return new I(e)}var I=class{endpointUrl;flushIntervalMs;maxBatchSize;maxBufferSize;maxRetries;retryBaseDelayMs;retryMaxDelayMs;shutdownTimeoutMs;sdkVersion;fetchFn;logger;now;sleep;apiKey;buffer=[];flushTimer;flushScheduled=!1;flushScheduledTimer;flushInFlight;inFlightCount=0;isStopped=!1;isShuttingDown=!1;constructor(t){this.endpointUrl=Z(t.baseUrl,t.endpointPath??$),this.flushIntervalMs=t.flushIntervalMs??1e3,this.maxBatchSize=t.maxBatchSize??20,this.maxBufferSize=t.maxBufferSize??1e3,this.maxRetries=t.maxRetries??3,this.retryBaseDelayMs=t.retryBaseDelayMs??200,this.retryMaxDelayMs=t.retryMaxDelayMs??2e3,this.shutdownTimeoutMs=t.shutdownTimeoutMs??2e3,this.fetchFn=t.fetchFn??fetch,this.logger=t.logger??console,this.now=t.now??(()=>new Date),this.sleep=t.sleep??(n=>new Promise(r=>setTimeout(r,n))),this.apiKey=t.apiKey,this.sdkVersion=t.sdkVersion,this.flushIntervalMs>0&&(this.flushTimer=setInterval(()=>{this.flush()},this.flushIntervalMs))}enqueue(t){if(this.isStopped||this.isShuttingDown){this.logger.warn("[WaniWani] Tracking transport is stopped, dropping event %s",t.id);return}if(this.buffer.length>=this.maxBufferSize){let n=this.buffer.length-this.maxBufferSize+1;this.buffer.splice(0,n),this.logger.warn("[WaniWani] Tracking buffer overflow, dropped %d oldest event(s)",n)}if(this.buffer.push(t),this.buffer.length>=this.maxBatchSize){this.flush();return}this.scheduleMicroFlush()}pendingEvents(){return this.buffer.length+this.inFlightCount}async flush(){return this.flushInFlight?this.flushInFlight:(this.flushInFlight=this.flushLoop().finally(()=>{this.flushInFlight=void 0}),this.flushInFlight)}async shutdown(t){this.isShuttingDown=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=void 0),this.flushScheduledTimer&&(clearTimeout(this.flushScheduledTimer),this.flushScheduledTimer=void 0,this.flushScheduled=!1);let n=t?.timeoutMs??this.shutdownTimeoutMs,r=this.flush();if(!Number.isFinite(n)||n<=0)return await r,this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()};let s=Symbol("shutdown-timeout");return await Promise.race([r.then(()=>"flushed"),this.sleep(n).then(()=>s)])===s?(this.isStopped=!0,{timedOut:!0,pendingEvents:this.pendingEvents()}):(this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()})}scheduleMicroFlush(){this.flushScheduled||(this.flushScheduled=!0,this.flushScheduledTimer=setTimeout(()=>{this.flushScheduledTimer=void 0,this.flushScheduled=!1,this.flush()},0))}async flushLoop(){for(;this.buffer.length>0&&!this.isStopped;){let t=this.buffer.splice(0,this.maxBatchSize);await this.sendBatchWithRetry(t)}}async sendBatchWithRetry(t){let n=0,r=t;for(;r.length>0&&!this.isStopped;){this.inFlightCount=r.length;let s=await this.sendBatchOnce(r);switch(this.inFlightCount=0,s.kind){case"success":return;case"auth":this.stopTransportForAuthFailure(s.status,r.length);return;case"permanent":this.logger.error("[WaniWani] Dropping %d event(s) after permanent failure: %s",r.length,s.reason);return;case"retryable":if(n>=this.maxRetries){this.logger.error("[WaniWani] Dropping %d event(s) after retry exhaustion: %s",r.length,s.reason);return}await this.sleep(this.backoffDelayMs(n)),n+=1;continue;case"partial":if(s.permanent.length>0&&this.logger.error("[WaniWani] Dropping %d event(s) rejected as permanent",s.permanent.length),s.retryable.length===0)return;if(n>=this.maxRetries){this.logger.error("[WaniWani] Dropping %d retryable event(s) after retry exhaustion",s.retryable.length);return}r=s.retryable,await this.sleep(this.backoffDelayMs(n)),n+=1;continue}}}async sendBatchOnce(t){let n;try{n=await this.fetchFn(this.endpointUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-WaniWani-SDK":D},body:JSON.stringify(this.makeBatchRequest(t))})}catch(i){return{kind:"retryable",reason:Q(i)}}if(H.has(n.status))return{kind:"auth",status:n.status};if(X.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let r=await J(n);if(!r?.rejected||r.rejected.length===0)return{kind:"success"};let s=this.classifyRejectedEvents(t,r.rejected);return s.retryable.length===0&&s.permanent.length===0?{kind:"success"}:{kind:"partial",retryable:s.retryable,permanent:s.permanent}}makeBatchRequest(t){return{sentAt:this.now().toISOString(),source:{sdk:D,version:this.sdkVersion??"0.0.0"},events:t}}classifyRejectedEvents(t,n){let r=new Map(t.map(a=>[a.id,a])),s=[],i=[];for(let a of n){let o=r.get(a.eventId);if(o){if(G(a)){s.push(o);continue}i.push(o)}}return{retryable:s,permanent:i}}backoffDelayMs(t){let n=this.retryBaseDelayMs*2**t;return Math.min(n,this.retryMaxDelayMs)}stopTransportForAuthFailure(t,n){this.isStopped=!0;let r=this.buffer.length;this.buffer.splice(0,r),this.logger.error("[WaniWani] Auth failure (HTTP %d). Stopping tracking transport and dropping %d queued event(s)",t,n+r)}};function G(e){if(e.retryable===!0)return!0;let t=e.code.toLowerCase();return t.includes("timeout")||t.includes("temporary")||t.includes("unavailable")||t.includes("rate_limit")||t.includes("transient")||t.includes("server")}async function J(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function Z(e,t){let n=e.endsWith("/")?e:`${e}/`,r=t.startsWith("/")?t.slice(1):t;return`${n}${r}`}function Q(e){return e instanceof Error?e.message:String(e)}function B(e){let{baseUrl:t,apiKey:n,tracking:r}=e;function s(){if(!n)throw new Error("WANIWANI_API_KEY is not set");return n}let i=n?A({baseUrl:t,apiKey:n,endpointPath:r.endpointPath,flushIntervalMs:r.flushIntervalMs,maxBatchSize:r.maxBatchSize,maxBufferSize:r.maxBufferSize,maxRetries:r.maxRetries,retryBaseDelayMs:r.retryBaseDelayMs,retryMaxDelayMs:r.retryMaxDelayMs,shutdownTimeoutMs:r.shutdownTimeoutMs}):void 0,a={async identify(o,d,m){s();let l=T({event:"user.identified",externalUserId:o,properties:d,meta:m});return i?.enqueue(l),{eventId:l.id}},async track(o){s();let d=T(o);return i?.enqueue(d),{eventId:d.id}},async flush(){s(),await i?.flush()},async shutdown(o){return s(),await i?.shutdown({timeoutMs:o?.timeoutMs??r.shutdownTimeoutMs})??{timedOut:!1,pendingEvents:0}}};return i&&ee(a,r.shutdownTimeoutMs),a}function ee(e,t){if(typeof process>"u"||typeof process.once!="function"||typeof process.on!="function")return;let n=()=>{e.shutdown({timeoutMs:t})};process.once("beforeExit",n),process.once("SIGINT",n),process.once("SIGTERM",n)}function te(e){let t=e?.baseUrl??"https://app.waniwani.ai",n=e?.apiKey??process.env.WANIWANI_API_KEY,r={endpointPath:e?.tracking?.endpointPath??"/api/mcp/events/v2/batch",flushIntervalMs:e?.tracking?.flushIntervalMs??1e3,maxBatchSize:e?.tracking?.maxBatchSize??20,maxBufferSize:e?.tracking?.maxBufferSize??1e3,maxRetries:e?.tracking?.maxRetries??3,retryBaseDelayMs:e?.tracking?.retryBaseDelayMs??200,retryMaxDelayMs:e?.tracking?.retryMaxDelayMs??2e3,shutdownTimeoutMs:e?.tracking?.shutdownTimeoutMs??2e3},s={baseUrl:t,apiKey:n,tracking:r},i=B(s),a=S(s);return{...i,kb:a,_config:s}}export{g as WaniWaniError,te as waniwani};
1
+ var m=class extends Error{constructor(n,r){super(n);this.status=r;this.name="WaniWaniError"}};var V="@waniwani/sdk";function S(e){let{baseUrl:t,apiKey:n}=e;function r(){if(!n)throw new Error("WANIWANI_API_KEY is not set");return n}async function s(i,a,o){let d=r(),g=`${t.replace(/\/$/,"")}${a}`,l={Authorization:`Bearer ${d}`,"X-WaniWani-SDK":V},f={method:i,headers:l};o!==void 0&&(l["Content-Type"]="application/json",f.body=JSON.stringify(o));let u=await fetch(g,f);if(!u.ok){let C=await u.text().catch(()=>"");throw new m(C||`KB API error: HTTP ${u.status}`,u.status)}return(await u.json()).data}return{async ingest(i){return s("POST","/api/mcp/kb/ingest",{files:i})},async search(i,a){return s("POST","/api/mcp/kb/search",{query:i,...a})},async sources(){return s("GET","/api/mcp/kb/sources")}}}function y(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}var P=["waniwani/sessionId","openai/sessionId","sessionId","conversationId","anthropic/sessionId"],U=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],F=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],W=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],L=["correlationId","openai/requestId"];function k(e){return e?y(e,P):void 0}function w(e){return e?y(e,U):void 0}function b(e){return e?y(e,F):void 0}function R(e){return e?y(e,W):void 0}function x(e){return e?y(e,L):void 0}var K=[{key:"waniwani/sessionId",source:"chatbar"},{key:"openai/sessionId",source:"chatgpt"},{key:"anthropic/sessionId",source:"claude"}];function M(e){if(!e)return;let t=e["waniwani/source"];if(typeof t=="string"&&t.length>0)return t;for(let{key:n,source:r}of K){let s=e[n];if(typeof s=="string"&&s.length>0)return r}}var O="@waniwani/sdk";function T(e,t={}){let n=t.now??(()=>new Date),r=t.generateId??_,s=N(e),i=v(e.meta),a=v(e.metadata),o=z(e,i),d=c(e.eventId)??r(),g=Y(e.timestamp,n),l=c(e.source)??M(i)??t.source??O,f=E(e)?{...e}:void 0,u={...a};return Object.keys(i).length>0&&(u.meta=i),f&&(u.rawLegacy=f),{id:d,type:"mcp.event",name:s,source:l,timestamp:g,correlation:o,properties:j(e,s),metadata:u,rawLegacy:f}}function _(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function j(e,t){if(!E(e))return v(e.properties);let n=q(e,t),r=v(e.properties);return{...n,...r}}function q(e,t){switch(t){case"tool.called":{let n={};return c(e.toolName)&&(n.name=e.toolName),c(e.toolType)&&(n.type=e.toolType),n}case"quote.succeeded":{let n={};return typeof e.quoteAmount=="number"&&(n.amount=e.quoteAmount),c(e.quoteCurrency)&&(n.currency=e.quoteCurrency),n}case"link.clicked":{let n={};return c(e.linkUrl)&&(n.url=e.linkUrl),n}case"purchase.completed":{let n={};return typeof e.purchaseAmount=="number"&&(n.amount=e.purchaseAmount),c(e.purchaseCurrency)&&(n.currency=e.purchaseCurrency),n}default:return{}}}function N(e){return E(e)?e.eventType:e.event}function z(e,t){let n=c(e.requestId)??w(t),r=c(e.sessionId)??k(t),s=c(e.traceId)??b(t),i=c(e.externalUserId)??R(t),a=c(e.correlationId)??x(t)??n,o={};return r&&(o.sessionId=r),s&&(o.traceId=s),n&&(o.requestId=n),a&&(o.correlationId=a),i&&(o.externalUserId=i),o}function Y(e,t){if(e instanceof Date)return e.toISOString();if(typeof e=="string"){let n=new Date(e);if(!Number.isNaN(n.getTime()))return n.toISOString()}return t().toISOString()}function v(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function c(e){if(typeof e=="string"&&e.trim().length!==0)return e}function E(e){return"eventType"in e}var $="/api/mcp/events/v2/batch";var D="@waniwani/sdk",H=new Set([401,403]),X=new Set([408,425,429,500,502,503,504]);function A(e){return new I(e)}var I=class{endpointUrl;flushIntervalMs;maxBatchSize;maxBufferSize;maxRetries;retryBaseDelayMs;retryMaxDelayMs;shutdownTimeoutMs;sdkVersion;fetchFn;logger;now;sleep;apiKey;buffer=[];flushTimer;flushScheduled=!1;flushScheduledTimer;flushInFlight;inFlightCount=0;isStopped=!1;isShuttingDown=!1;constructor(t){this.endpointUrl=Z(t.baseUrl,t.endpointPath??$),this.flushIntervalMs=t.flushIntervalMs??1e3,this.maxBatchSize=t.maxBatchSize??20,this.maxBufferSize=t.maxBufferSize??1e3,this.maxRetries=t.maxRetries??3,this.retryBaseDelayMs=t.retryBaseDelayMs??200,this.retryMaxDelayMs=t.retryMaxDelayMs??2e3,this.shutdownTimeoutMs=t.shutdownTimeoutMs??2e3,this.fetchFn=t.fetchFn??fetch,this.logger=t.logger??console,this.now=t.now??(()=>new Date),this.sleep=t.sleep??(n=>new Promise(r=>setTimeout(r,n))),this.apiKey=t.apiKey,this.sdkVersion=t.sdkVersion,this.flushIntervalMs>0&&(this.flushTimer=setInterval(()=>{this.flush()},this.flushIntervalMs))}enqueue(t){if(this.isStopped||this.isShuttingDown){this.logger.warn("[WaniWani] Tracking transport is stopped, dropping event %s",t.id);return}if(this.buffer.length>=this.maxBufferSize){let n=this.buffer.length-this.maxBufferSize+1;this.buffer.splice(0,n),this.logger.warn("[WaniWani] Tracking buffer overflow, dropped %d oldest event(s)",n)}if(this.buffer.push(t),this.buffer.length>=this.maxBatchSize){this.flush();return}this.scheduleMicroFlush()}pendingEvents(){return this.buffer.length+this.inFlightCount}async flush(){return this.flushInFlight?this.flushInFlight:(this.flushInFlight=this.flushLoop().finally(()=>{this.flushInFlight=void 0}),this.flushInFlight)}async shutdown(t){this.isShuttingDown=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=void 0),this.flushScheduledTimer&&(clearTimeout(this.flushScheduledTimer),this.flushScheduledTimer=void 0,this.flushScheduled=!1);let n=t?.timeoutMs??this.shutdownTimeoutMs,r=this.flush();if(!Number.isFinite(n)||n<=0)return await r,this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()};let s=Symbol("shutdown-timeout");return await Promise.race([r.then(()=>"flushed"),this.sleep(n).then(()=>s)])===s?(this.isStopped=!0,{timedOut:!0,pendingEvents:this.pendingEvents()}):(this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()})}scheduleMicroFlush(){this.flushScheduled||(this.flushScheduled=!0,this.flushScheduledTimer=setTimeout(()=>{this.flushScheduledTimer=void 0,this.flushScheduled=!1,this.flush()},0))}async flushLoop(){for(;this.buffer.length>0&&!this.isStopped;){let t=this.buffer.splice(0,this.maxBatchSize);await this.sendBatchWithRetry(t)}}async sendBatchWithRetry(t){let n=0,r=t;for(;r.length>0&&!this.isStopped;){this.inFlightCount=r.length;let s=await this.sendBatchOnce(r);switch(this.inFlightCount=0,s.kind){case"success":return;case"auth":this.stopTransportForAuthFailure(s.status,r.length);return;case"permanent":this.logger.error("[WaniWani] Dropping %d event(s) after permanent failure: %s",r.length,s.reason);return;case"retryable":if(n>=this.maxRetries){this.logger.error("[WaniWani] Dropping %d event(s) after retry exhaustion: %s",r.length,s.reason);return}await this.sleep(this.backoffDelayMs(n)),n+=1;continue;case"partial":if(s.permanent.length>0&&this.logger.error("[WaniWani] Dropping %d event(s) rejected as permanent",s.permanent.length),s.retryable.length===0)return;if(n>=this.maxRetries){this.logger.error("[WaniWani] Dropping %d retryable event(s) after retry exhaustion",s.retryable.length);return}r=s.retryable,await this.sleep(this.backoffDelayMs(n)),n+=1;continue}}}async sendBatchOnce(t){let n;try{n=await this.fetchFn(this.endpointUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-WaniWani-SDK":D},body:JSON.stringify(this.makeBatchRequest(t))})}catch(i){return{kind:"retryable",reason:Q(i)}}if(H.has(n.status))return{kind:"auth",status:n.status};if(X.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let r=await J(n);if(!r?.rejected||r.rejected.length===0)return{kind:"success"};let s=this.classifyRejectedEvents(t,r.rejected);return s.retryable.length===0&&s.permanent.length===0?{kind:"success"}:{kind:"partial",retryable:s.retryable,permanent:s.permanent}}makeBatchRequest(t){return{sentAt:this.now().toISOString(),source:{sdk:D,version:this.sdkVersion??"0.0.0"},events:t}}classifyRejectedEvents(t,n){let r=new Map(t.map(a=>[a.id,a])),s=[],i=[];for(let a of n){let o=r.get(a.eventId);if(o){if(G(a)){s.push(o);continue}i.push(o)}}return{retryable:s,permanent:i}}backoffDelayMs(t){let n=this.retryBaseDelayMs*2**t;return Math.min(n,this.retryMaxDelayMs)}stopTransportForAuthFailure(t,n){this.isStopped=!0;let r=this.buffer.length;this.buffer.splice(0,r),this.logger.error("[WaniWani] Auth failure (HTTP %d). Stopping tracking transport and dropping %d queued event(s)",t,n+r)}};function G(e){if(e.retryable===!0)return!0;let t=e.code.toLowerCase();return t.includes("timeout")||t.includes("temporary")||t.includes("unavailable")||t.includes("rate_limit")||t.includes("transient")||t.includes("server")}async function J(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function Z(e,t){let n=e.endsWith("/")?e:`${e}/`,r=t.startsWith("/")?t.slice(1):t;return`${n}${r}`}function Q(e){return e instanceof Error?e.message:String(e)}function B(e){let{baseUrl:t,apiKey:n,tracking:r}=e;function s(){if(!n)throw new Error("WANIWANI_API_KEY is not set");return n}let i=n?A({baseUrl:t,apiKey:n,endpointPath:r.endpointPath,flushIntervalMs:r.flushIntervalMs,maxBatchSize:r.maxBatchSize,maxBufferSize:r.maxBufferSize,maxRetries:r.maxRetries,retryBaseDelayMs:r.retryBaseDelayMs,retryMaxDelayMs:r.retryMaxDelayMs,shutdownTimeoutMs:r.shutdownTimeoutMs}):void 0,a={async identify(o,d,g){s();let l=T({event:"user.identified",externalUserId:o,properties:d,meta:g});return i?.enqueue(l),{eventId:l.id}},async track(o){s();let d=T(o);return i?.enqueue(d),{eventId:d.id}},async flush(){s(),await i?.flush()},async shutdown(o){return s(),await i?.shutdown({timeoutMs:o?.timeoutMs??r.shutdownTimeoutMs})??{timedOut:!1,pendingEvents:0}}};return i&&ee(a,r.shutdownTimeoutMs),a}function ee(e,t){if(typeof process>"u"||typeof process.once!="function"||typeof process.on!="function")return;let n=()=>{e.shutdown({timeoutMs:t})};process.once("beforeExit",n),process.once("SIGINT",n),process.once("SIGTERM",n)}function te(e){let t=e?.baseUrl??"https://app.waniwani.ai",n=e?.apiKey??process.env.WANIWANI_API_KEY,r={endpointPath:e?.tracking?.endpointPath??"/api/mcp/events/v2/batch",flushIntervalMs:e?.tracking?.flushIntervalMs??1e3,maxBatchSize:e?.tracking?.maxBatchSize??20,maxBufferSize:e?.tracking?.maxBufferSize??1e3,maxRetries:e?.tracking?.maxRetries??3,retryBaseDelayMs:e?.tracking?.retryBaseDelayMs??200,retryMaxDelayMs:e?.tracking?.retryMaxDelayMs??2e3,shutdownTimeoutMs:e?.tracking?.shutdownTimeoutMs??2e3},s={baseUrl:t,apiKey:n,tracking:r},i=B(s),a=S(s);return{...i,kb:a,_config:s}}export{m as WaniWaniError,te as waniwani};
2
2
  //# sourceMappingURL=index.js.map