"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/ai-sdk/index.ts
var ai_sdk_exports = {};
__export(ai_sdk_exports, {
  StripeAgentToolkit: () => toolkit_default
});
module.exports = __toCommonJS(ai_sdk_exports);

// src/shared/api.ts
var import_stripe = __toESM(require("stripe"));

// src/shared/functions.ts
var createCustomer = async (stripe, params) => {
  try {
    const customer = await stripe.customers.create(params);
    return { id: customer.id };
  } catch (error) {
    return "Failed to create customer";
  }
};
var listCustomers = async (stripe, params) => {
  try {
    const customers = await stripe.customers.list(params);
    return customers.data.map((customer) => ({ id: customer.id }));
  } catch (error) {
    return "Failed to list customers";
  }
};
var createProduct = async (stripe, params) => {
  try {
    const product = await stripe.products.create(params);
    return product;
  } catch (error) {
    return "Failed to create product";
  }
};
var listProducts = async (stripe, params) => {
  try {
    const products = await stripe.products.list(params);
    return products.data;
  } catch (error) {
    return "Failed to list products";
  }
};
var createPrice = async (stripe, params) => {
  try {
    const price = await stripe.prices.create(params);
    return price;
  } catch (error) {
    return "Failed to create price";
  }
};
var listPrices = async (stripe, params) => {
  try {
    const prices = await stripe.prices.list(params);
    return prices.data;
  } catch (error) {
    return "Failed to list prices";
  }
};
var createPaymentLink = async (stripe, params) => {
  try {
    const paymentLink = await stripe.paymentLinks.create({
      line_items: [params]
    });
    return { id: paymentLink.id, url: paymentLink.url };
  } catch (error) {
    return "Failed to create payment link";
  }
};
var createInvoice = async (stripe, params) => {
  try {
    const invoice = await stripe.invoices.create(params);
    return {
      id: invoice.id,
      url: invoice.hosted_invoice_url,
      customer: invoice.customer,
      status: invoice.status
    };
  } catch (error) {
    return "Failed to create invoice";
  }
};
var createInvoiceItem = async (stripe, params) => {
  try {
    const invoiceItem = await stripe.invoiceItems.create(params);
    return {
      id: invoiceItem.id,
      invoice: invoiceItem.invoice
    };
  } catch (error) {
    return "Failed to create invoice item";
  }
};
var finalizeInvoice = async (stripe, params) => {
  try {
    const invoice = await stripe.invoices.finalizeInvoice(params.invoice);
    return {
      id: invoice.id,
      url: invoice.hosted_invoice_url,
      customer: invoice.customer,
      status: invoice.status
    };
  } catch (error) {
    return "Failed to finalize invoice";
  }
};
var retrieveBalance = async (stripe, params) => {
  try {
    const balance = await stripe.balance.retrieve(params);
    return balance;
  } catch (error) {
    return "Failed to retrieve balance";
  }
};

// src/shared/api.ts
var StripeAPI = class {
  stripe;
  constructor(secretKey) {
    const stripeClient = new import_stripe.default(secretKey, {
      appInfo: {
        name: "stripe-agent-toolkit-typescript",
        version: "0.1.21",
        url: "https://github.com/stripe/agent-toolkit"
      }
    });
    this.stripe = stripeClient;
  }
  async createMeterEvent({
    event,
    customer,
    value
  }) {
    await this.stripe.billing.meterEvents.create({
      event_name: event,
      payload: {
        stripe_customer_id: customer,
        value
      }
    });
  }
  async run(method, arg) {
    if (method === "create_customer") {
      const output = JSON.stringify(await createCustomer(this.stripe, arg));
      return output;
    } else if (method === "list_customers") {
      const output = JSON.stringify(await listCustomers(this.stripe, arg));
      return output;
    } else if (method === "create_product") {
      const output = JSON.stringify(await createProduct(this.stripe, arg));
      return output;
    } else if (method === "list_products") {
      const output = JSON.stringify(await listProducts(this.stripe, arg));
      return output;
    } else if (method === "create_price") {
      const output = JSON.stringify(await createPrice(this.stripe, arg));
      return output;
    } else if (method === "list_prices") {
      const output = JSON.stringify(await listPrices(this.stripe, arg));
      return output;
    } else if (method === "create_payment_link") {
      const output = JSON.stringify(await createPaymentLink(this.stripe, arg));
      return output;
    } else if (method === "create_invoice") {
      const output = JSON.stringify(await createInvoice(this.stripe, arg));
      return output;
    } else if (method === "create_invoice_item") {
      const output = JSON.stringify(await createInvoiceItem(this.stripe, arg));
      return output;
    } else if (method === "finalize_invoice") {
      const output = JSON.stringify(await finalizeInvoice(this.stripe, arg));
      return output;
    } else if (method === "retrieve_balance") {
      const output = JSON.stringify(await retrieveBalance(this.stripe, arg));
      return output;
    } else {
      throw new Error("Invalid method " + method);
    }
  }
};
var api_default = StripeAPI;

