npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

arky-sdk

v0.26.143

Published

Official TypeScript SDK for Arky - website backend for custom frontends

Readme

arky-sdk

Official TypeScript SDK for Arky. It gives a storefront everything it needs (products, carts, checkout with Stripe or Monri, sign-in, forms, bookings, orders, content), plus the Admin client for staff tools and scripts.

Install

npm install --save-exact arky-sdk@<version>

Pin the exact version, so the Server, Admin and storefronts move together.

Start here

| You are building | Call | Import from | |---|---|---| | A website or web app | initialize({ storeId, salesChannelId }, options): the client plus reactive atoms, a cart store per buyer, package and market, a headless checkout and a booking calendar | arky-sdk/storefront | | Server code, or your own state layer | createStorefront({ storeId, salesChannelId }, options): the plain storefront client, the same calls without atoms | arky-sdk/storefront | | Staff tools, scripts, back offices | createAdmin({ apiUrl, accountToken? }) | arky-sdk/admin | | A React app | createArkyReact<AdminClient>() or createArkyReact<StorefrontClient>(): TanStack Query options and keys for every call of that client (React) | arky-sdk/react |

arky-sdk/storefront exports everything a storefront needs: both clients, the helpers (prices, blocks, images, paging, payments, forms), the error classes and every type. arky-sdk/utils holds the helpers on their own, and arky-sdk/types the types with the error classes and constants.

How every call works

  • One params object, then request options. A call takes one object of Arky's own fields, then optional request options: signal, headers, onSuccess, onError, and on the storefront locale, market and order_token for that one request. Each client has its own type for them: the Admin client takes AdminRequestOptions, without locale, market and order_token, and the storefront StorefrontRequestOptions. A call with nothing to send, such as customer.getMe(), takes only the options. Admin calls that act on a store name its store_id.
  • One verb per kind of action. find… reads a list. get… reads one record or view: get({ id }), get({ slug }) where a record has slugs, getByKey({ key }). Records change through create, update and delete. A cart or a checkout changes through add…, remove…, set… (replace a value) and select… (pick one of the offered choices). Business actions keep their own names: quote, shipTo, checkout, place, submit, cancel, pause, requestCode, verify.
  • One casing rule. Arky's data is snake_case: params, answers, atoms and the helpers' results. The SDK's own setup options and callbacks are camelCase: apiUrl, createId, onComplete.
  • Every list answers a page. { items, cursor }, with cursor: null on the last page. Pass the cursor back to read the next page, or let readAllPages(read) collect them and paginate(read) walk them. A missing record is an ArkyApiError with status 404 and its record's own code, such as PRODUCT.NOT_FOUND (see Errors).
  • The app picks every id. A create takes the record's id, a canonical UUID v4 the app makes once per user action and sends again on every retry. The same request under the same id answers the stored record; a different request under it is refused (409). The SDK never makes an id up: storefront calls that leave the id out take it from your createId factory.
  • Changes carry the version they read. Updates and actions send expected_updated_at (the updated_at you read); a stale one is refused with 409. The cart store sends it for you. Stock actions and two conversation actions name what they read instead. A stock action names the stock level (its id, or expected_level_id on a movement or a unit receipt) and its action_id (a unit receipt names its new unit's id), and an adjustment names the count it corrects in expected_count (the level's on_hand, or its unavailable with from_set_aside). Assigning a conversation names the assignee you read (expected_account_id), and changing its reply email the selection you read (expected_reply). A value that moved is refused with 409 GENERAL.CONFLICT. A package's access row has no version, so its delete names only the row's id.
  • A cart keeps its market. A cart call names the cart's own market: another one is refused with 409 CART.OTHER_MARKET, so a cart kept from another market is read, or moved with an update whose market_id is the context's, before anything is added.
  • Plan access. A store without plan access refuses storefront changes with 402 STORE.SUBSCRIPTION_REQUIRED, an email change and the code request for it included; buyers can still identify, sign in with a code, sign out, read and edit their profile, and read what they hold.
  • Context is explicit. Storefront requests carry X-Arky-Store-Id and X-Arky-Sales-Channel-Id, plus the locale and the market you set with setContext({ locale, market }). A call names the package it reads, and the company or one of its locations it acts for, never both. Every commercial call (packages, their items, products, bookings and carts) names its market, even when the named channel sells in one: without it Arky refuses with 409 SALES_CHANNEL.MARKET_REQUIRED, and a market the channel doesn't sell in with SALES_CHANNEL.MARKET_NOT_LISTED. A request through an archived sales channel of the store is refused with 409 SALES_CHANNEL.NOT_ACTIVE, which leaves the shopper's session as it is. Content reads need no market. A locale outside the store's languages is refused with STORE.LANGUAGE_NOT_SUPPORTED.
  • Errors carry a code. Everything the SDK throws at runtime is an ArkyError with a code that you map to your own text. A TypeError means your code passed a wrong value. See Errors.

1. Set up the store

import { createOrderToken, initialize } from "arky-sdk/storefront";

const arky = initialize({ storeId: "5e9b3d71-c826-4a04-b7f5-0d2a8e6c4f19", salesChannelId: "e5a8c2d7-3b91-4f06-9d4e-1c7b6a0f3e28" }, {
  locale: "en",
  market: "eu",
  createVisitorIdentity: () => ({ customer_id: crypto.randomUUID(), session_id: crypto.randomUUID() }),
  createSessionId: () => crypto.randomUUID(),
  createId: () => crypto.randomUUID(),
  createOrderToken,
});

