import { t as StandardSchemaV1 } from "../../standard-DIedMFAS.js"; import { n as UpstreamError } from "../../upstream-RyW4cAyx.js"; import { p as centsToMajor, t as Money } from "../../index-DB2HlD4k.js"; //#region src/core/commerce/square/client.d.ts type SquareEnvironment = "sandbox" | "production"; interface SquareConfig { /** Square access token (server-only secret). */ accessToken: string; /** Defaults to "sandbox". Selects the API host. */ environment?: SquareEnvironment; /** Pinned Square-Version. Bump deliberately (response shapes are stable per * version). Defaults to SQUARE_VERSION. */ version?: string; /** Transient-failure retry. OFF by default, so existing callers are byte-for-byte * unchanged; turn it on for unattended paths (cron sync, queue consumers) where * a 429 or a 5xx should cost a second rather than fail the job. Never retries a * 4xx other than 429—those are our bug, not Square's weather. */ retry?: SquareRetryConfig; /** Abandon a request after this long, per attempt. Default 10 s. Raise it for * a slow bulk call (a large catalog upsert, an image upload). */ timeoutMs?: number; } interface SquareRetryConfig { /** Attempts AFTER the first try. 0 disables. Defaults to 2. */ attempts?: number; /** First backoff step in ms; doubles each attempt. Defaults to 250. */ baseDelayMs?: number; /** Ceiling for one backoff step. Defaults to 4000. */ maxDelayMs?: number; } declare const SQUARE_VERSION = "2026-01-22"; /** * Which Square environment an application id belongs to, from its format—`sandbox-sq0idb-…` * or `sq0idp-…`—or `null` when it is neither (a * placeholder, a typo, an access token pasted into the wrong variable). * * The Web Payments SDK rejects a malformed id with "…not in the correct * format" and an id from the other environment with an opaque error at * checkout. Compare the result with the environment the server uses and * show a clear "payments not available" state instead. */ declare function squareApplicationIdEnvironment(applicationId: string | null | undefined): SquareEnvironment | null; interface SquareErrorBody { errors?: { code?: string; detail?: string; category?: string; }[]; } /** * A non-2xx answer from Square—an {@link UpstreamError}, so `message` is safe * to show a user and Square's own `detail` stays in the logs. `status` and * `code` (Square's first error code, for example, `"NOT_FOUND"`) are what let a caller * tell "not found" (a 404 is often an answer—no loyalty program, no such * card) from a failure, and map a decline to its own copy. */ declare class SquareApiError extends UpstreamError { /** Square's error category, for example, `"PAYMENT_METHOD_ERROR"`—a decline, the * buyer's to fix—as opposed to `"INVALID_REQUEST_ERROR"`, which is ours. */ readonly category: string | null; constructor(operation: string, status: number, body: SquareErrorBody, raw?: string); } //#endregion //#region src/core/commerce/square/money.d.ts /** Square money is an integer amount in the currency's minor unit (cents): * the shared {@link Money} shape. */ type SquareMoney = Money; //#endregion //#region src/core/commerce/square/locations.d.ts interface SquareLocation { id: string; name: string; /** ACTIVE | INACTIVE. Inactive locations still resolve but should not be sold at. */ status: string; /** ISO 4217, for example, "USD". A location's currency is fixed at creation. */ currency: string; timezone: string | null; /** Formatted single-line address, or null when the location has none. */ address: string | null; businessName: string | null; } /** Every location on the account. GET /v2/locations—unpaginated by design * (Square caps an account at 300 locations and returns them all). */ declare function listLocations(config: SquareConfig): Promise; /** One location by id, or null when it does not exist. GET /v2/locations/{id}. */ declare function retrieveLocation(config: SquareConfig, locationId: string): Promise; /** A location's editable fields. Structured, not the formatted single line * {@link SquareLocation} reads back; Square needs the parts. */ interface SquareLocationInput { name: string; businessName?: string; timezone?: string; address?: { line1?: string; line2?: string; /** City. */ locality?: string; /** State / province. */ region?: string; postalCode?: string; /** ISO 3166-1 alpha-2, for example, "US". */ country?: string; }; } /** * Create a location. POST /v2/locations. The onboarding call—a new merchant * joining a multi-location deploy needs one before anything can be sold there. * * **Currency is not settable and is not per-request.** Square derives it from * the seller account, so every location under one account shares it: an account * cannot mix USD and CAD. If a merchant needs a different currency they need a * different Square account, which is an onboarding constraint rather than a code * one—worth knowing before designing around it. * * The cap is 300 locations per account, including deactivated ones. */ declare function createLocation(config: SquareConfig, input: SquareLocationInput): Promise; /** * Update a location. PUT /v2/locations/{id}. * * Sparse: only the fields you pass are sent, so this never clears a field by * omission—which matters because `address` is a nested object Square replaces * wholesale. Passing a partial address replaces the whole address with that * partial, so read first if you mean to change one line of it. * * A location cannot be deleted, only deactivated—set `status` through the * Square dashboard; the API does not expose it here. */ declare function updateLocation(config: SquareConfig, locationId: string, input: Partial): Promise; //#endregion //#region src/core/commerce/square/orders.d.ts /** * An order line item—either a catalog variation reference (Square applies the * catalog price + taxes) OR an ad-hoc line (explicit name + price), for charges * with no catalog object behind them (for example, a manufacturing deposit). */ type SquareOrderLineItem = { catalogObjectId: string; quantity: number; /** * Selected modifiers (catalog object ids—the modifier, not its list). * Square prices these into the line from the catalog, so they are * server-authoritative: pass ids through, never a client-quoted amount. */ modifierIds?: string[]; } | { name: string; priceCents: number; quantity: number; currency?: string; }; /** * An order-level charge Square adds on top of the line items—shipping is the * usual one. Applied in the `SUBTOTAL_PHASE` (before taxes, so it can itself be * taxed) or the `TOTAL_PHASE` (after). Defaults to subtotal, untaxed, which is * a flat shipping fee. */ interface SquareServiceCharge { name: string; amountMoney: SquareMoney; calculationPhase?: "SUBTOTAL_PHASE" | "TOTAL_PHASE"; taxable?: boolean; } /** Who receives a fulfillment. Square requires a display name. */ interface SquareFulfillmentRecipient { displayName: string; phone?: string; email?: string; } /** A shipping address in the shape Square's `address` object wants. */ interface SquareAddress { line1: string; line2?: string; /** City. */ locality: string; /** State / province. */ administrativeDistrictLevel1: string; postalCode: string; /** ISO 3166-1 alpha-2, for example, "US". */ country: string; } /** * How the order reaches the customer. Created in the `PROPOSED` state; the * seller advances it from POS or the Dashboard. * * A pickup is either `asap`—Square computes the ready time from the prep * duration, the order-ahead café case—or `scheduled` at a specific instant, * the "collect your beans Tuesday" case. Which of those a shop offers, and how * `pickupAt` is chosen, is policy that belongs to the caller. */ type SquareFulfillment = { type: "pickup"; recipient: SquareFulfillmentRecipient; schedule: { type: "asap"; /** Minutes until the order is ready: the shop's prep time, a whole * number ≥ 1. Required: how long a kitchen takes is the shop's fact, * and a guessed default would promise customers the wrong time. */ prepMinutes: number; } | { type: "scheduled"; pickupAt: string; }; /** Customer note to the kitchen. Square caps it at 500 characters. */ note?: string; } | { type: "shipment"; recipient: SquareFulfillmentRecipient & { address: SquareAddress; }; /** Delivery note to the packer. Square caps it at 500 characters. */ note?: string; }; /** * Order-level pricing behaviour, sent as `order.pricing_options`. * * Square applies **nothing** by default to an API-created order. Dashboard tax * settings reach POS and Square Online on their own, but not `CreateOrder`—so * a storefront that omits this charges pre-tax, silently, and the merchant * finds out at reconciliation. There is no error to notice. * * Two documented foot-guns: * * - It must be nested INSIDE `order`. At the request root Square ignores it * without complaint—the call succeeds and the total is simply wrong. * That is why this is a field on the input rather than something a caller * assembles into the body themselves. * - Never combine `auto_apply_taxes` with an explicit `order.taxes[]`; * Square documents that as double-taxing. This client never sends * `taxes[]`, so that combination is unreachable from here by construction. */ interface SquarePricingOptions { /** * Apply the taxes configured on each catalog item (its `tax_ids`). * * Whether Square filters those `tax_ids` by the order's `location_id` is * strongly implied by Square staff but never stated in the docs. A seller * with different rates per location should confirm it against their own * catalog—two locations, two rates, one shared item—before trusting it. * If both rates apply, that case needs an explicit location→tax-object map * rather than this flag (#392). */ autoApplyTaxes?: boolean; /** Apply the automatic (rule-based) discounts configured in the Dashboard. */ autoApplyDiscounts?: boolean; } interface SquareOrder { id: string; locationId: string; state: string; totalMoney: SquareMoney; totalTaxMoney: SquareMoney; /** Automatic + explicit discounts, as Square applied them. */ totalDiscountMoney: SquareMoney; /** The sum of {@link SquareServiceCharge}s (for example, shipping). */ totalServiceChargeMoney: SquareMoney; referenceId: string | null; customerId: string | null; createdAt: string | null; /** When money settled—the accounting axis, and null until an order closes. */ closedAt: string | null; updatedAt: string | null; lineItems: { name: string; quantity: string; catalogObjectId: string | null; grossSalesMoney: SquareMoney; }[]; /** What's still owed: `totalMoney` less what the order's tenders paid. */ netAmountDueMoney: SquareMoney; /** The payments made against the order, one per tender. */ tenders: SquareTender[]; } /** * One payment made against an order. Square adds a tender when a payment for * the order completes, so an order that has a tender with a `paymentId` was * paid, even if the response to that payment call never arrived. */ interface SquareTender { id: string; /** `CARD`, `CASH`, `SQUARE_GIFT_CARD`, and so on. */ type: string; /** The payment's ID, for `retrievePayment`; null for a tender with no * payment behind it, such as cash recorded by hand. */ paymentId: string | null; amountMoney: SquareMoney; /** The tip on top of `amountMoney`, zero when there's none. */ tipMoney: SquareMoney; } /** * An order's subtotal as Square computed it: the line items after discounts, * before taxes and service charges. `totalMoney` less `totalTaxMoney` and * `totalServiceChargeMoney`. * * Take a tip's cap on this, from {@link calculateOrder} on the client and from * the created order on the server, so both sides cap against the same number. * A subtotal summed from base variation prices misses discounts and * modifiers, and disagrees near the cap. */ declare function orderSubtotal(order: SquareOrder): SquareMoney; declare function createOrder(config: SquareConfig, input: { locationId: string; lineItems: SquareOrderLineItem[]; customerId?: string; referenceId?: string; idempotencyKey?: string; /** Taxes and discounts are opt-in—see {@link SquarePricingOptions}. * Omitting this charges exactly the line-item prices, pre-tax. */ pricingOptions?: SquarePricingOptions; /** Order-level charges (shipping). Pass the same list to * {@link calculateOrder} or the preview total will be short by exactly * this much. */ serviceCharges?: SquareServiceCharge[]; /** How the order reaches the customer. Not a pricing input, so * {@link calculateOrder} does not take it. */ fulfillments?: SquareFulfillment[]; /** `"DRAFT"` makes an order template: a subscription phase names it (see * `createSubscription`), and each billing cycle copies it, line items and * fulfillment included, into the order Square bills. A draft can't be paid * or fulfilled itself. Omit it for an order to charge now. */ state?: "DRAFT"; }): Promise; /** * Retrieve one order. GET /v2/orders/{id}. * * To see whether an order was paid, read it here rather than from a * {@link createOrder} replayed under its idempotency key, which can answer * with the order as it was first created, before any tender. */ declare function retrieveOrder(config: SquareConfig, orderId: string): Promise; /** * Search orders for a customer (account order history). Returns full orders, * newest first. POST /v2/orders/search. */ declare function searchOrdersByCustomer(config: SquareConfig, input: { locationIds: string[]; customerId: string; limit?: number; }): Promise; /** * Search orders across locations and a date range, following the cursor. * POST /v2/orders/search. The reporting rail: best-sellers, per-merchant sales * totals, reorder suggestions. * * Defaults to `COMPLETED` only. That matters for money questions—leaving the * state filter open counts `OPEN` (unpaid) and `CANCELED` orders as revenue, * which quietly inflates every downstream report. * * `closedAt` is the right axis for accounting (when money settled); `createdAt` * for funnel questions (when the order was raised). They differ for anything not * paid immediately, so the caller picks rather than inheriting a guess. */ declare function searchOrders(config: SquareConfig, input: { locationIds: string[]; /** RFC 3339, inclusive. */ startAt?: string; /** RFC 3339, exclusive. */ endAt?: string; /** Defaults to ["COMPLETED"]. Pass [] to disable state filtering entirely. */ states?: string[]; /** Which timestamp the range and sort apply to. Defaults to "closedAt". */ dateField?: "closedAt" | "createdAt" | "updatedAt"; sortOrder?: "ASC" | "DESC"; /** Page size (Square caps at 1000). Defaults to 500. */ limit?: number; /** Safety bound on cursor pages, applied PER location chunk. Defaults to 20. */ maxPages?: number; }): Promise; /** * Preview an order's totals without creating one. POST /v2/orders/calculate. * * The order is never persisted, so this is the honest way to show a cart total * that matches what checkout will charge: the same pricing engine, no order to * clean up if the customer walks away. * * Pass the SAME `pricingOptions` you will pass to {@link createOrder}. Taxes * are not applied by default here either, so a preview that omits them while * the charge applies them is the exact mismatch this call exists to prevent. */ declare function calculateOrder(config: SquareConfig, input: { locationId: string; lineItems: SquareOrderLineItem[]; customerId?: string; /** Must match what {@link createOrder} will be given, or the previewed * total is not the total that gets charged. */ pricingOptions?: SquarePricingOptions; /** Likewise—the same list {@link createOrder} will be given. */ serviceCharges?: SquareServiceCharge[]; }): Promise; //#endregion //#region src/core/commerce/square/wire.d.ts /** Per-location presence, carried on the CatalogObject itself (not inside * `item_data`). Square's model is "present everywhere except…" or "present * nowhere except…", selected by `present_at_all_locations`. */ interface RawPresence { present_at_all_locations?: boolean; present_at_location_ids?: string[]; absent_at_location_ids?: string[]; } /** A per-location price/inventory override on an ITEM_VARIATION. This is what * makes one shared catalog serve many merchants at different prices. */ interface RawLocationOverride { location_id?: string; price_money?: { amount?: number; currency?: string; }; pricing_type?: string; track_inventory?: boolean; sold_out?: boolean; } /** One entry in a catalog object's `custom_attribute_values` map. Square fills * `name` from the definition, so a reader can find a value by the name the * seller gave it in the Square Dashboard. */ interface RawCustomAttributeValue { name?: string; key?: string; custom_attribute_definition_id?: string; type?: string; string_value?: string; number_value?: string; boolean_value?: boolean; selection_uid_values?: string[]; } /** Carried on the CatalogObject itself, keyed by each definition's key. */ interface RawCustomAttributes { custom_attribute_values?: Record; } interface RawVariationData { /** The parent ITEM's id. */ item_id?: string; name?: string; sku?: string; price_money?: { amount?: number; currency?: string; }; location_overrides?: RawLocationOverride[]; } interface RawCatalogObject extends RawPresence, RawCustomAttributes { id: string; type: string; version?: number; is_deleted?: boolean; /** Present on ITEM_VARIATION objects returned top-level (batch-retrieve). */ item_variation_data?: RawVariationData; item_data?: { name?: string; description?: string; is_archived?: boolean; image_ids?: string[]; variations?: ({ id: string; type: string; version?: number; item_variation_data?: RawVariationData; } & RawPresence & RawCustomAttributes)[]; reporting_category?: { id?: string; }; categories?: { id?: string; }[]; modifier_list_info?: { modifier_list_id?: string; min_selected_modifiers?: number; max_selected_modifiers?: number; enabled?: boolean; }[]; }; category_data?: { name?: string; category_type?: string; is_top_level?: boolean; ordinal?: number; parent_category?: { id?: string; ordinal?: number; }; }; modifier_list_data?: { name?: string; selection_type?: string; modifiers?: { id: string; is_deleted?: boolean; modifier_data?: { name?: string; price_money?: { amount?: number; }; ordinal?: number; on_by_default?: boolean; }; }[]; }; image_data?: { url?: string; }; subscription_plan_data?: { name?: string; all_items?: boolean; eligible_item_ids?: string[]; eligible_category_ids?: string[]; subscription_plan_variations?: RawCatalogObject[]; }; subscription_plan_variation_data?: { name?: string; subscription_plan_id?: string; monthly_billing_anchor_date?: number; can_prorate?: boolean; successor_plan_variation_id?: string; phases?: { uid?: string; ordinal?: number; cadence?: string; periods?: number; /** The pre-`pricing` field; Square still sends it for a STATIC phase. */ recurring_price_money?: { amount?: number; currency?: string; }; pricing?: { type?: string; price_money?: { amount?: number; currency?: string; }; discount_ids?: string[]; }; }[]; }; } //#endregion //#region src/core/commerce/square/catalog.d.ts /** Where a catalog object is sold. Square models this as "everywhere except" or * "nowhere except"—{@link presentAt} collapses that to a single predicate so * callers never re-derive the logic. */ interface SquarePresence { presentAtAllLocations: boolean; presentAtLocationIds: string[]; absentAtLocationIds: string[]; } /** A per-location price override on a variation. Absent `priceCents` means the * override adjusts something other than price (availability, inventory * tracking) and the base price still applies. */ interface SquareLocationOverride { locationId: string; priceCents: number | null; /** The override price's ISO 4217 code, or `null` when Square sent none. */ currency: string | null; trackInventory: boolean | null; soldOut: boolean | null; } /** * Is this object sold at `locationId`? * * The two lists are not symmetric: `present_at_location_ids` is a whitelist used * when `present_at_all_locations` is false, `absent_at_location_ids` a blacklist * used when it is true. Getting this backwards silently shows a merchant * products they don't carry, so it lives in exactly one place. */ declare function presentAt(presence: SquarePresence, locationId: string): boolean; /** * A custom attribute value on a catalog object: a field the seller defined, * such as tasting notes on an item or a description on a variation. Square * Dashboard shows these on items and variations; modifiers and categories * carry them only through the API. */ interface SquareCustomAttribute { /** The CatalogCustomAttributeDefinition's id. */ definitionId: string; /** The definition's key. Another application's key is prefixed with its * application id and a colon. */ key: string; /** The definition's name, as the seller sees it in the Square Dashboard. */ name: string; /** `STRING`, `NUMBER`, `BOOLEAN`, or `SELECTION`. */ type: string; stringValue: string | null; /** A decimal string, as Square sends it, so no precision is lost. */ numberValue: string | null; booleanValue: boolean | null; /** The chosen options of a `SELECTION` attribute, by uid. */ selectionUids: string[]; } /** * The text of the `STRING` custom attribute called `name`, trimmed, or `null` * when the object has none or it's blank. Names match without regard to case, * so a seller who types "Online description" in the Square Dashboard matches * a site that asks for "online description". */ declare function customAttributeText(attributes: readonly SquareCustomAttribute[] | undefined, name: string): string | null; interface SquareVariation extends SquarePresence { id: string; name: string; sku: string | null; /** The BASE price. For what a given merchant charges, use * {@link priceAtLocation}; the override wins where one exists. */ priceCents: number; /** * The base price's ISO 4217 code, as Square sent it, or `null` when it sent * none. Square almost always names it. When it doesn't, use the currency your * site sells in: `variation.currency ?? siteCurrency`. */ currency: string | null; /** Per-location price overrides, empty when the base price applies everywhere. */ locationOverrides: SquareLocationOverride[]; /** Seller-defined fields, empty when there are none. Optional so an object * built by hand, or read from a cache written before this field, still * type-checks; {@link mapCatalogItem} always sets it. */ customAttributes?: SquareCustomAttribute[]; /** Object version—pass back to {@link upsertCatalogItem} when updating. */ version: number; } /** * A catalog price: an amount in the currency's minor unit, and the ISO 4217 * code Square sent with it, or `null` when it sent none. Like the shared * `Money`, except that the toolkit doesn't guess a missing currency: it's a * fact about the site, so fill it from your own settings with * `price.currency ?? siteCurrency`. */ interface SquareCatalogPrice { amount: number; currency: string | null; } /** * The effective price of a variation at one location: the location's override * if it sets a price, otherwise the base price. This is the single definition of * "what does this cost here", and server-side re-pricing at checkout must use it * rather than trusting a client-submitted amount. */ declare function priceAtLocation(variation: SquareVariation, locationId: string): SquareCatalogPrice; /** One of an item's catalog images. */ interface SquareItemImage { /** The catalog IMAGE object's id. */ id: string; /** Square's CDN URL, or `null` when the response didn't carry the IMAGE * object, as on a batch upsert or when the image was deleted. */ url: string | null; } interface SquareCatalogItem extends SquarePresence { id: string; name: string; description: string; /** The primary image's URL: the first entry in {@link images}. */ imageUrl: string | null; /** Every image on the item, in Square's order, primary first. Lets a site * show an image other than the primary, which is also the register's tile. */ images: SquareItemImage[]; variations: SquareVariation[]; /** Seller-defined fields, empty when there are none. Optional for the same * reason as {@link SquareVariation.customAttributes}. */ customAttributes?: SquareCustomAttribute[]; /** Object version—pass back to {@link upsertCatalogItem} when updating. */ version: number; } /** Map a raw ITEM object (+ resolved images) to the normalized shape. */ declare function mapCatalogItem(obj: RawCatalogObject, images: Map): SquareCatalogItem; /** * List every catalog ITEM that isn't deleted or archived, with its variations * and primary image. * Walks the search cursor (coffee catalogs are small; a safety cap bounds it). * POST /v2/catalog/search. */ declare function listCatalogItems(config: SquareConfig): Promise; /** Retrieve a single catalog object (+ related images). GET /v2/catalog/object/{id}. */ declare function retrieveCatalogItem(config: SquareConfig, objectId: string): Promise; /** * Batch-retrieve catalog objects by id—used at checkout to verify cart prices * against the live catalog before charging. POST /v2/catalog/batch-retrieve. * Returns a map of variationId → price for the ITEM_VARIATION objects, with a * `null` currency where Square sent none. * * A variation of an archived item is omitted, like an unknown id, so a caller * that requires every id to resolve won't sell something the shop took down. */ declare function retrieveVariationPrices(config: SquareConfig, variationIds: string[]): Promise>; /** * Which of `ids` still exist in the catalog—present and not deleted, * optionally only of one object `type` (for example, `"MODIFIER"`, so a variation id * can't pass for an add-on). A deleted or unknown id is simply absent. POST * /v2/catalog/batch-retrieve, chunked at Square's 1000-id limit; no request at * all for an empty list. * * The add-on half of cart verification: pass the result as `liveModifierIds` * to `cartIssues` (louise-toolkit/commerce). A deleted modifier reaching * `createOrder` makes Square reject the whole order, with nothing to tell the * customer which add-on it was. */ declare function retrieveLiveCatalogObjectIds(config: SquareConfig, ids: readonly string[], options?: { type?: string; }): Promise>; /** * Like {@link retrieveVariationPrices}, but resolves each price **at a specific * location**—the location's `location_overrides` price where one exists, else * the base price. * * This is the multi-merchant checkout guard. One shared catalog is sold at * different prices per merchant to absorb each shop's commission, so verifying a * cart against base prices would let a customer pay the cheapest merchant's * price at the dearest merchant's storefront. Re-price against the location the * order is actually being placed at, never against the client's numbers. * * A variation absent at `locationId`, or of an archived item, is omitted from * the result entirely, so a caller that requires every id to resolve will fail * closed rather than silently selling something the merchant does not carry. */ declare function retrieveVariationPricesAt(config: SquareConfig, variationIds: string[], locationId: string): Promise>; //#endregion //#region src/core/commerce/square/catalog-details.d.ts /** A REGULAR Square category (product taxonomy). The parallel MENU_CATEGORY tree * (Square Online display) is filtered out by {@link listCategories}. */ interface SquareCategory { id: string; name: string; /** URL-safe slug (for example, a shop's `?cat=` value). */ slug: string; /** Parent category id, or null for a top-level category. */ parentId: string | null; isTop: boolean; /** Square display ordinal (lower sorts first); 0 when absent. */ ordinal: number; } /** A single modifier (a size, a milk, an add-on)—name + price adjustment. */ interface SquareModifier { id: string; name: string; priceCents: number; onByDefault?: boolean; } /** A modifier list by id (name + selection type + children). The per-item * min/max bounds live in {@link ItemModifierRef}, joined when resolving a product. */ interface SquareModifierList { id: string; name: string; selectionType: "SINGLE" | "MULTIPLE"; modifiers: SquareModifier[]; } /** An item's reference to a modifier list, with its selection bounds. */ interface ItemModifierRef { id: string; min: number; max: number; } /** {@link listCatalogItems}'s items plus the per-item category / reporting-category * / modifier extraction a storefront needs. */ interface DetailedCatalog { items: SquareCatalogItem[]; /** itemId → every category id it references. */ itemCategories: Record; /** itemId → its `reporting_category` id. */ reportingCategory: Record; /** itemId → its enabled modifier-list refs (id + selection bounds). */ itemModifiers: Record; } /** * Like {@link listCatalogItems}, but ALSO returns each item's category refs, its * `reporting_category`, and its enabled modifier-list bounds. One walk of * `/v2/catalog/search` over ITEMs. Square uses -1 for an "unset" min/max—this * normalizes those to 0 (optional / unbounded). */ declare function listCatalogDetailed(config: SquareConfig): Promise; /** * List every non-deleted REGULAR catalog CATEGORY (the product taxonomy). The * parallel MENU_CATEGORY tree (Square Online display) is dropped. * POST /v2/catalog/search. */ declare function listCategories(config: SquareConfig): Promise; /** * List every non-deleted MODIFIER_LIST (size/milk/shots…) with its MODIFIER * children, as an id→list map. The per-item min/max bounds are joined from * {@link DetailedCatalog.itemModifiers} when resolving a product. * POST /v2/catalog/search. */ declare function listModifierLists(config: SquareConfig): Promise>; interface CatalogVariationInput { /** Existing Square variation id—pass to update; omit to create a new one. */ id?: string; /** Stable client key for a NEW variation, echoed back in `idMappings` so the * caller can persist the id Square assigns (ignored when `id` is set). */ clientId?: string; name: string; sku?: string; priceCents: number; currency?: string; /** Current Square version—required when UPDATING an existing variation * (Square uses optimistic concurrency; a stale/absent version is rejected). */ version?: number; /** Per-location price overrides—the multi-merchant pricing lever. Omit to * sell at the base price everywhere. */ locationOverrides?: { locationId: string; /** Omit to override availability/inventory without changing price. */ priceCents?: number; currency?: string; trackInventory?: boolean; soldOut?: boolean; }[]; /** Where this variation is sold. Omit for "everywhere". */ presence?: Partial; } /** * Create or update a catalog ITEM with its ITEM_VARIATIONs (fixed pricing). * POST /v2/catalog/object. This is the one catalog WRITE—sites where D1 owns * the product and pushes it up (vs. Square-as-source-of-truth reads above) call * this to mirror an item and its size/price variations into Square. * * Omit `id`s to create (Square assigns real ids, returned in `idMappings` keyed * by each variation's `clientId`/`#temp` id). To UPDATE, pass the item `id` + * each variation `id` AND its current `version` (from a prior retrieve)—Square * rejects a write with a stale version. Returns the normalized item with the * real ids resolved. */ declare function upsertCatalogItem(config: SquareConfig, input: CatalogPresentationInput & { id?: string; name: string; description?: string; variations: CatalogVariationInput[]; /** Current item version—required when updating an existing ITEM. */ version?: number; /** Where the ITEM is sold. Omit for "everywhere". */ presence?: Partial; idempotencyKey?: string; }): Promise<{ item: SquareCatalogItem; idMappings: Record; }>; /** Taxonomy and imagery on a catalog write—the "same picture and category * everywhere" half of a multi-merchant push. */ interface CatalogPresentationInput { /** * Existing IMAGE object ids, in display order—the first is the primary. * Upload with {@link createCatalogImage} to get one; there is no way to attach * raw bytes through this call. */ imageIds?: string[]; /** CATEGORY object ids this item belongs to. */ categoryIds?: string[]; /** * The single category Square attributes this item to in its own sales * reports. Must also appear in `categoryIds`—Square derives one from the * other inconsistently otherwise, and a reporting category the item isn't in * is how a product goes missing from a sales breakdown while looking correct * in the dashboard. */ reportingCategoryId?: string; } /** One ITEM in a {@link batchUpsertCatalogObjects} call. */ interface CatalogItemInput extends CatalogPresentationInput { id?: string; /** Stable client key echoed back in `idMappings` for a NEW item. */ clientId?: string; name: string; description?: string; variations: CatalogVariationInput[]; version?: number; presence?: Partial; } /** * Upsert many ITEMs in one call. POST /v2/catalog/batch-upsert. * * The per-object {@link upsertCatalogItem} costs one request per item, which * turns a full catalog push into a rate-limit problem. This batches them. Square * allows up to 1,000 objects per batch and 10,000 per request, counting each * variation as an object, so this packs items into batches under that limit and * refuses a write over the request limit before sending anything. An empty list * sends nothing. * * The whole request is atomic: if any object is rejected, none are written. That * is usually what you want for a catalog push (no half-applied price change), * but it does mean one stale `version` fails the entire batch. */ declare function batchUpsertCatalogObjects(config: SquareConfig, items: CatalogItemInput[], options?: { idempotencyKey?: string; }): Promise<{ idMappings: Record; objects: SquareCatalogItem[]; }>; /** An uploaded catalog IMAGE. `url` is Square's CDN copy, not the source. */ interface SquareCatalogImage { id: string; url: string | null; caption: string | null; } /** * Upload an image and get back a catalog IMAGE object. POST /v2/catalog/images. * * The only way to get an id for {@link CatalogPresentationInput.imageIds}—the * catalog write takes ids, never bytes, so this runs first and its `id` feeds * the upsert. * * Multipart, and deliberately not built on the JSON verbs: `content-type` must * carry the boundary `fetch` generates, so setting it by hand breaks the upload * in a way that reads as a Square-side rejection. * * Pass `objectId` to attach the image to an existing ITEM in one call. Omit it * to create a free-standing image and attach it via a later write—which is * what you want when pushing many items that share one picture, since uploading * the same bytes per item bills and stores per item. * * `caption` is the accessibility text Square renders; worth setting. */ declare function createCatalogImage(config: SquareConfig, input: { /** The bytes. A `File` carries its own name and type; a `Blob` needs `filename`. */ file: Blob; filename?: string; caption?: string; /** Attach to this catalog object as part of the upload. */ objectId?: string; idempotencyKey?: string; }): Promise; /** * A catalog object exactly as Square returned it. * * Deliberately open—an index signature, not a modelled interface. The whole * point of {@link readModifyWriteCatalog} is that fields this client does not * know about survive the round trip, and a closed type would invite callers to * rebuild the object from the parts it names, which is the bug being prevented. */ type SquareCatalogObject = { id: string; type: string; version?: number; [key: string]: unknown; }; /** * Read a catalog object, mutate it, and write it back without losing anything. * * Square documents this failure verbatim: *"If a client reads an object at an * older API version and writes it back at a newer version, fields that were * introduced between those two versions will be absent from the request, and the * server will interpret that absence"*—as an intentional clear. The same hazard * applies to any read-modify-write that reconstructs the object from the fields * it happens to model: whatever it didn't model is silently erased. * * So this never rebuilds. It reads the raw object, hands that object to * `mutate`, and writes back what it got—with the version Square returned (for * optimistic concurrency) and the same pinned `Square-Version` on both calls, * which is what makes the round trip symmetrical. * * ```ts * await readModifyWriteCatalog(config, "VAR123", (object) => { * const data = object.item_variation_data as Record; * data.price_money = { amount: 1800, currency: "USD" }; * }); * ``` * * `mutate` may edit in place or return a replacement. Returning `null` or * `undefined` from an in-place edit is normal—only a returned object replaces. * * Prefer {@link upsertCatalogItem} when creating or wholesale-replacing an item; * this is for touching one field of something that already exists, which is * exactly when accidental erasure is most likely and least visible. */ declare function readModifyWriteCatalog(config: SquareConfig, objectId: string, mutate: (object: SquareCatalogObject) => SquareCatalogObject | void | Promise, options?: { idempotencyKey?: string; }): Promise; //#endregion //#region src/core/commerce/square/inventory.d.ts interface SquareInventoryCount { catalogObjectId: string; state: string; quantity: number; locationId: string; } /** POST /v2/inventory/counts/batch-retrieve. */ declare function retrieveInventoryCounts(config: SquareConfig, catalogObjectIds: string[], locationIds?: string[]): Promise; /** * One inventory change. `PHYSICAL_COUNT` sets an absolute quantity ("there are 4 * here now"); `ADJUSTMENT` moves stock between states by a delta. * * Prefer PHYSICAL_COUNT when reconciling against a real-world count: it is * idempotent in effect, so a replayed message lands on the same number, whereas * a replayed ADJUSTMENT double-counts. */ type SquareInventoryChange = { type: "PHYSICAL_COUNT"; catalogObjectId: string; locationId: string; quantity: number; /** Defaults to IN_STOCK. */ state?: string; /** RFC 3339. Defaults to now. Square rejects timestamps in the future. */ occurredAt?: string; } | { type: "ADJUSTMENT"; catalogObjectId: string; locationId: string; quantity: number; fromState: string; toState: string; occurredAt?: string; }; /** * Apply inventory changes. POST /v2/inventory/changes/batch-create. * * Note the direction of truth: D1 owns price, presence and placement, but * **Square owns inventory counts**. This exists for the reconcile path—a * physical recount, or seeding a new merchant's opening stock—not for mirroring * a D1 number over Square's on every sync. */ declare function batchChangeInventory(config: SquareConfig, changes: SquareInventoryChange[], options?: { idempotencyKey?: string; }): Promise; /** Set one variation's absolute on-hand count at one location—the common case * of {@link batchChangeInventory}, named for what it does. */ declare function setPhysicalCount(config: SquareConfig, input: { catalogObjectId: string; locationId: string; quantity: number; state?: string; occurredAt?: string; idempotencyKey?: string; }): Promise; //#endregion //#region src/core/commerce/square/menu.d.ts /** What {@link buildMenuTabs} reads: the four catalog reads, as fetched. */ interface MenuCatalog { /** From `listCatalogDetailed`. */ catalog: DetailedCatalog; /** From `listCategories`: the REGULAR category tree. */ categories: SquareCategory[]; /** From `listModifierLists`. */ modifierLists: Record; /** * From `retrieveInventoryCounts`, for the location the menu sells from. Only * `IN_STOCK` counts are read. A variation with no count is untracked, and an * untracked variation is never sold out. Pass `[]` when stock is unavailable, * and nothing shows as sold out. */ counts: SquareInventoryCount[]; } /** Options for {@link buildMenuTabs}. Both lists are the site's, usually set by an editor. */ interface MenuTabsOptions { /** * The top-level categories the menu shows, in tab order. An id that isn't a * top-level REGULAR category is skipped. An empty list is an empty menu: * guessing a category from its name is the site's call, not this function's. */ categoryIds: string[]; /** Items to leave off the menu, by Square item id. */ hiddenItemIds?: string[]; /** * The location the menu sells from. When set, a variation's price is its * price there (`priceAtLocation`), and only that location's counts are read. * Leave it out to use base prices and every count passed. */ locationId?: string; } /** A modifier list as one item offers it: the list plus that item's selection bounds. */ interface MenuModifierList extends SquareModifierList { /** The fewest modifiers a customer must pick; 0 when optional. From the item's ref. */ min: number; /** The most a customer may pick; 0 when unbounded. From the item's ref. */ max: number; } /** A variation a customer can order. */ interface MenuVariation { id: string; name: string; priceCents: number; /** The price's ISO 4217 code, or `null` when Square sent none, as on `SquareVariation`. */ currency: string | null; /** Units in stock, or `null` when Square doesn't track this variation. */ stock: number | null; } /** One item on a {@link MenuTab}. */ interface MenuItem { id: string; name: string; description: string; imageUrl: string | null; /** The priced variations, in Square's order. Never empty. */ variations: MenuVariation[]; /** True only when every variation is tracked and at zero or below. */ soldOut: boolean; /** The item's enabled modifier lists, in the item's order. A list with no modifiers is left out. */ modifierLists: MenuModifierList[]; } /** One tab of the menu: a subcategory, or a top-level category's own items. */ interface MenuTab { /** The category's id. */ id: string; name: string; slug: string; items: MenuItem[]; } /** * Menu tabs for an order-ahead app, from Square's category tree. * * Each chosen top-level category gives one tab per direct subcategory, in * Square's ordinal order, holding the items filed under that subcategory or * any level below it. Items filed directly under the top-level category, in * none of its subcategories, go in a trailing tab named after it. A top-level * category with no subcategories is that one tab. A tab with no items is left * out. * * An item filed under two subcategories appears in both tabs, so each tab * shows its full membership. A view that shows every tab at once dedupes by * item id. * * The rules each item follows: * * - **Hidden:** an item in `hiddenItemIds` is left off. * - **Priced:** a variation priced at 0, such as Square's variable pricing, * rings up at the register and can't be ordered online, so it's dropped. An * item with no priced variation left is off the menu. * - **Sold out:** only when every variation is tracked and at zero or below. * An untracked item, such as a drink made to order, is never sold out. * - **Modifiers:** each list's `min` and `max` come from the item's ref, not * the list, since two items can bound one list differently. */ declare function buildMenuTabs(input: MenuCatalog, options: MenuTabsOptions): MenuTab[]; //#endregion //#region src/core/commerce/square/payments.d.ts interface SquarePayment { id: string; status: string; orderId: string | null; amountMoney: SquareMoney; /** The tip, when one was sent; zero otherwise. Not included in `amountMoney`. */ tipMoney: SquareMoney; receiptUrl: string | null; /** When Square created the payment, as an RFC 3339 timestamp. */ createdAt: string | null; } /** * Charge a payment with a Web Payments SDK card token (`sourceId`). Attach the * order so the amount matches Square's computed total. POST /v2/payments. * * A tip goes in `tipMoney`, never folded into `amountMoney`: Square requires a * payment for an order to equal the order's total, and documents `amount_money` * as "not including tip_money". Tips live on the payment, not the order. */ declare function createPayment(config: SquareConfig, input: { sourceId: string; amountMoney: SquareMoney; /** Charged on top of `amountMoney`. Omitted from the body when zero. */ tipMoney?: SquareMoney; locationId: string; orderId?: string; customerId?: string; /** Web Payments SCA verification token (verifyBuyer) when present. */ verificationToken?: string; buyerEmailAddress?: string; referenceId?: string; idempotencyKey?: string; }): Promise; /** * Retrieve one payment. GET /v2/payments/{id}. With the `paymentId` of an * order's tender, this recovers a payment whose create call failed after * Square took it: its status, amounts, and receipt. */ declare function retrievePayment(config: SquareConfig, paymentId: string): Promise; //#endregion //#region src/core/commerce/square/customers.d.ts interface SquareCustomer { id: string; email: string | null; givenName: string | null; familyName: string | null; phoneNumber: string | null; } /** Find customers by exact email. POST /v2/customers/search. */ declare function searchCustomersByEmail(config: SquareConfig, email: string): Promise; /** Retrieve one customer. GET /v2/customers/{id}. */ declare function retrieveCustomer(config: SquareConfig, customerId: string): Promise; /** Create a customer. POST /v2/customers. */ declare function createCustomer(config: SquareConfig, input: { email: string; givenName?: string; familyName?: string; phoneNumber?: string; }): Promise; /** * Find-or-create a Square customer by email—used to (optionally) link a site * account to Square. Returns the customer and whether it was created. The * names and phone apply only when creating; to change a customer that already * exists, use {@link updateCustomer}. */ declare function ensureCustomer(config: SquareConfig, input: { email: string; givenName?: string; familyName?: string; phoneNumber?: string; }): Promise<{ customer: SquareCustomer; created: boolean; }>; /** * Change fields on an existing customer. PUT /v2/customers/{id}. Sparse: only * the fields you pass are sent, so an omitted one is left as it is—pass * `null` to clear it. */ declare function updateCustomer(config: SquareConfig, customerId: string, input: { email?: string | null; givenName?: string | null; familyName?: string | null; phoneNumber?: string | null; }): Promise; //#endregion //#region src/core/commerce/square/cards.d.ts interface SquareCard { id: string; last4: string | null; cardBrand: string | null; expMonth: number | null; expYear: number | null; /** The customer the card is on file for, when Square says. */ customerId?: string | null; /** `false` once disabled. */ enabled?: boolean; } /** * Save a card on file from a Web Payments token, attached to a customer—the * card id then seeds a subscription. POST /v2/cards. */ declare function createCard(config: SquareConfig, input: { sourceId: string; customerId: string; idempotencyKey?: string; verificationToken?: string; }): Promise; /** * A customer's cards on file, following the cursor. GET /v2/cards. Enabled * cards only unless `includeDisabled`. */ declare function listCards(config: SquareConfig, input: { customerId: string; includeDisabled?: boolean; maxPages?: number; }): Promise; /** * Disable (remove) a card on file—but only if it is on file for * `customerId`. Returns `false`, without disabling anything, when the card * doesn't exist or belongs to someone else, so a guessed card id from one * signed-in customer can't remove another's. POST /v2/cards/{id}/disable. */ declare function disableCard(config: SquareConfig, cardId: string, input: { customerId: string; }): Promise; //#endregion //#region src/core/commerce/square/loyalty.d.ts interface SquareLoyaltyAccount { id: string; programId: string | null; balance: number; lifetimePoints: number; customerId: string | null; } /** * The loyalty account for a Square customer (points balance / lifetime), or * null if they have none. POST /v2/loyalty/accounts/search. */ declare function retrieveLoyaltyAccountByCustomer(config: SquareConfig, customerId: string): Promise; interface SquareLoyaltyAccrualRule { /** `"SPEND"`, `"VISIT"`, `"ITEM_VARIATION"` or `"CATEGORY"`—as Square sends it. */ type: string; points: number; /** SPEND: points are earned per this much spend. */ spendMoney: SquareMoney | null; /** VISIT: the minimum purchase for a visit to count. */ visitMinimumMoney: SquareMoney | null; /** ITEM_VARIATION: the variation that earns. */ itemVariationId: string | null; /** CATEGORY: the category that earns. */ categoryId: string | null; } interface SquareLoyaltyProgram { id: string; /** `"ACTIVE"` or `"INACTIVE"`. An inactive program earns nothing. */ status: string; /** What the seller calls points, as set in the Dashboard, for example, Star / Stars. */ terminology: { one: string; other: string; } | null; accrualRules: SquareLoyaltyAccrualRule[]; /** Cheapest first. */ rewardTiers: { id: string; name: string; points: number; }[]; } /** * The seller's loyalty program—its earn rules, reward tiers and what it * calls points—or `null` when the seller has none (Square answers 404). * GET /v2/loyalty/programs/main (`main` is Square's alias for the seller's one * program). Any other failure throws, so a transient error isn't mistaken for * "no program" and cached as one. * * Returned as Square has it, inactive programs included: check `status` before * advertising it. */ declare function retrieveLoyaltyProgram(config: SquareConfig): Promise; //#endregion //#region src/core/commerce/square/subscription-plans.d.ts /** * One billing phase of a plan variation. Square bills `cadence` by `cadence` * for `periods` of them, then moves to the next phase; the last phase may run * forever. A free trial is a first phase with a 100% discount. */ interface SquareSubscriptionPhase { uid: string | null; /** Position in the variation's phases, from 0. */ ordinal: number; /** Square's cadence name: `WEEKLY`, `EVERY_TWO_WEEKS`, `MONTHLY`, * `QUARTERLY`, `ANNUAL`, and so on. */ cadence: string; /** How many cadences the phase lasts; `null` means it never ends. */ periods: number | null; /** `STATIC` bills `priceCents` each cadence. `RELATIVE` bills the order * template a subscription names for the phase, less `discountIds`. */ pricingType: string; priceCents: number | null; /** The price's ISO 4217 code, or `null` when Square sent none. */ currency: string | null; discountIds: string[]; } /** How often, and for how much: what a customer subscribes to. */ interface SquareSubscriptionPlanVariation extends SquarePresence { id: string; planId: string | null; name: string; phases: SquareSubscriptionPhase[]; /** Day of the month billing starts on, for a monthly cadence. */ monthlyBillingAnchorDate: number | null; canProrate: boolean; version: number; } /** What can be subscribed to, with the ways to subscribe to it. */ interface SquareSubscriptionPlan extends SquarePresence { id: string; name: string; /** Every item is eligible; the two ID lists are then empty. */ allItems: boolean; eligibleItemIds: string[]; eligibleCategoryIds: string[]; variations: SquareSubscriptionPlanVariation[]; version: number; } /** * List every non-deleted subscription plan with its variations. * POST /v2/catalog/search over SUBSCRIPTION_PLAN and SUBSCRIPTION_PLAN_VARIATION. * * Square returns a variation two ways, nested under its plan and as an object * of its own, and either can arrive alone, so both are read and joined on the * plan ID. A variation whose plan isn't in the catalog is dropped: there's * nothing to subscribe it to. Deleted plans and variations are skipped. */ declare function listSubscriptionPlans(config: SquareConfig): Promise; /** * One way to subscribe to an item: a plan variation the item is eligible for, * with the cadence its ongoing phase bills at. `subscriptionOffersFor` builds * them from `listSubscriptionPlans`. */ interface SquareSubscriptionOffer { planId: string; planName: string; /** The plan variation ID, which `createSubscription` enrolls in. */ variationId: string; /** The variation's name, as the seller wrote it in Square. */ name: string; /** Square's cadence name: `MONTHLY` and the like. */ cadence: string; /** The cadence for a customer, from `cadenceLabel`: "Every 2 weeks". */ every: string; /** The ongoing phase's pricing. Always `RELATIVE` for now; see * `subscriptionOffersFor`. */ pricingType: string; /** `null` for a `RELATIVE` offer, which bills the item at its catalog price, * less the plan's discounts, rather than at a price of its own. */ priceCents: number | null; } /** The item side of a plan's eligibility: a catalog item and the categories * it's in. */ interface SquareSubscribableItem { /** The catalog item ID, which a plan's `eligibleItemIds` names. */ itemId: string; categoryIds: readonly string[]; } /** * A site's own words for Square's cadence names. A map replaces the built-in * label for each cadence it names and leaves the rest English. A function is * asked about every cadence, including one Square adds later, so a site in * another language never shows English; it returns `undefined` to fall back * to the built-in label. */ type SquareCadenceLabels = Readonly> | ((cadence: string) => string | undefined); /** * A Square cadence name as a customer reads it: "Every 2 weeks" for * `EVERY_TWO_WEEKS`. A cadence the table doesn't know reads as Square names * it, lowercased ("Every five weeks" for `EVERY_FIVE_WEEKS`), so a new one is * odd rather than blank. An empty cadence gives `""`. * * The built-in table and the fallback are English. `labels` replaces either: * a map, cadence by cadence, or a function, for every cadence (see * `SquareCadenceLabels`). */ declare function cadenceLabel(cadence: string, labels?: SquareCadenceLabels): string; /** * The phase a subscription settles into: the last one, since an earlier phase, * such as a trial, ends, and the last may run forever. `undefined` for a * variation with no phases. */ declare function ongoingPhase(variation: Pick): SquareSubscriptionPhase | undefined; /** Whether a plan covers an item: it names the item, one of the item's * categories, or every item. */ declare function planCoversItem(plan: Pick, item: SquareSubscribableItem): boolean; /** * The ways to subscribe to an item, in the plans' order. A plan has to cover * the item (see `planCoversItem`). When you pass `locationId`, both the plan * and the variation have to be present at that location; without it, no * location filter applies. * * Only a variation whose ongoing phase prices `RELATIVE` is offered. Square * bills a `RELATIVE` phase by copying the order template the enrollment * builds, so each cycle can carry the item, a shipment, and a shipping charge. * A `STATIC` variation raises an invoice only, with no order to fulfill, and a * variation with no phase has nothing to bill. * * `options.labels` goes to `cadenceLabel` for each offer's `every`. */ declare function subscriptionOffersFor(plans: readonly SquareSubscriptionPlan[], item: SquareSubscribableItem, locationId?: string, options?: { labels?: SquareCadenceLabels; }): SquareSubscriptionOffer[]; /** * The offer for one plan variation ID, or `null` when the item has no such * offer: the variation doesn't exist, the item isn't eligible, it isn't * present at `locationId`, or `subscriptionOffersFor` doesn't offer it. Check a * plan variation ID a client sent with this before you enroll in it. */ declare function findSubscriptionOffer(plans: readonly SquareSubscriptionPlan[], item: SquareSubscribableItem, planVariationId: string, locationId?: string, options?: { labels?: SquareCadenceLabels; }): SquareSubscriptionOffer | null; /** * The `phases` that `createSubscription` takes for a variation: one entry per * `RELATIVE` phase, by ordinal, each naming `templateOrderId`, the `DRAFT` * order from `createOrder` that Square copies each cycle. A `STATIC` phase * bills the plan's own price and takes no template, so a variation with no * `RELATIVE` phase gives `[]`. */ declare function templatePhases(variation: Pick, templateOrderId: string): { ordinal: number; orderTemplateId: string; }[]; //#endregion //#region src/core/commerce/square/subscriptions.d.ts interface SquareSubscription { id: string; /** `PENDING`, `ACTIVE`, `PAUSED`, `CANCELED`, `DEACTIVATED`, or `COMPLETED`. * A cancel leaves it `ACTIVE` until `canceledDate`. */ status: string; planVariationId: string | null; customerId: string | null; cardId: string | null; locationId: string | null; /** `YYYY-MM-DD`: when billing started, or starts. */ startDate: string | null; /** `YYYY-MM-DD`: when billing stops, once a cancel is scheduled. */ canceledDate: string | null; /** `YYYY-MM-DD`: paid through here; the next bill comes the day after. */ chargedThroughDate: string | null; /** The invoices Square raised, newest first. */ invoiceIds: string[]; /** Each phase's order template, when the subscription bills by template. */ phases: SquareSubscriptionPhaseRef[]; /** Scheduled changes that haven't taken effect yet. */ actions: SquareSubscriptionAction[]; /** For `updateSubscription`'s optimistic concurrency. */ version: number | null; createdAt: string | null; } interface SquareSubscriptionPhaseRef { uid: string | null; ordinal: number; orderTemplateId: string | null; planPhaseUid: string | null; } /** A pending `CANCEL`, `PAUSE`, `RESUME`, or `SWAP_PLAN`. */ interface SquareSubscriptionAction { id: string; type: string; effectiveDate: string | null; newPlanVariationId: string | null; } /** A subscription plus the actions a lifecycle call scheduled. */ interface SquareSubscriptionChange { subscription: SquareSubscription; actions: SquareSubscriptionAction[]; } /** Active/past subscriptions for a customer. POST /v2/subscriptions/search. */ declare function searchSubscriptionsByCustomer(config: SquareConfig, input: { customerId: string; locationIds?: string[]; }): Promise; /** One subscription with its pending actions, or `null` when there's none by * that id. GET /v2/subscriptions/{id}. */ declare function retrieveSubscription(config: SquareConfig, subscriptionId: string): Promise; /** * Enroll a customer in a subscription plan variation, billed to a saved card. * POST /v2/subscriptions. * * A variation whose phase prices `RELATIVE` bills an order template instead of * a fixed amount: pass one `phases` entry per plan phase, naming a `DRAFT` * order from `createOrder` as its template. Each cycle copies that order, * fulfillment included, so a shipment's address goes on the template. */ declare function createSubscription(config: SquareConfig, input: { locationId: string; planVariationId: string; customerId: string; cardId: string; idempotencyKey?: string; /** `YYYY-MM-DD`; defaults to today. */ startDate?: string; /** The order template for each plan phase, by the phase's ordinal. */ phases?: { ordinal: number; orderTemplateId: string; }[]; /** Replaces a `STATIC` phase price for this one customer. */ priceOverride?: SquareMoney; /** Tax rate as a decimal string without `%`, for example "8.5". */ taxPercentage?: string; /** IANA zone the billing dates are read in; defaults to the location's. */ timezone?: string; }): Promise; /** * Change a subscription. PUT /v2/subscriptions/{id}. Sparse: only the fields * you pass are sent. `canceledDate: null` undoes a scheduled cancel; a date * can't be set here, `cancelSubscription` does that. Pass the `version` you * read so a change made since makes Square refuse, rather than overwrite. */ declare function updateSubscription(config: SquareConfig, subscriptionId: string, input: { cardId?: string; canceledDate?: null; priceOverride?: SquareMoney | null; taxPercentage?: string | null; version?: number; }): Promise; /** * Schedule a cancel for the end of the current billing period: `canceledDate` * is set, the status stays `ACTIVE` until then, and the customer keeps what * they paid for. POST /v2/subscriptions/{id}/cancel. Undo it with * `updateSubscription(id, { canceledDate: null })`. */ declare function cancelSubscription(config: SquareConfig, subscriptionId: string): Promise; /** * Schedule a pause. POST /v2/subscriptions/{id}/pause. With no options it * pauses at the end of the current billing period, until resumed; give * `pauseCycles` to resume after that many skipped bills, or a * `resumeEffectiveDate`. */ declare function pauseSubscription(config: SquareConfig, subscriptionId: string, input?: { /** `YYYY-MM-DD`; defaults to the end of the current billing period. */ pauseEffectiveDate?: string; /** Billing cycles to skip before resuming on its own. */ pauseCycles?: number; /** `YYYY-MM-DD` to resume on, instead of `pauseCycles`. */ resumeEffectiveDate?: string; /** When the resume bills: `IMMEDIATE` or `END_OF_PERIOD`. */ resumeChangeTiming?: "IMMEDIATE" | "END_OF_PERIOD"; /** Shown in the Square Dashboard. */ pauseReason?: string; }): Promise; /** * Schedule a resume of a paused or deactivated subscription. * POST /v2/subscriptions/{id}/resume. With no options it resumes now. */ declare function resumeSubscription(config: SquareConfig, subscriptionId: string, input?: { /** `YYYY-MM-DD`; defaults to today. */ resumeEffectiveDate?: string; /** When the first bill after the resume comes: `IMMEDIATE` or `END_OF_PERIOD`. */ resumeChangeTiming?: "IMMEDIATE" | "END_OF_PERIOD"; }): Promise; //#endregion //#region src/core/commerce/square/team.d.ts interface SquareTeamMember { id: string; referenceId: string | null; givenName: string | null; familyName: string | null; emailAddress: string | null; phoneNumber: string | null; status: string; isOwner: boolean; } interface TeamMemberInput { givenName?: string; familyName?: string; emailAddress?: string; phoneNumber?: string; /** Your own id for this person (for example, a portal_user id)—round-trips on the * Square record so you can correlate without a separate lookup. */ referenceId?: string; status?: "ACTIVE" | "INACTIVE"; /** Assign to all current + future locations (the common default). Omit and * Square assigns none; you manage locations yourself. */ assignAllLocations?: boolean; } /** Create a team member (employee). POST /v2/team-members. */ declare function createTeamMember(config: SquareConfig, input: TeamMemberInput & { idempotencyKey?: string; }): Promise; /** Update a team member. PUT /v2/team-members/{id}. */ declare function updateTeamMember(config: SquareConfig, teamMemberId: string, input: TeamMemberInput): Promise; /** Retrieve one team member. GET /v2/team-members/{id}. */ declare function retrieveTeamMember(config: SquareConfig, teamMemberId: string): Promise; /** * Search team members. POST /v2/team-members/search. The Team API has no email * filter, so pass `status`/`locationIds` and match the rest client-side (by * `referenceId` or `emailAddress`). Coffee teams are small—one page suffices, * so this returns the first page (up to `limit`, default 200). */ declare function searchTeamMembers(config: SquareConfig, input?: { locationIds?: string[]; status?: "ACTIVE" | "INACTIVE"; limit?: number; }): Promise; //#endregion //#region src/core/commerce/square/labor.d.ts interface SquareTimecard { id: string; locationId: string; teamMemberId: string; startAt: string; endAt: string | null; status: string; /** Optimistic-concurrency version—pass it back to update/close the card. */ version: number; /** Wage on the card (Square defaults it from the team member). An update is a * full replace and Square requires a wage, so pass this back when closing. */ wage: { title: string | null; hourlyRateCents: number; currency: string; } | null; } interface TimecardWage { title?: string; hourlyRateCents: number; currency?: string; } /** * Open a timecard (clock in). POST /v2/labor/timecards. A team member can hold * only ONE open timecard at a time. `startAt` is an RFC 3339 timestamp; pass a * `wage` (hourly rate) for Square to compute labor cost. Returns the timecard * incl. its `version`, which you need to close it later. Requires Square-Version * ≥ 2025-05-21 (the default pinned {@link SQUARE_VERSION} satisfies this). */ declare function createTimecard(config: SquareConfig, input: { locationId: string; teamMemberId: string; startAt: string; wage?: TimecardWage; idempotencyKey?: string; }): Promise; /** * Update a timecard—typically to close it (clock out) by setting `endAt`. * PUT /v2/labor/timecards/{id} REPLACES the record, so pass its full state * (location, team member, start) plus the current `version` from the prior * create/retrieve (Square rejects a stale version). */ declare function updateTimecard(config: SquareConfig, timecardId: string, input: { locationId: string; teamMemberId: string; startAt: string; endAt?: string; version: number; wage?: TimecardWage; }): Promise; /** Retrieve one timecard (for example, to read its current version before closing). * GET /v2/labor/timecards/{id}. */ declare function retrieveTimecard(config: SquareConfig, timecardId: string): Promise; /** * Search timecards (labor reporting). POST /v2/labor/timecards/search. Filter * by team members, locations, and/or a start-time window (RFC 3339). * Returns the first page newest-first (up to `limit`, default 200). */ declare function searchTimecards(config: SquareConfig, input?: { teamMemberIds?: string[]; locationIds?: string[]; startAtMin?: string; startAtMax?: string; limit?: number; }): Promise; //#endregion //#region src/core/commerce/square/invoices.d.ts interface SquareInvoicePaymentRequest { uid: string | null; requestType: string; dueDate: string | null; status: string | null; computedAmountCents: number; totalCompletedAmountCents: number; } interface SquareInvoice { id: string; version: number; status: string; orderId: string | null; /** Square-hosted pay page—present after publishing with SHARE_MANUALLY. */ publicUrl: string | null; paymentRequests: SquareInvoicePaymentRequest[]; } interface InvoicePaymentRequestInput { /** Exactly one BALANCE (the last request), with an optional leading DEPOSIT * and/or 2–12 INSTALLMENTs. */ type: "DEPOSIT" | "BALANCE" | "INSTALLMENT"; /** Due date, YYYY-MM-DD. */ dueDate: string; /** Fixed amount for this request. Omit on BALANCE to auto-cover the remainder. */ amountCents?: number; currency?: string; } /** * Create a DRAFT invoice for an existing OPEN Square Order (the order carries * the line items + total; the invoice adds the payment schedule + recipient). * POST /v2/invoices. Publish with {@link publishInvoice} to start collecting. * `deliveryMethod` "SHARE_MANUALLY" (default) yields a `publicUrl` after publish; * send your own email linking to it; "EMAIL" has Square email the customer. */ declare function createInvoice(config: SquareConfig, input: { locationId: string; orderId: string; customerId: string; paymentRequests: InvoicePaymentRequestInput[]; deliveryMethod?: "SHARE_MANUALLY" | "EMAIL"; title?: string; description?: string; idempotencyKey?: string; }): Promise; /** Publish a draft invoice (starts processing; yields the hosted `publicUrl` when * created with SHARE_MANUALLY). POST /v2/invoices/{id}/publish. Pass the current * `version` from {@link createInvoice} (optimistic concurrency). */ declare function publishInvoice(config: SquareConfig, invoiceId: string, version: number, idempotencyKey?: string): Promise; /** Retrieve one invoice—for example, to read each payment request's completed amount * when reconciling a webhook. GET /v2/invoices/{id}. */ declare function retrieveInvoice(config: SquareConfig, invoiceId: string): Promise; //#endregion //#region src/core/commerce/square/payment-links.d.ts interface SquarePaymentLink { id: string; /** Optimistic-concurrency version; required to update the link. */ version: number; /** The short `square.link` URL—the one to put in front of a buyer. */ url: string; /** The long `checkout.square.site` form. Absent on some responses. */ longUrl: string | null; /** The Order the link created. The attribution anchor for the webhook. */ orderId: string | null; createdAt: string | null; } /** Wallets offered on the hosted page. Omit a flag to take Square's default. */ interface SquareAcceptedPaymentMethods { applePay?: boolean; googlePay?: boolean; cashAppPay?: boolean; afterpayClearpay?: boolean; } /** Optional presentation/behavior of the hosted checkout page. */ interface SquareCheckoutOptions { /** Absolute https URL Square returns the buyer to after payment. Carry your * own order/session id in its query string—this is the only hook you get * for a branded confirmation page. */ redirectUrl?: string; /** Square collects and validates the shipping address on its own page. */ askForShippingAddress?: boolean; merchantSupportEmail?: string; acceptedPaymentMethods?: SquareAcceptedPaymentMethods; allowTipping?: boolean; shippingFee?: { name?: string; charge: SquareMoney; }; enableCoupon?: boolean; enableLoyalty?: boolean; } /** A one-off "name + price" link with no Order behind it. Cannot carry a * `referenceId`, so prefer {@link PaymentLinkOrderInput} when the sale has to * be attributed to anything. */ interface QuickPayInput { name: string; priceMoney: SquareMoney; locationId: string; } /** An Order-backed link. Line items may be ad-hoc (no catalog object). */ interface PaymentLinkOrderInput { locationId: string; lineItems: SquareOrderLineItem[]; customerId?: string; /** Up to 40 chars. Surfaced in the Square dashboard + Transactions export, * which is what makes it usable for attribution without this system. */ referenceId?: string; } /** * Create a Square-hosted checkout page. * POST /v2/online-checkout/payment-links. * * Exactly one of `quickPay` or `order`—passing both is rejected here rather * than by Square, so the mistake surfaces at the call site. * * `idempotencyKey` defaults to a random UUID, which is right for an interactive * checkout (each attempt is a new link). Pass a deterministic key only when a * retry must resolve to the SAME link. */ declare function createPaymentLink(config: SquareConfig, input: { quickPay?: QuickPayInput; order?: PaymentLinkOrderInput; description?: string; paymentNote?: string; checkoutOptions?: SquareCheckoutOptions; prePopulatedData?: { buyerEmail?: string; buyerPhoneNumber?: string; }; idempotencyKey?: string; }): Promise; /** Retrieve one payment link. GET /v2/online-checkout/payment-links/{id}. * Returns null when it no longer exists (already deleted, or a bad id). */ declare function retrievePaymentLink(config: SquareConfig, linkId: string): Promise; /** Delete a payment link, cancelling its unpaid order. * DELETE /v2/online-checkout/payment-links/{id}. */ declare function deletePaymentLink(config: SquareConfig, linkId: string): Promise<{ id: string; cancelledOrderId: string | null; }>; //#endregion //#region src/core/commerce/square/webhooks.d.ts /** * Verify a Square webhook signature. Square signs the concatenation of the * exact notification URL you configured and the raw request body with * HMAC-SHA256, base64-encoded, delivered in the `x-square-hmacsha256-signature` * header (this reproduces the SDK's WebhooksHelper.verifySignature). `body` * must be the raw request text. */ declare function verifySquareSignature(notificationUrl: string, body: string, signatureHeader: string | null, signatureKey: string): Promise; /** * A Square webhook event, validated to the envelope this integration reads. * Run it via {@link import("./index.js").parseWebhookEvent} AFTER * {@link verifySquareSignature}. Square nests the changed resource under * `data.object`, keyed by `data.type` (for example, `payment`, `invoice`, `order`) with * `data.id` the resource id—the handler switches on the top-level `type` and * reads/re-fetches from there. The object stays an untyped record (its shape * depends on `data.type`); extra envelope keys (merchant_id, created_at, …) are * dropped. */ declare const squareWebhookEventSchema: StandardSchemaV1 | undefined; }; }>; //#endregion export { CatalogItemInput, CatalogPresentationInput, CatalogVariationInput, DetailedCatalog, InvoicePaymentRequestInput, ItemModifierRef, MenuCatalog, MenuItem, MenuModifierList, MenuTab, MenuTabsOptions, MenuVariation, PaymentLinkOrderInput, QuickPayInput, SQUARE_VERSION, SquareAcceptedPaymentMethods, SquareAddress, SquareApiError, SquareCadenceLabels, SquareCard, SquareCatalogImage, SquareCatalogItem, SquareCatalogObject, SquareCatalogPrice, SquareCategory, SquareCheckoutOptions, SquareConfig, SquareCustomAttribute, SquareCustomer, SquareEnvironment, SquareFulfillment, SquareFulfillmentRecipient, SquareInventoryChange, SquareInventoryCount, SquareInvoice, SquareInvoicePaymentRequest, SquareItemImage, SquareLocation, SquareLocationInput, SquareLocationOverride, SquareLoyaltyAccount, SquareLoyaltyAccrualRule, SquareLoyaltyProgram, SquareModifier, SquareModifierList, SquareMoney, SquareOrder, SquareOrderLineItem, SquarePayment, SquarePaymentLink, SquarePresence, SquarePricingOptions, SquareRetryConfig, SquareServiceCharge, SquareSubscribableItem, SquareSubscription, SquareSubscriptionAction, SquareSubscriptionChange, SquareSubscriptionOffer, SquareSubscriptionPhase, SquareSubscriptionPhaseRef, SquareSubscriptionPlan, SquareSubscriptionPlanVariation, SquareTeamMember, SquareTender, SquareTimecard, SquareVariation, TeamMemberInput, TimecardWage, batchChangeInventory, batchUpsertCatalogObjects, buildMenuTabs, cadenceLabel, calculateOrder, cancelSubscription, centsToMajor, createCard, createCatalogImage, createCustomer, createInvoice, createLocation, createOrder, createPayment, createPaymentLink, createSubscription, createTeamMember, createTimecard, customAttributeText, deletePaymentLink, disableCard, ensureCustomer, findSubscriptionOffer, listCards, listCatalogDetailed, listCatalogItems, listCategories, listLocations, listModifierLists, listSubscriptionPlans, mapCatalogItem, ongoingPhase, orderSubtotal, pauseSubscription, planCoversItem, presentAt, priceAtLocation, publishInvoice, readModifyWriteCatalog, resumeSubscription, retrieveCatalogItem, retrieveCustomer, retrieveInventoryCounts, retrieveInvoice, retrieveLiveCatalogObjectIds, retrieveLocation, retrieveLoyaltyAccountByCustomer, retrieveLoyaltyProgram, retrieveOrder, retrievePayment, retrievePaymentLink, retrieveSubscription, retrieveTeamMember, retrieveTimecard, retrieveVariationPrices, retrieveVariationPricesAt, searchCustomersByEmail, searchOrders, searchOrdersByCustomer, searchSubscriptionsByCustomer, searchTeamMembers, searchTimecards, setPhysicalCount, squareApplicationIdEnvironment, squareWebhookEventSchema, subscriptionOffersFor, templatePhases, updateCustomer, updateLocation, updateSubscription, updateTeamMember, updateTimecard, upsertCatalogItem, verifySquareSignature };