// src/shared/prompts.ts
var createCustomerPrompt = `
This tool will create a customer in Stripe.

It takes two arguments:
- name (str): The name of the customer.
- email (str, optional): The email of the customer.
`;
var listCustomersPrompt = `
This tool will fetch a list of Customers from Stripe.

It takes no input.
`;
var createProductPrompt = `
This tool will create a product in Stripe.

It takes two arguments:
- name (str): The name of the product.
- description (str, optional): The description of the product.
`;
var listProductsPrompt = `
This tool will fetch a list of Products from Stripe.

It takes one optional argument:
- limit (int, optional): The number of products to return.
`;
var createPricePrompt = `
This tool will create a price in Stripe. If a product has not already been specified, a product should be created first.

It takes three arguments:
- product (str): The ID of the product to create the price for.
- unit_amount (int): The unit amount of the price in cents.
- currency (str): The currency of the price.
`;
var listPricesPrompt = `
This tool will fetch a list of Prices from Stripe.

It takes two arguments.
- product (str, optional): The ID of the product to list prices for.
- limit (int, optional): The number of prices to return.
`;
var createPaymentLinkPrompt = `
This tool will create a payment link in Stripe.

It takes two arguments:
- price (str): The ID of the price to create the payment link for.
- quantity (int): The quantity of the product to include in the payment link.
`;
var createInvoicePrompt = `
This tool will create an invoice in Stripe.

It takes one argument:
- customer (str): The ID of the customer to create the invoice for.
`;
var createInvoiceItemPrompt = `
This tool will create an invoice item in Stripe.

It takes two arguments:
- customer (str): The ID of the customer to create the invoice item for.
- price (str): The ID of the price to create the invoice item for.
`;
var finalizeInvoicePrompt = `
This tool will finalize an invoice in Stripe.

It takes one argument:
- invoice (str): The ID of the invoice to finalize.
`;
var retrieveBalancePrompt = `
This tool will retrieve the balance from Stripe. It takes no input.
`;

// src/shared/parameters.ts
var import_zod = require("zod");
var createCustomerParameters = import_zod.z.object({
  name: import_zod.z.string().describe("The name of the customer"),
  email: import_zod.z.string().email().optional().describe("The email of the customer")
});
var listCustomersParameters = import_zod.z.object({
  limit: import_zod.z.number().int().min(1).max(100).optional().describe(
    "A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10."
  ),
  email: import_zod.z.string().optional().describe(
    "A case-sensitive filter on the list based on the customer's email field. The value must be a string."
  )
});
var createProductParameters = import_zod.z.object({
  name: import_zod.z.string().describe("The name of the product."),
  description: import_zod.z.string().optional().describe("The description of the product.")
});
var listProductsParameters = import_zod.z.object({
  limit: import_zod.z.number().int().min(1).max(100).optional().describe(
    "A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10."
  )
});
var createPriceParameters = import_zod.z.object({
  product: import_zod.z.string().describe("The ID of the product to create the price for."),
  unit_amount: import_zod.z.number().int().describe("The unit amount of the price in cents."),
  currency: import_zod.z.string().describe("The currency of the price.")
});
var listPricesParameters = import_zod.z.object({
  product: import_zod.z.string().optional().describe("The ID of the product to list prices for."),
  limit: import_zod.z.number().int().min(1).max(100).optional().describe(
    "A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10."
  )
});
var createPaymentLinkParameters = import_zod.z.object({
  price: import_zod.z.string().describe("The ID of the price to create the payment link for."),
  quantity: import_zod.z.number().int().describe("The quantity of the product to include.")
});
var createInvoiceParameters = import_zod.z.object({
  customer: import_zod.z.string().describe("The ID of the customer to create the invoice for."),
  days_until_due: import_zod.z.number().int().optional().describe("The number of days until the invoice is due.")
});
var createInvoiceItemParameters = import_zod.z.object({
  customer: import_zod.z.string().describe("The ID of the customer to create the invoice item for."),
  price: import_zod.z.string().describe("The ID of the price for the item."),
  invoice: import_zod.z.string().describe("The ID of the invoice to create the item for.")
});
var finalizeInvoiceParameters = import_zod.z.object({
  invoice: import_zod.z.string().describe("The ID of the invoice to finalize.")
});
var retrieveBalanceParameters = import_zod.z.object({});