const setup = await arky.store.load();
const packages = await arky.eshop.package.find();
const shopPackage = packages.find((candidate) => candidate.key === "public");
console.log(setup.name, setup.languages, arky.currency.get(), shopPackage?.id);
  • The four factories are required. The app picks every customer, session and record id and every order token; createOrderToken makes a token in the shape Arky accepts. Without them initialize throws.
  • apiUrl defaults to https://api.arky.io. The store and sales-channel IDs are required canonical UUID v4 values. They are public identifiers and authenticate no person.
  • Sessions are kept in localStorage, separately for each API URL, store and sales channel. During server rendering, pass a request-local sessionStorage adapter. visitorIdentity restores a visitor pair your app picked earlier.
  • arky.store.load() reads the store's setup and the current market and fills the setup, market and currency atoms; the market's payment_option_ids lists its payment options, and each quote's payment_option_ids lists the ones that can pay that cart. The client reads each market once: arky.client.store.market.getCurrent() answers the current one from the same read. arky.getSetup() only answers the setup: name, timezone, languages, payment_options, customer_sign_in, which is { type: "store" } when the store signs its own customers in, or { type: "network", network_id } when they sign in through the network (Network customer sign-in), and seller, which is { type: "seller", name, address } with the store's legal name and postal address, or { type: "none" }. The setup is read once per client. A 409 PAYMENT_METHOD.TERMS_CHANGED refusal (the store changed an option's saved-card wording) drops it, so the next getSetup() or store.load() reads the new wording.
  • Packages. A package is a set of things you can buy, get or rent; a shop is a package with priced items. eshop.package.find() lists the packages open to this buyer in the current market and sales channel as a plain array, each with its blocks (its name and texts) and its access level. Pick yours by its key; every item, product, booking and cart call names its package_id. package is a reserved word in strict TypeScript, so a local holding one is shopPackage or memberPackage; properties such as eshop.package are fine.
  • setContext({ locale, market }) changes the language or the market. A market change clears every cart view; each market keeps its own carts and its own cart store, and switching back reads them again.

The store has the same calls as the plain client, under the same names. On top of them it has atoms (session, setup, market, currency, locale, …) and three helpers, each for one buyer and package in the current market: eshop.cart(scope), eshop.checkoutFlow(scope) and eshop.bookingCalendar(scope). The plain client's own cart calls stay reachable at arky.client.eshop.cart.

2. Products

A package sells products, booking services and packages through its priced items. eshop.packageItem.find pages them, one answer per priced item in the current market:

import { findBlock, formatMinor, getBlockTextValue, getImageUrl } from "arky-sdk/storefront";
import type { Media, StorefrontPackageItem } from "arky-sdk/storefront";

const page = await arky.eshop.packageItem.find({ package_id, include_price: true, selection: { types: ["product"] }, limit: 24 });
const imageIds = page.items.flatMap((item) => {
  const image = findBlock(item.content, "image");
  return image?.type === "media" && image.value ? [image.value] : [];
});
const images = await arky.media.find({ ids: imageIds });
const imageById = new Map<string, Media>(images.map((image) => [image.id, image]));

const rows = page.items.map((item: StorefrontPackageItem) => {
  const image = findBlock(item.content, "image");
  const summary = item.price_summary;
  return {
    name: getBlockTextValue(findBlock(item.content, "name"), "en"),
    image: image?.type === "media" && image.value ? getImageUrl(imageById.get(image.value), "medium") : null,
    from: summary && item.currency ? formatMinor(summary.min_amount, item.currency, "en") : "",
    href: `/products/${item.content.slugs.en}`,
  };
});
console.log(rows, page.cursor);
  • One search for every priced item. An answer names its package_item_id, package_id and market_id, what it lists (item), its position and the listed record's content (key, slugs, blocks, categories). selection narrows and orders the answers:
    • types (product, booking_service, package), text, categories (for products and booking services) and block filters blocks on the listed record;
    • price: { min_amount?, max_amount? } and price_basis (product_unit, booking_option, package_never or package_every with its cadence). Every price of one item has the same basis, so an item matches when its basis is the one asked for and its lowest to highest price overlaps the range. Search is per item, not per variant: a storefront that needs one variant filters its own read of the item's prices;
    • sort: package_order (the default) or starting_price (needs price_basis), and direction, asc unless you ask for desc. text matches words and word starts of an item's text, or the listed record's exact key, and keeps the order you ask for.
  • Prices in search. With include_price: true and an access level that shows prices, an answer has its currency and price_summary, { basis, min_amount, max_amount, price_count } over the item's prices on sale. A package's item holds exactly one price, and its answer names it as price_id.
  • Pages. A page holds 20 answers unless you ask for more, and a page can come back short with a cursor: follow it.
  • Media. media.find({ ids }) takes any number of ids, reads them 100 at a time and answers a plain array, and an answer that isn't a list or names a file it didn't ask for is refused (ArkyError answer_mismatch); content.load and loadEntries read their media through it. Storefront reads answer Public files, with their URL at content.original.url. Images also come as thumbnail, small, medium and large, and getImageUrl(media, size) picks one. Private files have null metadata URLs and getImageUrl returns null for them.
  • Texts are blocks. findBlock(record, key) finds a block and getBlockTextValue(block, locale) reads its text in the language you name, never another; an empty string means there is none.

A product page reads the product by its slug in the current language, then the prices of its item:

const product = await arky.eshop.product.get({ slug: "classic", package_id });
const { items: choices } = await arky.eshop.packageItem.findPrices({ package_item_id: product.package_item_id, package_id, include_price: true });
const byKey = await arky.eshop.product.getByKey({ key: "classic-x1", package_id });
console.log(choices.map((choice) => [choice.price_id, choice.content.sku, choice.price?.unit_price.amount]), byKey.id);
  • Reads. get takes { id } or { slug }; a key is read with getByKey({ key }). Both answer the product with the package_item_id of its item in that package and the current market. Booking services and categories read the same way; collections, forms, markets, packages and their offerings read by { id } or with getByKey({ key }).
  • Prices. packageItem.findPrices({ package_item_id }) pages an item's prices, its exact choices. Each names its price_id, the sellable it prices (a product_variant, booking_offering or package), its content (sku, blocks and the price basis) and, with include_price: true, its price, which carries the full reference (package_id, package_item_id, price_id) a cart line names.
  • More reads. packageItem.getByParent({ item: { type: "product", product_id } }) reads the item of a record in the current market, productVariant.get({ product_id, id }) reads one variant, with its price when you pass include_price: true, and product.findByIds({ ids, package_id }) reads up to 100 products in one request, answering { items, cursor: null } with the ones the package sells now, in the order asked. Staff read up to 100 variants with eshop.productVariant.find({ store_id, ids }), which takes no other filter, sort or page.

3. Cart

arky.eshop.cart({ buyer, package_id }) answers the cart store of that buyer and package in the current market: the same store on every call, shared with the checkout flow and the booking calendar of the same scope. A shopper who switches market gets that market's cart store. A store kept from before the switch refuses its next call with CartError context_changed. Storefront cart reads answer the buyer's copy of the cart, StorefrontCart, and the line helpers take it. Its quote is the buyer's copy too, StorefrontCartQuote: a package line's package leaves out each item's allocation weight, and its start leaves out the reason the store team wrote for an amendment.

const cart = arky.eshop.cart({ buyer: { type: "customer" }, package_id });
cart.item_count.subscribe((count) => console.log("items", count));
cart.status.subscribe((status) => console.log(status.error?.code));

await cart.ensure();
await cart.addProduct({ variant_id, quantity: 1, price: { package_id, package_item_id, price_id } });
const [line] = cart.product_items.get();
if (line) {
  await cart.setProductQuantity({ line_item_id: line.id, quantity: 2 });
  await cart.removeItem({ line_item_id: line.id });
}
  • Atoms:
    • cart, product_items, booking_items, package_items, item_count (product units, one per booking line, and each package line's quantity);
    • quote_result and promotion_codes, where promotion_codes holds every code the quote lists, each with its state: applied, stopped (a promotion ahead of it stopped the ones after it) or not_applied (it takes nothing off this cart);
    • status: loading, syncing, fetching_quote, processing_checkout, error and quote_error, where an error is { code, message }.
  • Reads: ensure() loads the cart this browser selected for the buyer, package and market, or creates one under an id from createId, kept across a lost answer. load() only loads; create({ id?, place_of_sale? }) only creates. A store whose branches issue fiscal receipts names the cart's place of sale, { type: "store_location", store_location_id } or { type: "none" }, when it creates the cart or later with setPlaceOfSale({ place_of_sale }). With no session, load() answers null and sends nothing, so a visitor who only browses never becomes a Customer; the first write identifies the visitor. A selected cart that now names another buyer, package or market ends the selection: another buyer or package is refused once with CartError other_cart, another market reads as no cart.
  • Changes: each answers the changed cart and sends the cart id and version for you. Line ids come from createId when you leave them out.
    • lines: addProduct, addBooking, addPackage, setProductQuantity({ line_item_id, quantity }), removeItem({ line_item_id }), clear();
    • checkout details: shipTo({ destination, contact_email? }), setDeliveryGroups({ delivery_groups }), selectShippingMethod({ shipping_method_id }), setBillingAddress({ billing_address }), setBuyer({ buyer }) (a company buyer's purchase_order_number; the buyer stays the one this cart store is for, else CartError not_ready), setPlaceOfSale({ place_of_sale }), setPromotionCodes({ promotion_codes }), which replaces the whole list, so pass the codes you keep plus the new one;
    • package deliveries: setFutureDeliveries({ packages }) and quoteFutureDeliveries({ packages }).
  • Quote and checkout: quote({ contact_email? }), checkout(...), retainCheckout(...), pendingCheckout() and recoverCheckout(). checkout and recoverCheckout answer the placed order; the cart store keeps no copy of it. Most pages use the checkout flow instead.
  • After a failed write: a write whose answer is lost, or that is refused because the cart changed (409), drops the view: cart and quote_result turn null, and the next ensure() reads the current cart. reset() drops the view by hand; clear() empties the cart in Arky. A change made while another change to the same cart is still being sent is refused with CartError busy before anything is sent, and the view keeps the first change's answer.
  • Prices. Every line names the exact price it is bought at, price: { package_id, package_item_id, price_id }, one of its item's prices read with packageItem.findPrices, so product, booking and package lines name it the same way. A cart is priced from its own package only: a club's prices are the products the club package lists, bought in a cart of that package, and money off for its members in another shop is a promotion with a package condition.

A cart line names its variant. To show names, quote the cart and read its products:

import { findBlock, getBlockTextValue } from "arky-sdk/storefront";

const cart = arky.eshop.cart({ buyer: { type: "customer" }, package_id });
await cart.ensure();
const quote = await cart.quote();
console.log(quote.lines.map((line) => (line.type === "product" ? getBlockTextValue(findBlock(line.product, "name"), "en") : line.type)), quote.totals.total);

The quote is in the store's locale, and each product line's snapshot keeps the variant's variant_sku and variant_blocks as they were quoted. A product line's compare_at is its price's comparison amount, or null when the price has none. A product line also names its product ({ id, key, blocks }) and its variant's shipping_profile_id (null when the variant doesn't ship), so a page names the line and shipTo groups shipped lines by profile without reading any variant. The cart's own product lines answer their product_id, which a cart update never sends back. A delivery's money is { price, discounts, tax }, where only a delivery's tax may be follow_goods. quote.ready is false while quote.blockers lists what is missing: a delivery, a shipping choice, a billing address, a taken booking slot, and so on. Each delivery's offers name their shipping method by shipping_method_key and shipping_method_blocks, so a page can show "Courier €45". A rate that needs a weight Arky doesn't know is left out of offers and listed in the delivery's unavailable with its code (SHIPPING.WEIGHT_UNKNOWN).

Arky works out every amount a page shows, so a page never adds up money itself:

  • Line totals. Each product, booking and package line has totals: { subtotal, discount, tax, total }, a booking line's for all its capacity_units and a package line's the sum of its items, each of which (get_product, rent_product) has its own totals. total is subtotal - discount + tax in a tax-exclusive market and subtotal - discount in an inclusive one.
  • Delivery totals. Each delivery has totals in the same shape, null until its shipping is chosen. The quote's totals are the sums of the line and delivery totals, so the parts always add up to totals.total.
  • One shipping method for the whole cart. shipping_choices: [{ shipping_method_id, amount }] lists each method that serves every delivery, with the sum of its offers, which is what selectShippingMethod({ shipping_method_id }) sets before delivery promotions and tax.
  • Delivery estimates. A delivery's and an offer's delivery_estimate is { min, max } in business days, or null.

4. Checkout

arky.eshop.checkoutFlow({ buyer, package_id }) is a headless checkout for your own cart page: steps, state and errors, and no UI.

import { mountCheckoutAction } from "arky-sdk/storefront";

const checkout = arky.eshop.checkoutFlow({ buyer: { type: "customer" }, package_id });
checkout.state.subscribe((state) => console.log(state.step, state.error?.code));

let state = await checkout.open();
checkout.setContact({ contact_email: { email: "[email protected]", language: "en" } });
state = await checkout.shipTo({ destination: { type: "delivery", address } });
for (const delivery of state.quote?.deliveries ?? []) {
  const [offer] = delivery.offers;
  if (offer) {
    state = await checkout.selectShipping({
      delivery_group_id: delivery.delivery_group_id,
      shipping_method_id: offer.shipping_method_id,
      rate_id: offer.rate_id,
    });
  }
}
if (state.step === "payment") state = await checkout.place({ return_url: (orderId) => `${location.origin}/order?order_id=${orderId}` });

const placed = state.placed;
if (placed && placed.payment_action.type !== "none") {
  await mountCheckoutAction({ action: placed.payment_action, payment_id: placed.payment_id, element: "#payment" });
}
  • Steps. state.step is one of:
    • cart: no lines, a line that can't be bought as it is (a taken booking slot, a price that can't hold its fixed per-unit fee: tax_unavailable, a package that would put the buyer under a second purchase minimum: package_minimum_conflict, or a switch or amend line whose change Arky refuses: package_change_refused, with that refusal's code), or a cart that needs a payment none of the market's payment options can take (payment_unavailable, with the reason's code), named in quote.blockers. A package change keeps its membership, so its new minimum never counts as a second one. While one of the buyer's memberships has a package change waiting, a line for a package of the offering that change moves into is blocked with package_change_scheduled, and placing it is refused with PACKAGE_MEMBER.CHANGE_SCHEDULED;
    • details: the contact email, an address, the billing address, a purchase order number or the place of sale is missing (place_of_sale_required: set it with setPlaceOfSale), the chosen branch doesn't sell now (place_of_sale_not_active), a company buyer at a place whose fiscal system is TaxCore has no verified tax ID for that country that TaxCore takes (fiscal_buyer_tax_id_required), a package line still needs a delivery (package_delivery_required, a renewing switch line's new shipping profile included), or a delivery no longer fits its lines (delivery_unavailable: set it again with shipTo);
    • shipping: a delivery needs its shipping choice;
    • payment: ready to place;
    • paying: the order waits for its payment, or a kept checkout waits for recover();
    • placed: paid, to pay later (cash on delivery), unconfirmed (the provider's answer needs checking) or free.
    • Every blocker kind has its step; a kind this SDK doesn't know yet holds the cart step.
  • State: the cart, the quote with its blockers, contact_email, contact_name ({ first_name, last_name } or null), destination (read from the cart's delivery), billing_address, the chosen payment_option_id (the quote's suggestion until you pick one), the pending request, the placed order with its payment_method_id and payment_method_setup (set when placing saves a card), its payment and outcome, busy and error.
  • Steps you call. Each step that reads or writes Arky answers the new state. setContact and selectPaymentOption only change the state.
    • open() and refresh() (quote again);
    • setContact({ contact_email: { email, language }, contact_name? }), shipTo({ destination }), setPlaceOfSale({ place_of_sale }), setBillingAddress({ billing_address });
    • selectShipping({ delivery_group_id, shipping_method_id, rate_id }) and selectPaymentOption({ payment_option_id });
    • setPromotionCodes({ promotion_codes });
    • place({ return_url?, save_payment_method?, payment_method_terms? });
    • reset() leaves placed or paying and keeps the contact, for a buyer who keeps shopping on the same page. open() drops a finished order by itself and keeps one still waiting for its payment.
  • Contact. The order's contact is an email with the language its emails are written in, plus an optional contact_name with both first_name and last_name that the SDK never fills in. open() names no contact: the page sets it with setContact from its own field, the billing address or the session, in the page language, and the flow stays on details until then. Each setContact states the whole contact, so a name it leaves out is cleared. After setContact, every quote sends the email, so a guest can use a promotion code limited to one use per customer. A company buyer's purchase order number is set with checkout.cart.setBuyer({ buyer }).
  • Placing. place pays with one of the quote's payment options, or places a free order at a zero total. The quote's payment_option_ids lists only the options that can pay this cart, so pick from it as it is. A paid package is paid by card at checkout: a cart with a package line that charges money or saves a card lists only card options, and Arky refuses cash on delivery and manual options for it with CART.CARD_REQUIRED. When the cart needs a payment and no option can take it, the quote shows payment_unavailable with the reason's code (CART.CARD_REQUIRED, CART.DEDICATED_SETUP_NEEDS_STRIPE, PAYMENT_METHOD.TERMS_UNAVAILABLE or CART.PAYMENT_OPTION_UNAVAILABLE), and checkout answers that code. When a package line's saves_card in the quote is true, the order saves the buyer's card: place({ payment_method_terms }) passes the card wording the buyer accepted, the flow sends save_payment_method: { type: "save", terms }, and place without that wording, or with save_payment_method: false, is refused with not_ready before anything is sent. Without such a line the flow sends { type: "dont_save" } unless the page passes save_payment_method: true with the wording. At a zero total a saved card sends the selected payment option instead of a free order, and Arky saves the card a renewing package needs through Stripe's setup; the quote then lists only Stripe options with saved-card wording in its language. Pass state.placed.payment_method_setup to mountPaymentMethodSetup({ setup, element }), confirm it, then call eshop.paymentMethod.completeSetup({ id: state.placed.payment_method_id }). Arky refuses that place with CART.NOTHING_DUE when no line saves a card. A Monri store can't take such a cart, because Arky saves a Monri card only from a paid checkout: its quote shows payment_unavailable with CART.DEDICATED_SETUP_NEEDS_STRIPE.
  • On account. A company buyer with on-account terms checks out through the cart store instead: checkout.cart.checkout({ contact_email: { email, language }, payment: { type: "on_account", payment_option_id } }). A cart with a package line that charges money or saves a card is never put on account (CART.ON_ACCOUNT_PAID_PACKAGE). A store that sells a membership paid by invoice sells a product and, once it is paid, gives the package through a zero-price order, or assigns it when the package needs no order.
  • After placing: recover() finishes a kept checkout, resumePayment() reopens the order's checkout payment page while its payment window is open, refreshPayment() reads the payment again, and openOrder({ order_id, url }) reopens an order after a payment redirect. openOrder answers { state, url }, where url is the link without its order token.
  • Errors: every step throws a CheckoutFlowError and records { code, message } in state.error. The codes are:
    • busy (a step is already running), not_ready and pending (recover the kept checkout first);
    • presentation_changed: the state then shows the new quote, which the buyer reviews before placing again;
    • refused, interrupted (try again or recover()), unavailable (no browser storage or lock) and failed.

Paying with Stripe or Monri

mountCheckoutAction({ action, payment_id, element, onComplete?, onValidationError? }) mounts the payment form into element (a selector or an element). It answers what it mounted, or null when the order has nothing to pay:

  • Stripe mounts Stripe's embedded Checkout. onComplete runs when Stripe reports the payment done; call checkout.refreshPayment() then, or read the order page after the return_url redirect.
  • Monri mounts Monri's card form. It needs the payment_id and the buyer's billing details, so call the mount's confirm from your pay button. onValidationError gets a MonriCheckoutError with code invalid_card while the card details are wrong, and null when they are fine.
import { mountCheckoutAction, MonriCheckoutError } from "arky-sdk/storefront";

const placed = arky.eshop.checkoutFlow({ buyer: { type: "customer" }, package_id }).state.get().placed;
if (placed && placed.payment_action.type === "monri_components") {
  const mount = await mountCheckoutAction({ action: placed.payment_action, payment_id: placed.payment_id, element: "#payment" });
  if (mount?.type === "monri_components") {
    try {
      await mount.confirm({
        full_name: "Ana Horvat",
        address: "Main Street 1",
        city: "Zagreb",
        zip: "10000",
        phone: "+385 1 234 567",
        country: "HR",
        email: "[email protected]",
      });
    } catch (error) {
      if (!(error instanceof MonriCheckoutError)) throw error;
      console.log(error.code);
    }
  }
}

A MonriCheckoutError says what went wrong:

  • invalid_details lets the buyer correct the form;
  • unknown_result means the payment needs checking, so never start a second checkout;
  • already_submitted, invalid_action and unavailable (Monri needs an HTTPS page).

Saved cards use eshop.paymentMethod.requestSetup, startSetup, mountPaymentMethodSetup({ setup, element }) and its confirm({ return_url }), then completeSetup, which answers the card as Arky holds it without asking Stripe; Stripe's own setup post is what makes it ready. A Monri option refuses this setup (PAYMENT_METHOD.DEDICATED_SETUP_NEEDS_STRIPE), because Arky saves a Monri card only from a paid checkout.

A membership replaces its card by saving a new one and selecting it: eshop.packageMember.selectPaymentMethod({ id, expected_updated_at, payment_method_id }) charges any renewal that's owed, and resume then restarts a blocked membership. A Stripe card is saved with the setup above. A Monri membership's buyer places a paid checkout under the Monri option with place({ save_payment_method: true, payment_method_terms }) and, once its payment succeeds, selects state.placed.payment_method_id. Arky has no payment page for an owed renewal order.

Each checkout action and card setup carries runs_on, which says where the payment runs: { type: "provider" }, or { type: "simulator", api_url } on a test store. These two mounts handle both, so the same site code works on a test store and a live one. A network's store-billing card setup also works with mountPaymentMethodSetup. On a test store the mount draws a test payment form in the page's own words: pass simulator_texts: { title, description, complete, decline, expire, cancel } to mountCheckoutAction and mountPaymentMethodSetup. A simulated payment mounted without them is refused with ArkyError not_ready; a live payment ignores them.

5. Order page

An order email links to the order with a #order_token=... fragment, so a guest can open it in any browser:

import { latestPayment, paymentAmounts, paymentOutcome } from "arky-sdk/storefront";

const opened = await arky.eshop.order.fromLink({ id: orderId, url: location.href });
history.replaceState(history.state, "", opened.url);

const payments = await arky.eshop.order.findPayments({ order_id: opened.order.id }, { order_token: opened.order_token });
const latest = latestPayment(payments);
console.log(opened.order.number, latest ? paymentOutcome(latest) : null, paymentAmounts(payments).net_paid);
  • order.fromLink({ id, url }) checks the token, reads the order with it, keeps the token for that order and answers { order, url, order_token }, where url is the link without the token. A link without a token uses the token kept at checkout, or the customer's session. A malformed token is an ArkyError with code invalid_link.
  • Tokens are sent only when you pass them. Order reads send a token only as the request option { order_token }. The order, its payments and fulfillments, resumePayment, downloadAsset, cancellations, reschedules and returns accept it. order.retainedToken({ order_id }) answers the kept one. Keep payment provider return URLs free of the token.
  • paymentOutcome(payment) says what a payment means to the shopper: paid, awaiting, unconfirmed (the provider's answer is unclear and the team settles it, so tell the shopper you will email them) or failed. latestPayment(payments) picks the newest.
  • paymentAmounts(payments) adds up an order's payments (StorefrontPayment[]) as Arky does: paid, refunded, refund_pending, disputed and net_paid. disputed nets each reinstatement against its withdrawal, and counts a withdrawal Stripe reports in another currency as the dispute's own amount. It leaves out what is still owed, because that also subtracts the order's credits, which a storefront doesn't read.
  • Buyer's copies. Storefront order, payment and return reads answer the buyer's copies (StorefrontOrder, StorefrontPayment, StorefrontReturn), which leave out what only the store team sees, such as who recorded a payment; paymentOutcome, paymentAmounts and the line helpers take them.
  • Invoices. A storefront order carries light copies { id, type, created_at }. An unissued_invoice names its reason: awaiting_outside_number, awaiting_receipts, counter_held or blocked. Issued invoice and reversed_invoice copies carry their number and issue time; credit_note and reversal also name the invoice they correct. outside_invoice and outside_credit_note carry the merchant’s number and document ({ type: "link", url } with an HTTPS URL or { type: "paper" }), and an outside credit note names its credited invoice_id. eshop.order.getInvoice({ order_id, invoice_id }) reads a full document with the same Order access. Arky documents hold frozen seller, buyer, lines and totals; fiscal_receipts names their pending or numbered receipts. Payments belong to the Order.
  • Receipts. A storefront order carries its fiscal receipts, oldest first, as light copies { id, type, document, created_at }. type is sale, advance, next_advance, advance_settle, advance_return, advance_correction, final, refund, correction or copy, and document names the fiscal system with the receipt's state: tax_core (done with its invoice_number and verification_url), fbih_printer (done with its receipt_number) or croatia_cis with its number (done with its jir). A tax_core receipt issued on another device is done_on_other_device with its invoice_number. An fbih_printer receipt written by hand is written_by_hand with its hand_number, then printing_after_hand and done_after_hand with the printed receipt_number, or print_failed_after_hand while the print waits for staff; one issued on another device is done_on_other_device with its receipt_number, a string.

To order again, reorder({ id, order_id, buyer, package_id }) builds a new cart from the products the order bought directly, in the package you name (normally the buyer's current one) and the current market, at that package's prices there, with the same access as creating a cart there. The buyer is the order's own (CART.REORDER_BUYER). A product that package doesn't sell in that market, or that can't be bought now, is left out and listed in left_out; when nothing is left, Arky refuses with CART.REORDER_NOTHING_LEFT. The new cart becomes this browser's cart for that buyer, package and market, so the cart store's load() reads it:

const reordered = await arky.client.eshop.cart.reorder({
  id: crypto.randomUUID(),
  order_id: orderId,
  buyer: { type: "customer" },
  package_id,
});
const cart = await arky.eshop.cart({ buyer: { type: "customer" }, package_id }).load();
console.log(cart?.id === reordered.cart.cart.id, reordered.left_out.map((line) => line.variant_id));

6. Customer sign-in

arky.session.subscribe((session) => console.log(session?.type));

await arky.customer.requestCode({ contact: { type: "email", email: "[email protected]", language: "en" } });
await arky.customer.verify({ code: "123456" });
const me = await arky.customer.getMe();
if (me) {
  await arky.customer.updateMe({
    expected_updated_at: me.customer.updated_at,
    profile: [{ id: crypto.randomUUID(), key: "first_name", type: "text", value: "Ana" }],
  });
}
const { items: orders } = await arky.eshop.order.find({ limit: 20 });
console.log(orders.length);
const signedOut = await arky.customer.logout();
console.log(signedOut.type);
  • Visitors, customers and contacts. A visitor signs in with a code sent to an email or a phone number, in a store that signs its own customers in: a store of an Isolated network, or any test store. requestCode({ contact }) takes { type: "email", email, language } or { type: "phone", number, language } (E.164, such as +38761234567) and sends the code by email or SMS in that language, one of the store's languages. The code message's id comes from createId; a lost answer is retried under the same id, so the customer gets one message. The accepted code signs in to the store's own account for that address: a code for an address whose account is already linked to a customer of the store signs the visitor in to that customer, and otherwise the visitor's own customer is linked to the account. Either way the address becomes a confirmed contact. A customer's contacts are where the store writes to the person, each unconfirmed_email or unconfirmed_phone (typed in, not proved) or confirmed_email or confirmed_phone (the person proved it); they never sign anyone in, and several customers may hold one address. Its links show { type: "own" } for each account that signs in to it, never the account. A store of a Connected network refuses its own customer codes with 409 CUSTOMER_SIGN_IN.NETWORK_SIGN_IN: its customers sign in through the network (Network customer sign-in).
  • verify signs the customer in under a new session id from createSessionId. Its session is store_customer_signed_in_by_email with the email or store_customer_signed_in_by_phone with the number it signed in with, and the client's session.signed_in_with names that address. When the visitor signs in as a customer who already exists, Arky merges the visitor's cart into that customer's cart, and the cart store follows it. A staff invite's message gives its template code, email or number, and code_days; the page its link opens passes them back as verify({ code, email }) or verify({ code, number }). An invite opens only with its own code.
  • Sign-in refusals carry their own codes: CUSTOMER_SIGN_IN.CODE_RECENT (a new code within the configured interval, sixty seconds in production), CUSTOMER_SIGN_IN.CODE_INVALID (a wrong or expired code, or none waiting) and CUSTOMER_SIGN_IN.ATTEMPTS_EXHAUSTED (too many wrong codes for the address).
  • No session, no visitor. With no session, getMe() answers null and sends nothing, as eshop.cart.getCurrent and a cart store's load() do. The first write, such as a code request, a cart or a form submission, identifies the visitor.
  • Signing out. logout() forgets the session in this browser and answers { type: "revoked", session_id } when Arky confirmed it, { type: "unconfirmed", session_id } when the request failed, so an earlier copy of the session may still work until it expires, or { type: "local_only" } when there was no session.
  • Session lifetime. A signed-in session's access token lasts an hour; the SDK refreshes it on the first 401 and keeps every cart and checkout view. Every tab of a browser uses the one stored session: the SDK reads it for each request, refreshes it in one tab at a time under a Web Lock, uses a session another tab already refreshed instead of refreshing again, and reports a session another tab changed to onAuthStateChanged. A browser without Web Locks refuses the refresh with ArkyError storage. A browser that refuses storage keeps the session in that tab only, and the client's sessionStorageUnavailable is then true, so the site can tell the shopper that other tabs won't share the sign-in. Only Arky's own refusal of that refresh (401 GENERAL.UNAUTHENTICATED or 403 GENERAL.UNAUTHORIZED in Arky's error body) clears the session and reports it to onAuthStateChanged and the session atom. Any other failed refresh, such as a 401 or 403 from a proxy, a 429 or a 5xx, fails that request with the refresh's error and keeps the session for the next try. A refresh whose answer was lost after Arky made the new session has already replaced the old one, so the next refresh is refused and the shopper signs in again. A visitor whose token Arky itself refuses (401 GENERAL.UNAUTHENTICATED in Arky's error body, for example after the visitor session expired) is replaced: the SDK identifies a new visitor and sends the request once more. Any other 401, such as a proxy's, fails that request and keeps the visitor. Changing the shopper, signing out or switching markets clears checkout contact, delivery, payment selection and the displayed order. A late response from the previous context cannot restore them; a kept checkout request stays in the browser for explicit recovery by the customer who kept it, and another customer signed in on the same browser neither sees it nor is blocked by it.
  • Contacts. On a signed-in session, requestCode sends a code to another email or number, and verifyContact({ address, code }) confirms it as a contact and adds it to the person's sign-in, where address is { type: "email", email } or { type: "phone", number }. addContact({ expected_updated_at, contact, sms }) saves an unconfirmed contact, updateContact({ expected_updated_at, address, language, sms }) changes the language its messages are written in or a phone's SMS consent, and removeContact({ expected_updated_at, address }) removes it; removing a contact never ends a sign-in. A customer holds each address once (CUSTOMER_CONTACT.EXISTS) and at most the configured number of contacts (CUSTOMER_CONTACT.LIMIT). unsubscribe({ address }) and resubscribe({ address }) record one email's choice. Each answer is CustomerMe, { customer, session }, and the stored session takes its customer at once. removeLink() removes the signed-in customer's own link, ends this browser's session and answers { removed: true }; a customer's last link stays while it owns a saved card or holds a company membership (CUSTOMER_LINK.LAST_LINK).
  • A visitor fills in its own record. A visitor that never signs in uses getMe, updateMe, addContact, updateContact and removeContact too, so a booking page saves the person's name, phone and SMS consent without a sign-in. Only a code confirms an address: a visitor's contacts stay unconfirmed until requestCode and verify sign it in.
  • Name and SMS consent. A customer's updateMe, a visitor's included, also takes name ({ first_name, last_name }, null to clear). Each phone contact holds its own SMS consent: sms: "on" records the customer's own yes for that number only, a number starts with SMS off unless the save that adds it turns it on, and the read shows sms as { type: "off" } or { type: "on", at }. The store team's customer read answers { type: "off", at }, when the number's SMS became off, or { type: "on", at, by }.

Network customer sign-in

In a Connected network, a customer signs in once through the network and opens a key at each store they use:

import { createNetworkCustomer } from "arky-sdk/storefront";

const network = createNetworkCustomer({ apiUrl: "https://api.arky.io", networkId: "0f6a3c84-2d19-4e75-b8a1-5c9e7d3b2f60" });
const session_id = crypto.randomUUID();
await network.requestCode({ session_id, reach: { type: "network" }, contact: { type: "email", email: "[email protected]", language: "en" } });
await network.verify({ session_id, code: "123456" });
const { items: stores } = await network.store.find();
const key = await network.store.openKey({ store_id: stores[0].store_id, id: crypto.randomUUID(), visitor_token: arky.customer.visitorToken });
arky.customer.useStoreKey(key);
  • Reach. { type: "network" } is the network's own portal: it opens every store the person uses and may change the person's logins. { type: "store", store_id } is one store's own page: it reaches that store only (403 NETWORK_CUSTOMER_SIGN_IN.STORE_NOT_REACHED at another) and never changes logins (409 ACCOUNT_LOGIN.NETWORK_REACH_REQUIRED). An Isolated network refuses the network sign-in (409 NETWORK_CUSTOMER_SIGN_IN.NOT_CONNECTED), and so does a test store (409 NETWORK_CUSTOMER_SIGN_IN.TEST_STORE).
  • The code. requestCode({ session_id, reach, contact }) answers { session_id, code_expires_at } alike for every address and sends the code through the network's own Resend or Twilio login, with its customer texts in the contact's language (409 NETWORK.CUSTOMER_TEXT_MISSING without one, NETWORK.RESEND_MISSING or NETWORK.TWILIO_MISSING without the login). The same session_id and contact while the code is open answer the same pending sign-in. NETWORK_CUSTOMER_SIGN_IN.CODES_BUSY means the network's code budget is spent for now, and NETWORK_CUSTOMER_SIGN_IN.CODE_RECENT that a code to that address went out moments ago. verify({ session_id, code }) keeps the sign-in in this browser; a wrong, expired or replaced code answers NETWORK_CUSTOMER_SIGN_IN.CODE_INVALID, too many NETWORK_CUSTOMER_SIGN_IN.ATTEMPTS_EXHAUSTED.
  • Store keys. A network sign-in never acts in a store itself. store.openKey({ store_id, id, visitor_token }) opens that store's key for the customer linked to the person there, else for the visitor whose visitor_token it passes (arky.customer.visitorToken, or null), else for a new customer, and the sign-in's address becomes a confirmed contact there. arky.customer.useStoreKey(key) makes the key the storefront client's session, so every storefront call works as for any signed-in customer. A key lives as long as its sign-in and has no refresh token: when Arky refuses it, the storefront client forgets it and identifies a new visitor. A key the store revoked can't be opened again by the same sign-in (409 NETWORK_CUSTOMER_SIGN_IN.KEY_REVOKED). store.acceptInvite({ store_id, id, code, sent_to }) redeems that store's invite inside a sign-in with reach { type: "store", store_id } and answers its key the same way, opened under the app-picked id: the same id again answers that key, so a lost answer is sent again as it was, and an id that names another record is refused with 409.
  • The person's account. getMe() answers { account_id, logins, session }: the customer logins (customer_email and customer_phone) and this sign-in's reach and signed_in_with. With reach network, login.requestCode({ contact }), login.verify({ address, code, confirm_join }) and login.remove({ address }) change the logins, and every change tells the person's other logins. An address that belongs to another account of the network answers 409 ACCOUNT_LOGIN.JOIN_CONFIRMATION_REQUIRED and joins that account only with confirm_join: true; ACCOUNT_LOGIN.JOIN_LINKED_APART names a store where both are linked to different customers, which merges them first. The other refusals are ACCOUNT_LOGIN.TAKEN, ACCOUNT_LOGIN.LIMIT, ACCOUNT_LOGIN.LAST_LOGIN, ACCOUNT_LOGIN.EMAIL_SESSION_REQUIRED (adding an email needs a sign-in with an email the account holds) and ACCOUNT_LOGIN.OLDER_EMAIL_REQUIRED. store.find() lists the stores the person is linked to, store.removeLink({ store_id }) removes the person's own link there, and deleteAccount() deletes the account through a sign-in with its oldest email (409 ACCOUNT.ANCHOR_SESSION_REQUIRED), or answers 409 ACCOUNT.MEMBER_SESSION_REQUIRED for an account with memberships, which only its own member session deletes. A delete that would take a store customer's last link while that customer's saved card or company membership needs it answers 409 CUSTOMER_LINK.LAST_LINK, as every account delete does.
  • Session. The client sends the network_customer_access_ token, refreshes once when Arky refuses it, and forgets the sign-in when Arky refuses the refresh. Its session is { id, reach }, onAuthStateChanged reports changes, and logout() answers { type: "ended", session_id }, { type: "unconfirmed", session_id } or { type: "local_only" }.

7. Forms

import { FormAnswerError } from "arky-sdk/storefront";

const form = await arky.forms.getByKey({ key: "contact" });

try {
  await arky.forms.submit({ form, values: { email: "[email protected]", message: "Hello" }, language: "en" });
} catch (error) {
  if (error instanceof FormAnswerError) console.log(error.questionKey, error.code);
  else throw error;
}
  • Submitting. forms.submit takes the loaded form and a { key: value } map, checks each value against its question and builds the answers. You can also pass form_id, questions_updated_at and answers that you built yourself.
  • Answer errors. A value that doesn't fit throws a FormAnswerError with the question's key and a code: required, invalid, too_short, too_long, pattern_mismatch, too_small, too_large, unknown_option, too_many_files (more than the question's max_files), file_size (an empty file), file_name or unknown_question.
  • Lengths and patterns. Text lengths count characters as Arky does, so an emoji counts once. A question's pattern is checked before sending only where JavaScript reads it as Arky does: a pattern with \d, \w or \b (Unicode classes in Arky), or one JavaScript can't read, is left to Arky, which answers the question's field error.
  • Empty answers are left out. File answers carry File objects and are sent as multipart. Arky's configured limits refuse what is too big (production: 10 MiB a file, 20 files and 50 MiB a request): 413 FORM_SUBMISSION.FILE_TOO_LARGE, 409 FORM_SUBMISSION.TOO_MANY_FILES and 413 GENERAL.PAYLOAD_TOO_LARGE.
  • The form a shopper sees. forms.get and forms.getByKey answer StorefrontForm: id, key, questions, questions_updated_at and status, without the store's email and stage settings.
  • Changed forms. When the form's questions changed since you loaded it, Arky refuses with 409 FORM_SUBMISSION.FORM_CHANGED: load it again.

A long form can keep its answers in the browser until they are sent, so a lost answer survives a reload:

import { formValuesFromAnswers } from "arky-sdk/storefront";

const application = await arky.forms.getByKey({ key: "partner-application" });
const saved = await arky.forms.pendingSubmission({ form_id: application.id });
const restored = saved ? formValuesFromAnswers(saved.answers) : {};
const kept = saved ?? (await arky.forms.retainSubmission({ form: application, values: { company: "Kafana d.o.o." }, language: "en" }));
const sent = await arky.forms.recoverSubmission({ form_id: kept.form_id });
console.log(restored, sent?.id);

retainSubmission keeps the whole submission, answers included, under an id from createId; it can't hold files. The same answers again answer the kept one; different ones are refused with DurableRequestError pending until it is sent. pendingSubmission reads it back and recoverSubmission sends it under the same id.

8. Bookings

arky.eshop.bookingCalendar({ buyer, package_id }) builds a month calendar and the free slots of a booking service, and adds a chosen slot to that buyer's cart:

const { items: services } = await arky.eshop.packageItem.find({ package_id, selection: { types: ["booking_service"] }, limit: 20 });
const calendar = arky.eshop.bookingCalendar({ buyer: { type: "customer" }, package_id });

const [service] = services;
if (service?.item.type === "booking_service") {
  const state = await calendar.select({ booking_service_id: service.item.booking_service_id, store_location_id });
  const day = state.days.find((cell) => cell.available);
  if (day) calendar.selectDate({ date: day.iso });
  const [slot] = calendar.state.get().slots;
  if (slot) await calendar.addToCart({ slot });
}
  • State:
    • the service: booking_service, store_location_id (the branch the visit is at), booking_choices (the prices of its offerings in this package and market), booking_resources ({ id, key, blocks, timezone }, from the availability rows), selected_booking_resource_id, availability, timezone (null: each slot in its resource's timezone) and loading;
    • the calendar: month and days (date, iso, available, is_selected, is_in_range, is_today, blank), plus the calendar.month_label atom with the shown month in the store's language;
    • the choice: selected_date, slots (booking_offering_id, store_location_id, booking_resource_id, price_ref, price, from, to, timezone, time_text, date_text, is_multi_day) and selected_slot.
  • Calls. Steps that read Arky answer the new state; picks only change the state.
    • reads: select({ booking_service_id, store_location_id }), prevMonth(), nextMonth(), selectResource({ booking_resource_id }) and loadMoreChoices();
    • picks: selectDate({ date }), selectFirstAvailableDate(), selectSlot({ slot }) and setTimezone({ timezone });
    • addToCart({ slot, id?, capacity_units?, form_submission_id?, add_ons? }) answers the cart. Pass add_ons for an offering that has add-ons, each once; without them the line names none. The line names the slot's branch; its resource is { type: "resource", booking_resource_id } after selectResource, else { type: "any" }, so Arky picks one.
  • Sign-out and language. Signing out or another buyer signing in empties the calendar, member prices included; call select again. A language change writes the slot texts again in the new language.
  • Prices and resources. select reads the service and the first page of its item's prices; a slot shows once its offering's price is loaded, so call loadMoreChoices() while booking_choices_cursor is set. The resources come with the availability: each row names its resource's resource_key and resource_blocks, so booking_resources lists { id, key, blocks, timezone } and the calendar reads no resource.
  • Months and time zones. A month read covers the shown month and a day on each side, up to 20 offerings a request, following cursor until every offering is in: Arky ends a page before the offering that would pass its slot budget and answers the cursor of the rest. A slot shows in its resource's timezone (slot.timezone) under that zone's date, as a venue's own site shows it; setTimezone({ timezone }) shows every slot in one zone instead, such as the visitor's for an online service.
  • Stays. A slot that crosses midnight, such as a night's stay, is is_multi_day: its time_text is the date range, and its days are is_in_range once it is chosen. A booking lasts at most 24 hours, so a stay of several nights is one booking a night; with a booking of the same service already in the cart, the calendar opens on the month that booking ends in.

The cart and the checkout are the same as for products: the checkoutFlow of the same scope sees the booking lines.

  • Without the calendar, read the service with bookingService.get({ id, package_id }), its offerings' prices with packageItem.findPrices({ package_item_id, package_id }), and the free slots at one branch with bookingService.getAvailability({ package_id, booking_service_id, store_location_id, from, to }) (at most 60 days per read; follow cursor). Each row names its booking_offering_id, store_location_id and booking_resource_id. Add a slot with cart.addBooking({ booking_offering_id, store_location_id, resource, requested_interval, add_ons, capacity_units, price }), where resource is { type: "any" } or { type: "resource", booking_resource_id }, add_ons names each of the offering's add-ons once, every one being required, with the booker's resource pick for it ({ add_on_id, resource, form_submission_id?, add_ons }, empty when the offering has none); Arky picks the offering that fills each add-on and refuses picks that break the offering's rules with CART.BOOKING_ADD_ON_INVALID and price is { package_id, package_item_id, price_id }. bookingOffering.get({ id, package_id }) reads one offering with its price, and bookingResource.get({ id, offering_id, package_id }) one resource it can use.
  • What the quote plans. Each quote booking line has availability: available with spots and the plan, history with the plan, or unavailable with its code. The plan names the resource Arky picked, the line's interval, its total_interval with every add-on, and each add-on's own interval and resource.
  • Taken slots. The quote checks the slot again: a taken slot is a booking_unavailable blocker.
  • Later changes. eshop.order.cancelBookingItem and rescheduleBookingItem change a booking after the order; both name the line as order_booking_item_id.
  • The patient's answer. An upcoming booking's status.attendance is { type: "upcoming", response }, where response is unanswered, coming or change_requested with its at; a reschedule sets it back to unanswered. eshop.order.answerBookingItem({ order_id, order_booking_item_id, starts_at, answer }) records the signed-in customer's answer ("coming" or "change_requested") for the start they saw. A reminder carries a signed answer link: eshop.order.answerBookingByLink({ token, answer }) needs no session and answers { order_id, order_booking_item_id, starts_at, response }. A stale start is refused with 409 GENERAL.CONFLICT and an answer after the start with ORDER.BOOKING_CHANGE_CLOSED.
  • Resources. eshop.bookingResource.get({ id, offering_id, package_id }) accepts an id or a slug in the client’s locale. Slugs are unique per store and language; the supplied offering must be visible and be able to use that resource. A booking resource has no type: its categories say what it is. Its hours name the branch of each window ({ store_location_id, from, to }, times of day in milliseconds).
  • Order booking lines. A booking line names its store_location_id, customer_id, interval and total_interval (with every add-on), its add_ons (each with its own offering, service, resource, interval, price { type: "free" } or { type: "listed", price, amount }, and status held or taken_off) and changes, the staff changes to the line (line, add_on, add_on_added or offering_changed, with by and at).

9. Content and media

const site = await arky.content.load({ collection: { key: "website" } });
const title = site.object("info")?.text("title");
const post = await arky.content.load({ entry: { collection_id, slug: "launch" } }, { locale: "it" });
const posts = await arky.content.loadEntries({ collection_id, limit: 20 });
const older = posts.cursor ? await arky.content.loadEntries({ collection_id, limit: 20, cursor: posts.cursor }) : null;
console.log(title, site.media("hero")?.id, post.text("title"), posts.items.length, older?.items.length);
  • content.load reads one collection ({ id } or { key }) or one entry ({ id }, { collection_id, key } or { collection_id, slug }), with the media its blocks name. loadEntries reads one page of a collection's entries (limit, 20 unless named, at most 100) with the media they name and answers { items, cursor }; pass cursor back for the next page. It never walks the whole collection.
  • Accessors. The answer has record, blocks, media_by_id and accessors in the call's locale: block(key), text(key), media(key), object(key) and list(key). Text is read in the exact language asked for, never another, and an accessor for a block of another type throws.
  • Missing entries. A key or slug that matches no entry throws an ArkyError with code not_found.
  • Plain reads: content.collection.get({ id }), content.collection.getByKey({ key }), content.entry.get({ id }) and content.entry.find, which takes collection_id with key, slug, query or filters, or a list of ids.
  • Storefront shapes. These routes answer StorefrontCollection and StorefrontEntry. A collection has type: "public"; an entry keeps its key and slugs in type: { type: "public", key, slugs }, so a loaded entry's URL uses post.record.type.slugs.it. Public entry create and update still take key and slugs as request fields.
  • Shared entries. After the customer signs in, sharedEntries.find({ collection_id?, limit?, cursor? }), get({ id }) and fileLink({ id, media_id, variant }) read the entries shared with that customer as StorefrontSharedEntry. A file link answers { url, expires_at } and lasts five minutes. These reads use the customer's session and each read is logged. Public content reads do not expose Private, Shared or Note entries.

Errors

Everything the SDK throws at runtime is an ArkyError with a code; map the code to your own text. Each class works with instanceof whichever entry point made it.

| Class | When | Codes | |---|---|---| | ArkyApiError | Arky answered with its own refusal | Arky's own, such as GENERAL.CONFLICT, GENERAL.NOT_FOUND and FORM_SUBMISSION.FORM_CHANGED, exactly as the Server sent it; it also has statusCode and validationErrors | | CartPresentationChangedError | a checkout's quote changed (an ArkyApiError with code COMMERCE.PRESENTATION_CHANGED) | carries the new quote | | ArkyNetworkError | no readable answer: no answer at all, a success that isn't JSON, or a refusal without Arky's error body, such as a proxy's 502 page (with its statusCode) | network, aborted, unreadable_answer | | DurableRequestError | a retry-safe request couldn't run | storage (no localStorage or Web Locks; nothing was sent), busy, pending, answer_mismatch, settled_elsewhere | | CartError | th