drizzle-cube 0.4.18 → 0.4.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  import { Hono as L } from "hono";
2
2
  import { S as V, v as B, b as M, a as z, n as K, p as _, w as U, d as F, g as G, f as X, i as O, c as W, M as Y, e as T, s as I } from "../mcp-transport-m1X1GtwG.js";
3
3
  import { formatCubeResponse as k, handleBatchRequest as Z, formatMetaResponse as ee, formatSqlResponse as D, handleDryRun as J } from "../utils.js";
4
- var re = (C) => {
4
+ var re = (w) => {
5
5
  const y = {
6
6
  ...{
7
7
  origin: "*",
@@ -9,23 +9,23 @@ var re = (C) => {
9
9
  allowHeaders: [],
10
10
  exposeHeaders: []
11
11
  },
12
- ...C
13
- }, H = /* @__PURE__ */ ((l) => typeof l == "string" ? l === "*" ? () => l : (i) => l === i ? i : null : typeof l == "function" ? l : (i) => l.includes(i) ? i : null)(y.origin), f = ((l) => typeof l == "function" ? l : Array.isArray(l) ? () => l : () => [])(y.allowMethods);
12
+ ...w
13
+ }, H = /* @__PURE__ */ ((d) => typeof d == "string" ? d === "*" ? () => d : (i) => d === i ? i : null : typeof d == "function" ? d : (i) => d.includes(i) ? i : null)(y.origin), f = ((d) => typeof d == "function" ? d : Array.isArray(d) ? () => d : () => [])(y.allowMethods);
14
14
  return async function(i, m) {
15
- function g(q, a) {
16
- i.res.headers.set(q, a);
15
+ function q(g, a) {
16
+ i.res.headers.set(g, a);
17
17
  }
18
- const v = await H(i.req.header("origin") || "", i);
19
- if (v && g("Access-Control-Allow-Origin", v), y.credentials && g("Access-Control-Allow-Credentials", "true"), y.exposeHeaders?.length && g("Access-Control-Expose-Headers", y.exposeHeaders.join(",")), i.req.method === "OPTIONS") {
20
- y.origin !== "*" && g("Vary", "Origin"), y.maxAge != null && g("Access-Control-Max-Age", y.maxAge.toString());
21
- const q = await f(i.req.header("origin") || "", i);
22
- q.length && g("Access-Control-Allow-Methods", q.join(","));
18
+ const x = await H(i.req.header("origin") || "", i);
19
+ if (x && q("Access-Control-Allow-Origin", x), y.credentials && q("Access-Control-Allow-Credentials", "true"), y.exposeHeaders?.length && q("Access-Control-Expose-Headers", y.exposeHeaders.join(",")), i.req.method === "OPTIONS") {
20
+ y.origin !== "*" && q("Vary", "Origin"), y.maxAge != null && q("Access-Control-Max-Age", y.maxAge.toString());
21
+ const g = await f(i.req.header("origin") || "", i);
22
+ g.length && q("Access-Control-Allow-Methods", g.join(","));
23
23
  let a = y.allowHeaders;
24
24
  if (!a?.length) {
25
25
  const s = i.req.header("Access-Control-Request-Headers");
26
26
  s && (a = s.split(/\s*,\s*/));
27
27
  }
28
- return a?.length && (g("Access-Control-Allow-Headers", a.join(",")), i.res.headers.append("Vary", "Access-Control-Request-Headers")), i.res.headers.delete("Content-Length"), i.res.headers.delete("Content-Type"), new Response(null, {
28
+ return a?.length && (q("Access-Control-Allow-Headers", a.join(",")), i.res.headers.append("Vary", "Access-Control-Request-Headers")), i.res.headers.delete("Content-Length"), i.res.headers.delete("Content-Type"), new Response(null, {
29
29
  headers: i.res.headers,
30
30
  status: 204,
31
31
  statusText: "No Content"
@@ -34,30 +34,30 @@ var re = (C) => {
34
34
  await m(), y.origin !== "*" && i.header("Vary", "Origin", { append: !0 });
35
35
  };
36
36
  };
37
- function te(C) {
37
+ function te(w) {
38
38
  const {
39
- cubes: j,
39
+ cubes: C,
40
40
  drizzle: y,
41
41
  schema: H,
42
42
  extractSecurityContext: f,
43
- engineType: l,
43
+ engineType: d,
44
44
  cors: i,
45
45
  basePath: m = "/cubejs-api/v1",
46
- cache: g,
47
- mcp: v = { enabled: !0 },
48
- agent: q
49
- } = C;
50
- if (!j || j.length === 0)
46
+ cache: q,
47
+ mcp: x = { enabled: !0 },
48
+ agent: g
49
+ } = w;
50
+ if (!C || C.length === 0)
51
51
  throw new Error("At least one cube must be provided in the cubes array");
52
52
  const a = new L();
53
53
  i && a.use("/*", re(i));
54
54
  const s = new V({
55
55
  drizzle: y,
56
56
  schema: H,
57
- engineType: l,
58
- cache: g
57
+ engineType: d,
58
+ cache: q
59
59
  });
60
- if (j.forEach((r) => {
60
+ if (C.forEach((r) => {
61
61
  s.registerCube(r);
62
62
  }), a.post(`${m}/load`, async (r) => {
63
63
  try {
@@ -210,52 +210,53 @@ function te(C) {
210
210
  error: e instanceof Error ? e.message : "Explain query failed"
211
211
  }, 500);
212
212
  }
213
- }), q && a.post(`${m}/agent/chat`, async (r) => {
213
+ }), g && a.post(`${m}/agent/chat`, async (r) => {
214
214
  try {
215
- const { handleAgentChat: e } = await import("../handler-DefTXJpi.js"), n = await r.req.json(), { message: o, sessionId: t, history: c } = n;
215
+ const { handleAgentChat: e } = await import("../handler-CbDMdSY5.js"), n = await r.req.json(), { message: o, sessionId: t, history: c } = n;
216
216
  if (!o || typeof o != "string")
217
217
  return r.json({ error: "message is required and must be a string" }, 400);
218
- let u = (q.apiKey || "").trim();
219
- if (q.allowClientApiKey) {
220
- const w = r.req.header("x-agent-api-key");
221
- w && (u = w.trim());
218
+ let u = (g.apiKey || "").trim();
219
+ if (g.allowClientApiKey) {
220
+ const j = r.req.header("x-agent-api-key");
221
+ j && (u = j.trim());
222
222
  }
223
223
  if (!u)
224
224
  return r.json({
225
225
  error: "No API key configured. Set agent.apiKey in server config or send X-Agent-Api-Key header."
226
226
  }, 401);
227
- const h = await f(r), x = new TextEncoder(), p = new ReadableStream({
228
- async start(w) {
227
+ const h = await f(r), R = g.buildSystemContext?.(h), p = new TextEncoder(), P = new ReadableStream({
228
+ async start(j) {
229
229
  try {
230
- const b = e({
230
+ const l = e({
231
231
  message: o,
232
232
  sessionId: t,
233
233
  history: c,
234
234
  semanticLayer: s,
235
235
  securityContext: h,
236
- agentConfig: q,
237
- apiKey: u
236
+ agentConfig: g,
237
+ apiKey: u,
238
+ systemContext: R
238
239
  });
239
- for await (const d of b) {
240
- const R = `data: ${JSON.stringify(d)}
240
+ for await (const v of l) {
241
+ const b = `data: ${JSON.stringify(v)}
241
242
 
242
243
  `;
243
- w.enqueue(x.encode(R));
244
+ j.enqueue(p.encode(b));
244
245
  }
245
- } catch (b) {
246
- const d = {
246
+ } catch (l) {
247
+ const v = {
247
248
  type: "error",
248
- data: { message: b instanceof Error ? b.message : "Stream failed" }
249
+ data: { message: l instanceof Error ? l.message : "Stream failed" }
249
250
  };
250
- w.enqueue(x.encode(`data: ${JSON.stringify(d)}
251
+ j.enqueue(p.encode(`data: ${JSON.stringify(v)}
251
252
 
252
253
  `));
253
254
  } finally {
254
- w.close();
255
+ j.close();
255
256
  }
256
257
  }
257
258
  });
258
- return new Response(p, {
259
+ return new Response(P, {
259
260
  status: 200,
260
261
  headers: {
261
262
  "Content-Type": "text/event-stream",
@@ -268,18 +269,18 @@ function te(C) {
268
269
  error: e instanceof Error ? e.message : "Agent chat failed"
269
270
  }, 500);
270
271
  }
271
- }), v.enabled !== !1) {
272
+ }), x.enabled !== !1) {
272
273
  const r = {
273
274
  uri: "drizzle-cube://schema",
274
275
  name: "Cube Schema",
275
276
  description: "Current cube metadata as JSON",
276
277
  mimeType: "application/json",
277
278
  text: JSON.stringify(s.getMetadata(), null, 2)
278
- }, e = [...X(), r], n = G(), o = v.basePath ?? "/mcp";
279
+ }, e = [...X(), r], n = G(), o = x.basePath ?? "/mcp";
279
280
  a.post(`${o}`, async (t) => {
280
281
  const c = B(
281
282
  t.req.header("origin"),
282
- v.allowedOrigins ? { allowedOrigins: v.allowedOrigins } : {}
283
+ x.allowedOrigins ? { allowedOrigins: x.allowedOrigins } : {}
283
284
  );
284
285
  if (!c.valid)
285
286
  return t.json(M(null, -32600, c.reason), 403);
@@ -292,12 +293,12 @@ function te(C) {
292
293
  error: "Unsupported MCP protocol version",
293
294
  supported: h.supported
294
295
  }, 426);
295
- const x = await t.req.json().catch(() => null), p = _(x);
296
+ const R = await t.req.json().catch(() => null), p = _(R);
296
297
  if (!p)
297
298
  return t.json(M(null, -32600, "Invalid JSON-RPC 2.0 request"), 400);
298
- const w = U(u), b = p.method === "initialize";
299
+ const P = U(u), j = p.method === "initialize";
299
300
  try {
300
- const d = await F(
301
+ const l = await F(
301
302
  p.method,
302
303
  p.params,
303
304
  {
@@ -312,13 +313,13 @@ function te(C) {
312
313
  );
313
314
  if (O(p))
314
315
  return t.body(null, 202);
315
- const R = W(p.id ?? null, d), P = b && d && typeof d == "object" && "sessionId" in d ? d.sessionId : void 0, S = {};
316
- if (P && (S[Y] = P), w) {
316
+ const v = W(p.id ?? null, l), b = j && l && typeof l == "object" && "sessionId" in l ? l.sessionId : void 0, S = {};
317
+ if (b && (S[Y] = b), P) {
317
318
  const E = new TextEncoder(), A = T(), $ = new ReadableStream({
318
319
  start(Q) {
319
320
  Q.enqueue(E.encode(`id: ${A}
320
321
 
321
- `)), Q.enqueue(E.encode(I(R, A))), Q.close();
322
+ `)), Q.enqueue(E.encode(I(v, A))), Q.close();
322
323
  }
323
324
  });
324
325
  return new Response($, {
@@ -331,13 +332,13 @@ function te(C) {
331
332
  }
332
333
  });
333
334
  }
334
- return t.json(R, 200, S);
335
- } catch (d) {
335
+ return t.json(v, 200, S);
336
+ } catch (l) {
336
337
  if (O(p))
337
- return console.error("MCP notification processing error:", d), t.body(null, 202);
338
- console.error("MCP RPC error:", d);
339
- const R = d?.code ?? -32603, P = d?.data, S = d.message || "MCP request failed", E = M(p.id ?? null, R, S, P);
340
- if (w) {
338
+ return console.error("MCP notification processing error:", l), t.body(null, 202);
339
+ console.error("MCP RPC error:", l);
340
+ const v = l?.code ?? -32603, b = l?.data, S = l.message || "MCP request failed", E = M(p.id ?? null, v, S, b);
341
+ if (P) {
341
342
  const A = new TextEncoder(), $ = T(), Q = new ReadableStream({
342
343
  start(N) {
343
344
  N.enqueue(A.encode(`id: ${$}
@@ -359,7 +360,7 @@ function te(C) {
359
360
  }), a.delete(`${o}`, (t) => t.json({ error: "Session termination not supported" }, 405)), a.get(`${o}`, (t) => {
360
361
  const c = new TextEncoder(), u = T();
361
362
  let h;
362
- const x = new ReadableStream({
363
+ const R = new ReadableStream({
363
364
  start(p) {
364
365
  p.enqueue(c.encode(I({
365
366
  jsonrpc: "2.0",
@@ -375,7 +376,7 @@ function te(C) {
375
376
  clearInterval(h);
376
377
  }
377
378
  });
378
- return new Response(x, {
379
+ return new Response(R, {
379
380
  status: 200,
380
381
  headers: {
381
382
  "Content-Type": "text/event-stream",
@@ -387,13 +388,13 @@ function te(C) {
387
388
  }
388
389
  return a;
389
390
  }
390
- function ne(C, j) {
391
- const y = te(j);
392
- return C.route("/", y), C;
391
+ function ne(w, C) {
392
+ const y = te(C);
393
+ return w.route("/", y), w;
393
394
  }
394
- function ie(C) {
395
- const j = new L();
396
- return ne(j, C);
395
+ function ie(w) {
396
+ const C = new L();
397
+ return ne(C, w);
397
398
  }
398
399
  export {
399
400
  ie as createCubeApp,
@@ -1,9 +1,9 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("next/server"),f=require("../mcp-transport-8u9G5oNa.cjs"),i=require("../utils.cjs");function j(n){const{cubes:o,drizzle:s,schema:c,engineType:d,cache:a}=n;if(!o||o.length===0)throw new Error("At least one cube must be provided in the cubes array");const t=new f.SemanticLayerCompiler({drizzle:s,schema:c,engineType:d,cache:a});return o.forEach(e=>{t.registerCube(e)}),t}function R(n,o){const s=n.headers.get("origin"),c={};return o.origin&&(typeof o.origin=="string"?c["Access-Control-Allow-Origin"]=o.origin:Array.isArray(o.origin)?s&&o.origin.includes(s)&&(c["Access-Control-Allow-Origin"]=s):typeof o.origin=="function"&&s&&o.origin(s)&&(c["Access-Control-Allow-Origin"]=s)),o.methods&&(c["Access-Control-Allow-Methods"]=o.methods.join(", ")),o.allowedHeaders&&(c["Access-Control-Allow-Headers"]=o.allowedHeaders.join(", ")),o.credentials&&(c["Access-Control-Allow-Credentials"]="true"),c}function J(n){return async function(s){const c=R(s,n);return new Response(null,{status:200,headers:c})}}function T(n){const{extractSecurityContext:o,cors:s}=n,c=j(n);return async function(a,t){try{let e;if(a.method==="POST"){const N=await a.json();e=N.query||N}else if(a.method==="GET"){const N=a.nextUrl.searchParams.get("query");if(!N)return r.NextResponse.json(i.formatErrorResponse("Query parameter is required",400),{status:400});try{e=JSON.parse(N)}catch{return r.NextResponse.json(i.formatErrorResponse("Invalid JSON in query parameter",400),{status:400})}}else return r.NextResponse.json(i.formatErrorResponse("Method not allowed",405),{status:405});const l=await o(a,t),y=c.validateQuery(e);if(!y.isValid)return r.NextResponse.json(i.formatErrorResponse(`Query validation failed: ${y.errors.join(", ")}`,400),{status:400});const u=a.headers.get("x-cache-control")==="no-cache",p=await c.executeMultiCubeQuery(e,l,{skipCache:u}),w=i.formatCubeResponse(e,p,c);return r.NextResponse.json(w,{headers:s?R(a,s):{}})}catch(e){return process.env.NODE_ENV!=="test"&&console.error("Next.js load handler error:",e),r.NextResponse.json(i.formatErrorResponse(e instanceof Error?e.message:"Query execution failed",500),{status:500})}}}function M(n){const{cors:o}=n,s=j(n);return async function(d,a){try{const t=s.getMetadata(),e=i.formatMetaResponse(t);return r.NextResponse.json(e,{headers:o?R(d,o):{}})}catch(t){return process.env.NODE_ENV!=="test"&&console.error("Next.js meta handler error:",t),r.NextResponse.json(i.formatErrorResponse(t instanceof Error?t.message:"Failed to fetch metadata",500),{status:500})}}}function A(n){const{extractSecurityContext:o,cors:s}=n,c=j(n);return async function(a,t){try{let e;if(a.method==="POST"){const v=await a.json();e=v.query||v}else if(a.method==="GET"){const v=a.nextUrl.searchParams.get("query");if(!v)return r.NextResponse.json(i.formatErrorResponse("Query parameter is required",400),{status:400});try{e=JSON.parse(v)}catch{return r.NextResponse.json(i.formatErrorResponse("Invalid JSON in query parameter",400),{status:400})}}else return r.NextResponse.json(i.formatErrorResponse("Method not allowed",405),{status:405});const l=await o(a,t),y=c.validateQuery(e);if(!y.isValid)return r.NextResponse.json(i.formatErrorResponse(`Query validation failed: ${y.errors.join(", ")}`,400),{status:400});const u=e.measures?.[0]||e.dimensions?.[0];if(!u)return r.NextResponse.json(i.formatErrorResponse("No measures or dimensions specified",400),{status:400});const p=u.split(".")[0],w=await c.generateSQL(p,e,l),N=i.formatSqlResponse(e,w);return r.NextResponse.json(N,{headers:s?R(a,s):{}})}catch(e){return process.env.NODE_ENV!=="test"&&console.error("Next.js SQL handler error:",e),r.NextResponse.json(i.formatErrorResponse(e instanceof Error?e.message:"SQL generation failed",500),{status:500})}}}function L(n){const{extractSecurityContext:o,cors:s}=n,c=j(n);return async function(a,t){try{let e;if(a.method==="POST"){const u=await a.json();e=u.query||u}else if(a.method==="GET"){const u=a.nextUrl.searchParams.get("query");if(!u)return r.NextResponse.json({error:"Query parameter is required",valid:!1},{status:400});try{e=JSON.parse(u)}catch{return r.NextResponse.json({error:"Invalid JSON in query parameter",valid:!1},{status:400})}}else return r.NextResponse.json({error:"Method not allowed",valid:!1},{status:405});const l=await o(a,t),y=await i.handleDryRun(e,l,c);return r.NextResponse.json(y,{headers:s?R(a,s):{}})}catch(e){return process.env.NODE_ENV!=="test"&&console.error("Next.js dry-run handler error:",e),r.NextResponse.json({error:e instanceof Error?e.message:"Dry-run validation failed",valid:!1},{status:400})}}}function D(n){const{extractSecurityContext:o,cors:s}=n,c=j(n);return async function(a,t){try{if(a.method!=="POST")return r.NextResponse.json(i.formatErrorResponse("Method not allowed - use POST",405),{status:405});const e=await a.json(),{queries:l}=e;if(!l||!Array.isArray(l))return r.NextResponse.json(i.formatErrorResponse('Request body must contain a "queries" array',400),{status:400});if(l.length===0)return r.NextResponse.json(i.formatErrorResponse("Queries array cannot be empty",400),{status:400});const y=await o(a,t),u=a.headers.get("x-cache-control")==="no-cache",p=await i.handleBatchRequest(l,y,c,{skipCache:u});return r.NextResponse.json(p,{headers:s?R(a,s):{}})}catch(e){return process.env.NODE_ENV!=="test"&&console.error("Next.js batch handler error:",e),r.NextResponse.json(i.formatErrorResponse(e instanceof Error?e.message:"Batch execution failed",500),{status:500})}}}function V(n){const{extractSecurityContext:o,cors:s}=n,c=j(n);return async function(a,t){try{if(a.method!=="POST")return r.NextResponse.json({error:"Method not allowed"},{status:405});const e=await a.json(),l=e.query||e,y=e.options||{},u=await o(a,t),p=c.validateQuery(l);if(!p.isValid)return r.NextResponse.json({error:`Query validation failed: ${p.errors.join(", ")}`},{status:400});const w=await c.explainQuery(l,u,y);return r.NextResponse.json(w,{headers:s?R(a,s):{}})}catch(e){return process.env.NODE_ENV!=="test"&&console.error("Next.js explain handler error:",e),r.NextResponse.json({error:e instanceof Error?e.message:"Explain query failed"},{status:500})}}}function k(n){const{cors:o}=n,s=j(n);return async function(d,a){try{if(d.method!=="POST")return r.NextResponse.json(i.formatErrorResponse("Method not allowed - use POST",405),{status:405});const t=await d.json(),e=await i.handleDiscover(s,t);return r.NextResponse.json(e,{headers:o?R(d,o):{}})}catch(t){return process.env.NODE_ENV!=="test"&&console.error("Next.js discover handler error:",t),r.NextResponse.json(i.formatErrorResponse(t instanceof Error?t.message:"Discovery failed",500),{status:500})}}}function q(n){const{cors:o}=n,s=j(n);return async function(d,a){try{if(d.method!=="POST")return r.NextResponse.json(i.formatErrorResponse("Method not allowed - use POST",405),{status:405});const t=await d.json();if(!t.naturalLanguage)return r.NextResponse.json(i.formatErrorResponse("naturalLanguage field is required",400),{status:400});const e=await i.handleSuggest(s,t);return r.NextResponse.json(e,{headers:o?R(d,o):{}})}catch(t){return process.env.NODE_ENV!=="test"&&console.error("Next.js suggest handler error:",t),r.NextResponse.json(i.formatErrorResponse(t instanceof Error?t.message:"Query suggestion failed",500),{status:500})}}}function z(n){const{cors:o}=n,s=j(n);return async function(d,a){try{if(d.method!=="POST")return r.NextResponse.json(i.formatErrorResponse("Method not allowed - use POST",405),{status:405});const t=await d.json();if(!t.query)return r.NextResponse.json(i.formatErrorResponse("query field is required",400),{status:400});const e=await i.handleValidate(s,t);return r.NextResponse.json(e,{headers:o?R(d,o):{}})}catch(t){return process.env.NODE_ENV!=="test"&&console.error("Next.js validate handler error:",t),r.NextResponse.json(i.formatErrorResponse(t instanceof Error?t.message:"Query validation failed",500),{status:500})}}}function $(n){const{extractSecurityContext:o,cors:s}=n,c=j(n);return async function(a,t){try{if(a.method!=="POST")return r.NextResponse.json(i.formatErrorResponse("Method not allowed - use POST",405),{status:405});const e=await a.json();if(!e.query)return r.NextResponse.json(i.formatErrorResponse("query field is required",400),{status:400});const l=await o(a,t),y=await i.handleLoad(c,l,e);return r.NextResponse.json(y,{headers:s?R(a,s):{}})}catch(e){return process.env.NODE_ENV!=="test"&&console.error("Next.js MCP load handler error:",e),r.NextResponse.json(i.formatErrorResponse(e instanceof Error?e.message:"Query execution failed",500),{status:500})}}}function _(n){const{extractSecurityContext:o,cors:s,mcp:c={enabled:!0}}=n,d=j(n);return async function(t){if(t.method==="DELETE")return r.NextResponse.json({error:"Session termination not supported"},{status:405});if(t.method==="GET"){const m=new TextEncoder,C=f.primeEventId(),g=new ReadableStream({start(h){h.enqueue(m.encode(f.serializeSseEvent({jsonrpc:"2.0",method:"mcp/ready",params:{protocol:"streamable-http"}},C,15e3)))}}),x=new Headers({"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});if(s){const h=R(t,s);Object.entries(h).forEach(([E,S])=>x.set(E,S))}return new r.NextResponse(g,{status:200,headers:x})}if(t.method!=="POST")return r.NextResponse.json(i.formatErrorResponse("Method not allowed - use POST",405),{status:405});const e=f.validateOriginHeader(t.headers.get("origin"),c.allowedOrigins?{allowedOrigins:c.allowedOrigins}:{});if(!e.valid)return r.NextResponse.json(f.buildJsonRpcError(null,-32600,e.reason),{status:403});const l=t.headers.get("accept");if(!f.validateAcceptHeader(l))return r.NextResponse.json(f.buildJsonRpcError(null,-32600,"Accept header must include both application/json and text/event-stream"),{status:400});const y=f.negotiateProtocol(Object.fromEntries(t.headers.entries()));if(!y.ok)return r.NextResponse.json({error:"Unsupported MCP protocol version",supported:y.supported},{status:426});let u;try{u=await t.json()}catch{u=null}const p=f.parseJsonRpc(u);if(!p)return r.NextResponse.json(f.buildJsonRpcError(null,-32600,"Invalid JSON-RPC 2.0 request"),{status:400});const w=f.wantsEventStream(l),N=p.method==="initialize",v=(m,C=200,g={})=>r.NextResponse.json(m,{status:C,headers:{...s?R(t,s):{},...g}});try{const m=await f.dispatchMcpMethod(p.method,p.params,{semanticLayer:d,extractSecurityContext:h=>o(h),rawRequest:t,rawResponse:null});if(f.isNotification(p))return new r.NextResponse(null,{status:202});const C=N&&m&&typeof m=="object"&&"sessionId"in m?m.sessionId:void 0,g={};C&&(g[f.MCP_SESSION_ID_HEADER]=C);const x=f.buildJsonRpcResult(p.id??null,m);if(w){const h=new TextEncoder,E=f.primeEventId(),S=new ReadableStream({start(H){H.enqueue(h.encode(`id: ${E}
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("next/server"),f=require("../mcp-transport-8u9G5oNa.cjs"),i=require("../utils.cjs");function g(n){const{cubes:o,drizzle:s,schema:c,engineType:d,cache:a}=n;if(!o||o.length===0)throw new Error("At least one cube must be provided in the cubes array");const r=new f.SemanticLayerCompiler({drizzle:s,schema:c,engineType:d,cache:a});return o.forEach(e=>{r.registerCube(e)}),r}function x(n,o){const s=n.headers.get("origin"),c={};return o.origin&&(typeof o.origin=="string"?c["Access-Control-Allow-Origin"]=o.origin:Array.isArray(o.origin)?s&&o.origin.includes(s)&&(c["Access-Control-Allow-Origin"]=s):typeof o.origin=="function"&&s&&o.origin(s)&&(c["Access-Control-Allow-Origin"]=s)),o.methods&&(c["Access-Control-Allow-Methods"]=o.methods.join(", ")),o.allowedHeaders&&(c["Access-Control-Allow-Headers"]=o.allowedHeaders.join(", ")),o.credentials&&(c["Access-Control-Allow-Credentials"]="true"),c}function J(n){return async function(s){const c=x(s,n);return new Response(null,{status:200,headers:c})}}function T(n){const{extractSecurityContext:o,cors:s}=n,c=g(n);return async function(a,r){try{let e;if(a.method==="POST"){const N=await a.json();e=N.query||N}else if(a.method==="GET"){const N=a.nextUrl.searchParams.get("query");if(!N)return t.NextResponse.json(i.formatErrorResponse("Query parameter is required",400),{status:400});try{e=JSON.parse(N)}catch{return t.NextResponse.json(i.formatErrorResponse("Invalid JSON in query parameter",400),{status:400})}}else return t.NextResponse.json(i.formatErrorResponse("Method not allowed",405),{status:405});const l=await o(a,r),m=c.validateQuery(e);if(!m.isValid)return t.NextResponse.json(i.formatErrorResponse(`Query validation failed: ${m.errors.join(", ")}`,400),{status:400});const u=a.headers.get("x-cache-control")==="no-cache",y=await c.executeMultiCubeQuery(e,l,{skipCache:u}),C=i.formatCubeResponse(e,y,c);return t.NextResponse.json(C,{headers:s?x(a,s):{}})}catch(e){return process.env.NODE_ENV!=="test"&&console.error("Next.js load handler error:",e),t.NextResponse.json(i.formatErrorResponse(e instanceof Error?e.message:"Query execution failed",500),{status:500})}}}function M(n){const{cors:o}=n,s=g(n);return async function(d,a){try{const r=s.getMetadata(),e=i.formatMetaResponse(r);return t.NextResponse.json(e,{headers:o?x(d,o):{}})}catch(r){return process.env.NODE_ENV!=="test"&&console.error("Next.js meta handler error:",r),t.NextResponse.json(i.formatErrorResponse(r instanceof Error?r.message:"Failed to fetch metadata",500),{status:500})}}}function A(n){const{extractSecurityContext:o,cors:s}=n,c=g(n);return async function(a,r){try{let e;if(a.method==="POST"){const j=await a.json();e=j.query||j}else if(a.method==="GET"){const j=a.nextUrl.searchParams.get("query");if(!j)return t.NextResponse.json(i.formatErrorResponse("Query parameter is required",400),{status:400});try{e=JSON.parse(j)}catch{return t.NextResponse.json(i.formatErrorResponse("Invalid JSON in query parameter",400),{status:400})}}else return t.NextResponse.json(i.formatErrorResponse("Method not allowed",405),{status:405});const l=await o(a,r),m=c.validateQuery(e);if(!m.isValid)return t.NextResponse.json(i.formatErrorResponse(`Query validation failed: ${m.errors.join(", ")}`,400),{status:400});const u=e.measures?.[0]||e.dimensions?.[0];if(!u)return t.NextResponse.json(i.formatErrorResponse("No measures or dimensions specified",400),{status:400});const y=u.split(".")[0],C=await c.generateSQL(y,e,l),N=i.formatSqlResponse(e,C);return t.NextResponse.json(N,{headers:s?x(a,s):{}})}catch(e){return process.env.NODE_ENV!=="test"&&console.error("Next.js SQL handler error:",e),t.NextResponse.json(i.formatErrorResponse(e instanceof Error?e.message:"SQL generation failed",500),{status:500})}}}function L(n){const{extractSecurityContext:o,cors:s}=n,c=g(n);return async function(a,r){try{let e;if(a.method==="POST"){const u=await a.json();e=u.query||u}else if(a.method==="GET"){const u=a.nextUrl.searchParams.get("query");if(!u)return t.NextResponse.json({error:"Query parameter is required",valid:!1},{status:400});try{e=JSON.parse(u)}catch{return t.NextResponse.json({error:"Invalid JSON in query parameter",valid:!1},{status:400})}}else return t.NextResponse.json({error:"Method not allowed",valid:!1},{status:405});const l=await o(a,r),m=await i.handleDryRun(e,l,c);return t.NextResponse.json(m,{headers:s?x(a,s):{}})}catch(e){return process.env.NODE_ENV!=="test"&&console.error("Next.js dry-run handler error:",e),t.NextResponse.json({error:e instanceof Error?e.message:"Dry-run validation failed",valid:!1},{status:400})}}}function D(n){const{extractSecurityContext:o,cors:s}=n,c=g(n);return async function(a,r){try{if(a.method!=="POST")return t.NextResponse.json(i.formatErrorResponse("Method not allowed - use POST",405),{status:405});const e=await a.json(),{queries:l}=e;if(!l||!Array.isArray(l))return t.NextResponse.json(i.formatErrorResponse('Request body must contain a "queries" array',400),{status:400});if(l.length===0)return t.NextResponse.json(i.formatErrorResponse("Queries array cannot be empty",400),{status:400});const m=await o(a,r),u=a.headers.get("x-cache-control")==="no-cache",y=await i.handleBatchRequest(l,m,c,{skipCache:u});return t.NextResponse.json(y,{headers:s?x(a,s):{}})}catch(e){return process.env.NODE_ENV!=="test"&&console.error("Next.js batch handler error:",e),t.NextResponse.json(i.formatErrorResponse(e instanceof Error?e.message:"Batch execution failed",500),{status:500})}}}function V(n){const{extractSecurityContext:o,cors:s}=n,c=g(n);return async function(a,r){try{if(a.method!=="POST")return t.NextResponse.json({error:"Method not allowed"},{status:405});const e=await a.json(),l=e.query||e,m=e.options||{},u=await o(a,r),y=c.validateQuery(l);if(!y.isValid)return t.NextResponse.json({error:`Query validation failed: ${y.errors.join(", ")}`},{status:400});const C=await c.explainQuery(l,u,m);return t.NextResponse.json(C,{headers:s?x(a,s):{}})}catch(e){return process.env.NODE_ENV!=="test"&&console.error("Next.js explain handler error:",e),t.NextResponse.json({error:e instanceof Error?e.message:"Explain query failed"},{status:500})}}}function k(n){const{cors:o}=n,s=g(n);return async function(d,a){try{if(d.method!=="POST")return t.NextResponse.json(i.formatErrorResponse("Method not allowed - use POST",405),{status:405});const r=await d.json(),e=await i.handleDiscover(s,r);return t.NextResponse.json(e,{headers:o?x(d,o):{}})}catch(r){return process.env.NODE_ENV!=="test"&&console.error("Next.js discover handler error:",r),t.NextResponse.json(i.formatErrorResponse(r instanceof Error?r.message:"Discovery failed",500),{status:500})}}}function q(n){const{cors:o}=n,s=g(n);return async function(d,a){try{if(d.method!=="POST")return t.NextResponse.json(i.formatErrorResponse("Method not allowed - use POST",405),{status:405});const r=await d.json();if(!r.naturalLanguage)return t.NextResponse.json(i.formatErrorResponse("naturalLanguage field is required",400),{status:400});const e=await i.handleSuggest(s,r);return t.NextResponse.json(e,{headers:o?x(d,o):{}})}catch(r){return process.env.NODE_ENV!=="test"&&console.error("Next.js suggest handler error:",r),t.NextResponse.json(i.formatErrorResponse(r instanceof Error?r.message:"Query suggestion failed",500),{status:500})}}}function z(n){const{cors:o}=n,s=g(n);return async function(d,a){try{if(d.method!=="POST")return t.NextResponse.json(i.formatErrorResponse("Method not allowed - use POST",405),{status:405});const r=await d.json();if(!r.query)return t.NextResponse.json(i.formatErrorResponse("query field is required",400),{status:400});const e=await i.handleValidate(s,r);return t.NextResponse.json(e,{headers:o?x(d,o):{}})}catch(r){return process.env.NODE_ENV!=="test"&&console.error("Next.js validate handler error:",r),t.NextResponse.json(i.formatErrorResponse(r instanceof Error?r.message:"Query validation failed",500),{status:500})}}}function $(n){const{extractSecurityContext:o,cors:s}=n,c=g(n);return async function(a,r){try{if(a.method!=="POST")return t.NextResponse.json(i.formatErrorResponse("Method not allowed - use POST",405),{status:405});const e=await a.json();if(!e.query)return t.NextResponse.json(i.formatErrorResponse("query field is required",400),{status:400});const l=await o(a,r),m=await i.handleLoad(c,l,e);return t.NextResponse.json(m,{headers:s?x(a,s):{}})}catch(e){return process.env.NODE_ENV!=="test"&&console.error("Next.js MCP load handler error:",e),t.NextResponse.json(i.formatErrorResponse(e instanceof Error?e.message:"Query execution failed",500),{status:500})}}}function _(n){const{extractSecurityContext:o,cors:s,mcp:c={enabled:!0}}=n,d=g(n);return async function(r){if(r.method==="DELETE")return t.NextResponse.json({error:"Session termination not supported"},{status:405});if(r.method==="GET"){const h=new TextEncoder,w=f.primeEventId(),v=new ReadableStream({start(p){p.enqueue(h.encode(f.serializeSseEvent({jsonrpc:"2.0",method:"mcp/ready",params:{protocol:"streamable-http"}},w,15e3)))}}),S=new Headers({"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});if(s){const p=x(r,s);Object.entries(p).forEach(([R,E])=>S.set(R,E))}return new t.NextResponse(v,{status:200,headers:S})}if(r.method!=="POST")return t.NextResponse.json(i.formatErrorResponse("Method not allowed - use POST",405),{status:405});const e=f.validateOriginHeader(r.headers.get("origin"),c.allowedOrigins?{allowedOrigins:c.allowedOrigins}:{});if(!e.valid)return t.NextResponse.json(f.buildJsonRpcError(null,-32600,e.reason),{status:403});const l=r.headers.get("accept");if(!f.validateAcceptHeader(l))return t.NextResponse.json(f.buildJsonRpcError(null,-32600,"Accept header must include both application/json and text/event-stream"),{status:400});const m=f.negotiateProtocol(Object.fromEntries(r.headers.entries()));if(!m.ok)return t.NextResponse.json({error:"Unsupported MCP protocol version",supported:m.supported},{status:426});let u;try{u=await r.json()}catch{u=null}const y=f.parseJsonRpc(u);if(!y)return t.NextResponse.json(f.buildJsonRpcError(null,-32600,"Invalid JSON-RPC 2.0 request"),{status:400});const C=f.wantsEventStream(l),N=y.method==="initialize",j=(h,w=200,v={})=>t.NextResponse.json(h,{status:w,headers:{...s?x(r,s):{},...v}});try{const h=await f.dispatchMcpMethod(y.method,y.params,{semanticLayer:d,extractSecurityContext:p=>o(p),rawRequest:r,rawResponse:null});if(f.isNotification(y))return new t.NextResponse(null,{status:202});const w=N&&h&&typeof h=="object"&&"sessionId"in h?h.sessionId:void 0,v={};w&&(v[f.MCP_SESSION_ID_HEADER]=w);const S=f.buildJsonRpcResult(y.id??null,h);if(C){const p=new TextEncoder,R=f.primeEventId(),E=new ReadableStream({start(H){H.enqueue(p.encode(`id: ${R}
2
2
 
3
- `)),H.enqueue(h.encode(f.serializeSseEvent(x,E))),H.close()}}),O=new Headers({"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive",...g});if(s){const H=R(t,s);Object.entries(H).forEach(([b,P])=>O.set(b,P))}return new r.NextResponse(S,{status:200,headers:O})}return v(x,200,g)}catch(m){if(f.isNotification(p))return process.env.NODE_ENV!=="test"&&console.error("Next.js MCP notification processing error:",m),new r.NextResponse(null,{status:202});process.env.NODE_ENV!=="test"&&console.error("Next.js MCP RPC handler error:",m);const C=m?.code??-32603,g=m?.data,x=m.message||"MCP request failed",h=f.buildJsonRpcError(p.id??null,C,x,g);if(w){const E=new TextEncoder,S=f.primeEventId(),O=new ReadableStream({start(b){b.enqueue(E.encode(`id: ${S}
3
+ `)),H.enqueue(p.encode(f.serializeSseEvent(S,R))),H.close()}}),O=new Headers({"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive",...v});if(s){const H=x(r,s);Object.entries(H).forEach(([b,P])=>O.set(b,P))}return new t.NextResponse(E,{status:200,headers:O})}return j(S,200,v)}catch(h){if(f.isNotification(y))return process.env.NODE_ENV!=="test"&&console.error("Next.js MCP notification processing error:",h),new t.NextResponse(null,{status:202});process.env.NODE_ENV!=="test"&&console.error("Next.js MCP RPC handler error:",h);const w=h?.code??-32603,v=h?.data,S=h.message||"MCP request failed",p=f.buildJsonRpcError(y.id??null,w,S,v);if(C){const R=new TextEncoder,E=f.primeEventId(),O=new ReadableStream({start(b){b.enqueue(R.encode(`id: ${E}
4
4
 
5
- `)),b.enqueue(E.encode(f.serializeSseEvent(h,S))),b.close()}}),H=new Headers({"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});if(s){const b=R(t,s);Object.entries(b).forEach(([P,I])=>H.set(P,I))}return new r.NextResponse(O,{status:200,headers:H})}return v(h,200)}}}function Q(n){const{extractSecurityContext:o,cors:s,agent:c}=n;if(!c)throw new Error("agent config is required for createAgentChatHandler");const d=j(n);return async function(t,e){try{if(t.method!=="POST")return r.NextResponse.json({error:"Method not allowed - use POST"},{status:405});const{handleAgentChat:l}=await Promise.resolve().then(()=>require("../handler-hwoGzGex.cjs")),y=await t.json(),{message:u,sessionId:p,history:w}=y;if(!u||typeof u!="string")return r.NextResponse.json({error:"message is required and must be a string"},{status:400});let N=(c.apiKey||"").trim();if(c.allowClientApiKey){const x=t.headers.get("x-agent-api-key");x&&(N=x.trim())}if(!N)return r.NextResponse.json({error:"No API key configured. Set agent.apiKey in server config or send X-Agent-Api-Key header."},{status:401});const v=await o(t,e),m=new TextEncoder,C=new ReadableStream({async start(x){try{const h=l({message:u,sessionId:p,history:w,semanticLayer:d,securityContext:v,agentConfig:c,apiKey:N});for await(const E of h){const S=`data: ${JSON.stringify(E)}
5
+ `)),b.enqueue(R.encode(f.serializeSseEvent(p,E))),b.close()}}),H=new Headers({"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});if(s){const b=x(r,s);Object.entries(b).forEach(([P,I])=>H.set(P,I))}return new t.NextResponse(O,{status:200,headers:H})}return j(p,200)}}}function Q(n){const{extractSecurityContext:o,cors:s,agent:c}=n;if(!c)throw new Error("agent config is required for createAgentChatHandler");const d=g(n);return async function(r,e){try{if(r.method!=="POST")return t.NextResponse.json({error:"Method not allowed - use POST"},{status:405});const{handleAgentChat:l}=await Promise.resolve().then(()=>require("../handler-DtdjM1Vx.cjs")),m=await r.json(),{message:u,sessionId:y,history:C}=m;if(!u||typeof u!="string")return t.NextResponse.json({error:"message is required and must be a string"},{status:400});let N=(c.apiKey||"").trim();if(c.allowClientApiKey){const p=r.headers.get("x-agent-api-key");p&&(N=p.trim())}if(!N)return t.NextResponse.json({error:"No API key configured. Set agent.apiKey in server config or send X-Agent-Api-Key header."},{status:401});const j=await o(r,e),h=c.buildSystemContext?.(j),w=new TextEncoder,v=new ReadableStream({async start(p){try{const R=l({message:u,sessionId:y,history:C,semanticLayer:d,securityContext:j,agentConfig:c,apiKey:N,systemContext:h});for await(const E of R){const O=`data: ${JSON.stringify(E)}
6
6
 
7
- `;x.enqueue(m.encode(S))}}catch(h){const E={type:"error",data:{message:h instanceof Error?h.message:"Stream failed"}};x.enqueue(m.encode(`data: ${JSON.stringify(E)}
7
+ `;p.enqueue(w.encode(O))}}catch(R){const E={type:"error",data:{message:R instanceof Error?R.message:"Stream failed"}};p.enqueue(w.encode(`data: ${JSON.stringify(E)}
8
8
 
9
- `))}finally{x.close()}}}),g=new Headers({"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});if(s){const x=R(t,s);Object.entries(x).forEach(([h,E])=>g.set(h,E))}return new Response(C,{status:200,headers:g})}catch(l){return process.env.NODE_ENV!=="test"&&console.error("Next.js agent chat handler error:",l),r.NextResponse.json({error:l instanceof Error?l.message:"Agent chat failed"},{status:500})}}}function K(n){const{mcp:o={enabled:!0}}=n,s={load:T(n),meta:M(n),sql:A(n),dryRun:L(n),batch:D(n),explain:V(n)};return o.enabled!==!1&&(s.mcpRpc=_(n)),n.agent&&(s.agentChat=Q(n)),s}exports.createAgentChatHandler=Q;exports.createBatchHandler=D;exports.createCubeHandlers=K;exports.createDiscoverHandler=k;exports.createDryRunHandler=L;exports.createExplainHandler=V;exports.createLoadHandler=T;exports.createMcpLoadHandler=$;exports.createMcpRpcHandler=_;exports.createMetaHandler=M;exports.createOptionsHandler=J;exports.createSqlHandler=A;exports.createSuggestHandler=q;exports.createValidateHandler=z;
9
+ `))}finally{p.close()}}}),S=new Headers({"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});if(s){const p=x(r,s);Object.entries(p).forEach(([R,E])=>S.set(R,E))}return new Response(v,{status:200,headers:S})}catch(l){return process.env.NODE_ENV!=="test"&&console.error("Next.js agent chat handler error:",l),t.NextResponse.json({error:l instanceof Error?l.message:"Agent chat failed"},{status:500})}}}function K(n){const{mcp:o={enabled:!0}}=n,s={load:T(n),meta:M(n),sql:A(n),dryRun:L(n),batch:D(n),explain:V(n)};return o.enabled!==!1&&(s.mcpRpc=_(n)),n.agent&&(s.agentChat=Q(n)),s}exports.createAgentChatHandler=Q;exports.createBatchHandler=D;exports.createCubeHandlers=K;exports.createDiscoverHandler=k;exports.createDryRunHandler=L;exports.createExplainHandler=V;exports.createLoadHandler=T;exports.createMcpLoadHandler=$;exports.createMcpRpcHandler=_;exports.createMetaHandler=M;exports.createOptionsHandler=J;exports.createSqlHandler=A;exports.createSuggestHandler=q;exports.createValidateHandler=z;