// src/shared/tools.ts
var tools = [
  {
    method: "create_customer",
    name: "Create Customer",
    description: createCustomerPrompt,
    parameters: createCustomerParameters,
    actions: {
      customers: {
        create: true
      }
    }
  },
  {
    method: "list_customers",
    name: "List Customers",
    description: listCustomersPrompt,
    parameters: listCustomersParameters,
    actions: {
      customers: {
        read: true
      }
    }
  },
  {
    method: "create_product",
    name: "Create Product",
    description: createProductPrompt,
    parameters: createProductParameters,
    actions: {
      products: {
        create: true
      }
    }
  },
  {
    method: "list_products",
    name: "List Products",
    description: listProductsPrompt,
    parameters: listProductsParameters,
    actions: {
      products: {
        read: true
      }
    }
  },
  {
    method: "create_price",
    name: "Create Price",
    description: createPricePrompt,
    parameters: createPriceParameters,
    actions: {
      prices: {
        create: true
      }
    }
  },
  {
    method: "list_prices",
    name: "List Prices",
    description: listPricesPrompt,
    parameters: listPricesParameters,
    actions: {
      prices: {
        read: true
      }
    }
  },
  {
    method: "create_payment_link",
    name: "Create Payment Link",
    description: createPaymentLinkPrompt,
    parameters: createPaymentLinkParameters,
    actions: {
      paymentLinks: {
        create: true
      }
    }
  },
  {
    method: "create_invoice",
    name: "Create Invoice",
    description: createInvoicePrompt,
    parameters: createInvoiceParameters,
    actions: {
      invoices: {
        create: true
      }
    }
  },
  {
    method: "create_invoice_item",
    name: "Create Invoice Item",
    description: createInvoiceItemPrompt,
    parameters: createInvoiceItemParameters,
    actions: {
      invoiceItems: {
        create: true
      }
    }
  },
  {
    method: "finalize_invoice",
    name: "Finalize Invoice",
    description: finalizeInvoicePrompt,
    parameters: finalizeInvoiceParameters,
    actions: {
      invoices: {
        update: true
      }
    }
  },
  {
    method: "retrieve_balance",
    name: "Retrieve Balance",
    description: retrieveBalancePrompt,
    parameters: retrieveBalanceParameters,
    actions: {
      balance: {
        read: true
      }
    }
  }
];
var tools_default = tools;

// src/shared/configuration.ts
var isToolAllowed = (tool2, configuration) => {
  return Object.keys(tool2.actions).every((resource) => {
    const permissions = tool2.actions[resource];
    return Object.keys(permissions).every((permission) => {
      return configuration.actions[resource]?.[permission] === true;
    });
  });
};

// src/ai-sdk/tool.ts
var import_ai = require("ai");
function StripeTool(stripeAPI, method, description, schema) {
  return (0, import_ai.tool)({
    description,
    parameters: schema,
    execute: (arg) => {
      return stripeAPI.run(method, arg);
    }
  });
}

// src/ai-sdk/toolkit.ts
var StripeAgentToolkit = class {
  _stripe;
  tools;
  constructor({
    secretKey,
    configuration
  }) {
    this._stripe = new api_default(secretKey);
    this.tools = {};
    const filteredTools = tools_default.filter(
      (tool2) => isToolAllowed(tool2, configuration)
    );
    filteredTools.forEach((tool2) => {
      this.tools[tool2.method] = StripeTool(
        this._stripe,
        tool2.method,
        tool2.description,
        tool2.parameters
      );
    });
  }
  middleware(config) {
    const bill = async ({
      promptTokens,
      completionTokens
    }) => {
      if (config.billing) {
        if (config.billing.meters.input) {
          await this._stripe.createMeterEvent({
            event: config.billing.meters.input,
            customer: config.billing.customer,
            value: promptTokens.toString()
          });
        }
        if (config.billing.meters.output) {
          await this._stripe.createMeterEvent({
            event: config.billing.meters.output,
            customer: config.billing.customer,
            value: completionTokens.toString()
          });
        }
      }
    };
    return {
      wrapGenerate: async ({ doGenerate }) => {
        const result = await doGenerate();
        if (config.billing) {
          await bill(result.usage);
        }
        return result;
      },
      wrapStream: async ({ doStream }) => {
        const { stream, ...rest } = await doStream();
        const transformStream = new TransformStream({
          async transform(chunk, controller) {
            if (chunk.type === "finish") {
              if (config.billing) {
                await bill(chunk.usage);
              }
            }
            controller.enqueue(chunk);
          }
        });
        return {
          stream: stream.pipeThrough(transformStream),
          ...rest
        };
      }
    };
  }
  getTools() {
    return this.tools;
  }
};
var toolkit_default = StripeAgentToolkit;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  StripeAgentToolkit
});
//# sourceMappingURL=index.js.map