@puckeditor/cloud-client 0.7.0-canary.75c0f12c → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -20431,7 +20431,6 @@ var processUserTool = async ({
20431
20431
  const responses = [];
20432
20432
  for (let i = 0; i < requestTools.length; i++) {
20433
20433
  const { name: name20, input } = requestTools[i];
20434
- console.info(`[PUCK] Calling user tool "${name20}"...`);
20435
20434
  const tool2 = tools?.[name20];
20436
20435
  if (!tool2) {
20437
20436
  throw new Error(`An unknown tool was called: ${name20}`);
@@ -20440,7 +20439,6 @@ var processUserTool = async ({
20440
20439
  throw new Error(`Input was not present in tool call: ${toolCallId}`);
20441
20440
  }
20442
20441
  const output = await tool2.execute(input);
20443
- console.info(`[PUCK] Called user tool "${name20}" successfully`);
20444
20442
  responses.push({ name: name20, input, output });
20445
20443
  }
20446
20444
  const res = await fetch(`${host}/tool`, {
@@ -20492,14 +20490,13 @@ var cloudApi = async (path, body, options = {}, onChunk) => {
20492
20490
  "No Puck API key specified. Set the PUCK_API_KEY environment variable, or provide one to the function"
20493
20491
  );
20494
20492
  }
20495
- const { context, collectionId, tools = {} } = ai;
20493
+ const { context, tools = {} } = ai;
20496
20494
  const res = await fetch(`${host}/${path}`, {
20497
20495
  headers: { "x-api-key": apiKey },
20498
20496
  method: "post",
20499
20497
  body: JSON.stringify({
20500
20498
  ...body,
20501
20499
  context,
20502
- collectionId,
20503
20500
  tools: prepareUserTools(tools)
20504
20501
  })
20505
20502
  });
@@ -20549,14 +20546,13 @@ async function generate({
20549
20546
  config: config2,
20550
20547
  pageData,
20551
20548
  context,
20552
- collectionId,
20553
20549
  tools,
20554
20550
  apiKey,
20555
20551
  host,
20556
20552
  onFinish
20557
20553
  }) {
20558
20554
  let result = null;
20559
- const options = { ai: { context, collectionId, tools }, apiKey, host };
20555
+ const options = { ai: { context, tools }, apiKey, host };
20560
20556
  await cloudApi("generate", { prompt, config: config2, pageData }, options, (chunk) => {
20561
20557
  if (chunk.type === "data-page") {
20562
20558
  result = chunk.data;
@@ -20575,143 +20571,194 @@ init_react_import();
20575
20571
  // src/routes.ts
20576
20572
  init_react_import();
20577
20573
 
20578
- // src/api/plan.ts
20574
+ // src/api/attachments.ts
20579
20575
  init_react_import();
20580
-
20581
- // ../plugin-pages/api/index.ts
20582
- init_react_import();
20583
- var GET = async ({
20584
- path,
20585
- versionId,
20586
- siteId,
20587
- latestVersion
20588
- }, options) => {
20589
- const {
20590
- host = "https://cloud.puckeditor.com/api",
20591
- ott,
20592
- apiKey = getApiKey()
20593
- } = options;
20594
- if (!ott && !apiKey) {
20576
+ var DEFAULT_HOST = "https://cloud.puckeditor.com/api";
20577
+ var proxyAttachment = async (path, method, body, options) => {
20578
+ const apiKey = options.apiKey ?? getApiKey();
20579
+ const host = (options.host ?? DEFAULT_HOST).replace(/\/+$/, "");
20580
+ if (!apiKey) {
20595
20581
  throw new Error(
20596
20582
  "No Puck API key specified. Set the PUCK_API_KEY environment variable, or provide one to the function"
20597
20583
  );
20598
20584
  }
20599
- const res = await fetch(
20600
- `${host}/page?path=${path}${versionId ? `&versionId=${versionId}` : ""}${latestVersion ? `&latestVersion=true` : ""}`,
20601
- {
20602
- headers: {
20603
- ...ott ? { "x-ott": ott } : {},
20604
- ...apiKey && !ott ? { "x-api-key": apiKey } : {},
20605
- ...siteId ? { "site-id": siteId } : {}
20606
- }
20607
- }
20608
- );
20609
- if (!res.body) {
20610
- throw new Error(`Puck ${res.status} (${res.statusText})`);
20611
- } else if (!res.ok) {
20612
- const body = await res.json();
20613
- throw new Error(
20614
- `Puck ${res.status} (${res.statusText}): ${body.error ?? "Unknown reason"}`
20585
+ const response = await fetch(`${host}${path}`, {
20586
+ method,
20587
+ redirect: "manual",
20588
+ headers: {
20589
+ "x-api-key": apiKey,
20590
+ ...body ? { "content-type": "application/json" } : {}
20591
+ },
20592
+ ...body ? { body: JSON.stringify(body) } : {}
20593
+ });
20594
+ const contentType = response.headers.get("content-type");
20595
+ const location = response.headers.get("location");
20596
+ const headers = new Headers();
20597
+ if (contentType) {
20598
+ headers.set("content-type", contentType);
20599
+ }
20600
+ if (location) {
20601
+ headers.set("location", location);
20602
+ }
20603
+ const responseBody = response.status === 204 || response.status === 304 ? null : await response.arrayBuffer();
20604
+ return new Response(responseBody, {
20605
+ headers,
20606
+ status: response.status,
20607
+ statusText: response.statusText
20608
+ });
20609
+ };
20610
+ var internalError = (error45) => Response.json(
20611
+ {
20612
+ error: error45 instanceof Error ? error45.message : "An unexpected error occurred"
20613
+ },
20614
+ { status: 500 }
20615
+ );
20616
+ var createAttachments = async (context, options = {}) => {
20617
+ try {
20618
+ return await proxyAttachment(
20619
+ "/chat/attachments",
20620
+ "POST",
20621
+ context.body,
20622
+ options
20615
20623
  );
20624
+ } catch (error45) {
20625
+ return internalError(error45);
20616
20626
  }
20617
- return res;
20618
20627
  };
20619
-
20620
- // src/api/plan.ts
20621
- function plan({ plan: plan2, config: config2 }, options = {}) {
20622
- console.info(`[PUCK] Executing plan with ${plan2.pages.length} pages...`);
20623
- if (!process.env.PUCK_SITE_ID) {
20624
- throw new Error(`Please configure the PUCK_SITE_ID environment variable`);
20628
+ var getAttachment = async (context, options = {}) => {
20629
+ try {
20630
+ return await proxyAttachment(
20631
+ `/chat/attachments/${context.params.attachmentId}`,
20632
+ "GET",
20633
+ null,
20634
+ options
20635
+ );
20636
+ } catch (error45) {
20637
+ return internalError(error45);
20625
20638
  }
20626
- const stream = createUIMessageStream({
20627
- execute: async ({ writer }) => {
20628
- writer.write({ type: "data-plan-progress", data: {} });
20629
- for (let i = 0; i < plan2.pages.length; i++) {
20630
- const page = plan2.pages[i];
20631
- console.info(`[PUCK] Executing prompt "${page.pagePrompt}"...`);
20632
- writer.write({
20633
- type: "data-plan-progress",
20634
- data: { path: page.path, status: "processing" }
20635
- });
20636
- const existingPageRes = await GET(
20637
- {
20638
- path: page.path,
20639
- latestVersion: true,
20640
- siteId: process.env.PUCK_SITE_ID
20641
- },
20642
- {
20643
- host: "http://localhost:3000/api",
20644
- apiKey: process.env.PUCK_API_KEY
20645
- }
20646
- );
20647
- const existingPageJson = await existingPageRes.json();
20648
- const existingPageData = existingPageJson.page?.versions?.at(0)?.data ?? void 0;
20649
- const data = await generate({
20650
- prompt: page.pagePrompt,
20651
- config: config2,
20652
- context: options.ai?.context,
20653
- pageData: existingPageData,
20654
- tools: options.ai?.tools,
20655
- host: options.host,
20656
- apiKey: options.apiKey
20657
- });
20658
- console.log("data", data);
20659
- if (!data) {
20660
- throw new Error(`Could not generate ${page.path}`);
20661
- }
20662
- writer.write({
20663
- type: "data-plan-progress",
20664
- data: { path: page.path, data, status: "complete" }
20665
- });
20666
- console.info(`[PUCK] Received page data`);
20667
- console.info(`[PUCK] Writing to pages db...`);
20668
- console.log(
20669
- { body: { data, path: page.path, status: "draft" } },
20670
- {
20671
- host: "http://localhost:3000/api",
20672
- siteId: process.env.PUCK_SITE_ID,
20673
- apiKey: process.env.PUCK_API_KEY
20674
- }
20675
- );
20676
- console.info(`[PUCK] Write complete`);
20677
- }
20678
- }
20679
- });
20680
- return createUIMessageStreamResponse({ stream });
20681
- }
20639
+ };
20640
+ var deleteAttachment = async (context, options = {}) => {
20641
+ try {
20642
+ return await proxyAttachment(
20643
+ `/chat/attachments/${context.params.attachmentId}`,
20644
+ "DELETE",
20645
+ null,
20646
+ options
20647
+ );
20648
+ } catch (error45) {
20649
+ return internalError(error45);
20650
+ }
20651
+ };
20682
20652
 
20683
20653
  // src/routes.ts
20684
- var routeRegistry = {
20685
- "/api/puck/chat": {
20686
- POST: chat
20687
- },
20688
- "/api/puck/plan": {
20689
- POST: plan
20654
+ var utf8Decoder = new TextDecoder("utf-8", { fatal: false });
20655
+ var safeDecode3 = (pathname) => pathname.replace(/(?:%[0-9a-fA-F]{2})+/g, (run) => {
20656
+ const bytes = run.slice(1).split("%").map((pair) => Number.parseInt(pair, 16));
20657
+ return utf8Decoder.decode(Uint8Array.from(bytes));
20658
+ });
20659
+ var normalizePathname = (pathname) => {
20660
+ const normalized = safeDecode3(pathname).replace(/\/+$/, "");
20661
+ return normalized.length > 0 ? normalized : "/";
20662
+ };
20663
+ var matchRoute = (pattern, pathname) => {
20664
+ const normalizedPattern = normalizePathname(pattern);
20665
+ const normalizedPathname = normalizePathname(pathname);
20666
+ const patternSegments = normalizedPattern.split("/").filter(Boolean);
20667
+ const pathSegments = normalizedPathname.split("/").filter(Boolean);
20668
+ if (patternSegments.length !== pathSegments.length) {
20669
+ return null;
20670
+ }
20671
+ const params = {};
20672
+ for (let i = 0; i < patternSegments.length; i += 1) {
20673
+ const patternSegment = patternSegments[i];
20674
+ const pathSegment = pathSegments[i];
20675
+ if (patternSegment.startsWith(":")) {
20676
+ params[patternSegment.slice(1)] = pathSegment;
20677
+ continue;
20678
+ }
20679
+ if (patternSegment !== pathSegment) {
20680
+ return null;
20681
+ }
20690
20682
  }
20683
+ return params;
20691
20684
  };
20692
- var findRoute = (pathname, method) => {
20693
- return routeRegistry[pathname][method];
20685
+ var routeRegistry = [
20686
+ {
20687
+ pattern: "/api/puck/chat/attachments/:attachmentId",
20688
+ methods: {
20689
+ DELETE: deleteAttachment,
20690
+ GET: getAttachment
20691
+ }
20692
+ },
20693
+ {
20694
+ pattern: "/api/puck/chat/attachments",
20695
+ methods: {
20696
+ POST: createAttachments
20697
+ }
20698
+ },
20699
+ {
20700
+ pattern: "/api/puck/chat",
20701
+ methods: {
20702
+ POST: ({ body }, options) => chat(body, options)
20703
+ }
20704
+ }
20705
+ ];
20706
+ var findRouteInRegistry = (routeRegistry2, pathname, method) => {
20707
+ for (const route of routeRegistry2) {
20708
+ const params = matchRoute(route.pattern, pathname);
20709
+ if (!params) {
20710
+ continue;
20711
+ }
20712
+ const handler = route.methods[method];
20713
+ if (!handler) {
20714
+ return null;
20715
+ }
20716
+ return {
20717
+ handler,
20718
+ params
20719
+ };
20720
+ }
20721
+ return null;
20694
20722
  };
20723
+ var findRoute = (pathname, method) => findRouteInRegistry(routeRegistry, pathname, method);
20695
20724
 
20696
20725
  // src/api/puck-handler.ts
20697
- async function puckHandler(request, options) {
20726
+ var bodyMethods = /* @__PURE__ */ new Set(["PATCH", "POST", "PUT"]);
20727
+ var isRouteMethod = (method) => method === "DELETE" || method === "GET" || method === "POST";
20728
+ var handlePuckRequest = async (request, options, findRoute2) => {
20698
20729
  const cloned = request.clone();
20699
20730
  const url2 = new URL(cloned.url);
20700
- const searchParams = Object.fromEntries(url2.searchParams);
20731
+ const query = Object.fromEntries(url2.searchParams);
20701
20732
  const pathname = url2.pathname;
20702
20733
  const method = cloned.method;
20703
- const route = findRoute(pathname, method);
20734
+ if (!isRouteMethod(method)) {
20735
+ return Response.json({ error: "Not found" }, { status: 404 });
20736
+ }
20737
+ const route = findRoute2(pathname, method);
20704
20738
  if (!route) {
20705
20739
  return Response.json({ error: "Not found" }, { status: 404 });
20706
20740
  }
20707
20741
  let body = null;
20708
- if (method === "POST" || method === "PUT" || method === "PATCH") {
20742
+ if (bodyMethods.has(method)) {
20709
20743
  try {
20710
20744
  body = await cloned.json();
20711
- } catch (error45) {
20745
+ } catch {
20712
20746
  }
20713
20747
  }
20714
- return route(body ?? searchParams, options);
20748
+ return route.handler(
20749
+ {
20750
+ body,
20751
+ headers: cloned.headers,
20752
+ params: route.params,
20753
+ pathname,
20754
+ query,
20755
+ request: cloned
20756
+ },
20757
+ options
20758
+ );
20759
+ };
20760
+ async function puckHandler(request, options = {}) {
20761
+ return handlePuckRequest(request, options, findRoute);
20715
20762
  }
20716
20763
 
20717
20764
  // src/index.ts