export { CIMPLIFY_CDN_HOSTS, DEFAULT_CDN_BASE_URL, DURATION_UNIT, INPUT_FIELD_TYPE, PRODUCT_TYPE, RENDER_HINT, allGalleryImages, assetUrl, getVariantDisplayName, isCimplifyAsset, resolveGallery } from './chunk-E6T5VJMG.mjs';
export { isValidPhoneForContext, normalizePhoneToE164, resolvePhoneCountryCode } from './chunk-YOIVZ6OA.mjs';
export { ActivityService, CimplifyClient, DeliveryService, PlacesService, StoreCreditQueries, SubscriptionService, SupportService, UploadService, createCimplifyClient } from './chunk-NWUEWUX2.mjs';
import { getAuthorizationEndpoint, DEFAULT_ISSUER, generatePkce, generateState } from './chunk-7BM56JET.mjs';
export { AUTHORIZATION_TYPE, AUTH_MUTATION, AuthService, BusinessService, CHECKOUT_MODE, CHECKOUT_MUTATION, CHECKOUT_STEP, CONTACT_TYPE, CartOperations, CatalogueQueries, CheckoutService as CheckoutOperations, CheckoutService, CimplifyElement, CimplifyElements, DEFAULT_COUNTRY, DEFAULT_CURRENCY, DEVICE_TYPE, ELEMENTS_AUTH_CONTACT_TYPES, ELEMENTS_AUTH_MODES, ELEMENTS_AUTH_PROMPTS, ELEMENT_TYPES, EVENT_TYPES, FxService, InventoryService, LINK_MUTATION, LINK_QUERY, LinkService, LiteService, MESSAGE_TYPES, MOBILE_MONEY_PROVIDER, ORDER_MUTATION, ORDER_TYPE, OrderQueries, PAYMENT_METHOD, PAYMENT_MUTATION, PAYMENT_STATE, PICKUP_TIME_TYPE, SchedulingService, combine, combineObject, createElements, err, flatMap, fromPromise, generateIdempotencyKey, getOrElse, isErr, isOk, mapError, mapResult, ok, startSignIn, toNullable, tryCatch, unwrap } from './chunk-7BM56JET.mjs';
export { CURRENCY_SYMBOLS, MOBILE_MONEY_PROVIDERS, categorizePaymentError, detectMobileMoneyProvider, formatMoney, formatNumberCompact, formatPrice, formatPriceAdjustment, formatPriceCompact, formatPriceRange, formatPriceWithTax, formatProductPrice, getBasePrice, getCurrencySymbol, getDiscountPercentage, getDisplayPrice, getMarkupPercentage, getPriceRange, getProductCurrency, getTaxAmount, getUnitPriceAtQuantity, hasTaxInfo, isOnSale, isPaymentStatusFailure, isPaymentStatusRequiresAction, isPaymentStatusSuccess, isTaxInclusive, normalizePaymentResponse, normalizeStatusResponse, parsePrice } from './chunk-TD3AY34U.mjs';
export { CimplifyError, ERROR_HINTS, ErrorCode, IdempotencyMismatchError, ZERO, currencyCode, enrichError, getErrorHint, isCimplifyError, isIdempotencyMismatchError, isQuoteConflictRequiringConsent, isQuoteError, isRetryableError, isSupportedCurrency, money, moneyFromNumber } from './chunk-AMZXALF6.mjs';
import './chunk-3G6RQLXK.mjs';

// src/silent-sign-in.ts
var DEFAULT_SCOPE = "openid email phone profile";
var DEFAULT_TIMEOUT_MS = 12e3;
var RESPONSE_TYPE_CODE = "code";
var RESPONSE_MODE_WEB_MESSAGE = "web_message";
var PROMPT_NONE = "none";
var AUTHORIZATION_RESPONSE_MESSAGE_TYPE = "authorization_response";
var ERROR_LOGIN_REQUIRED = "login_required";
async function signInSilent(opts) {
  const sessionUri = opts.sessionUri ?? "/auth/session";
  try {
    const sess = await fetch(sessionUri, { credentials: "include" });
    if (sess.ok) {
      const body = await sess.json().catch(() => null);
      if (body?.sub) return { ok: true, reason: "already_signed_in" };
    }
  } catch {
  }
  const callbackUri = opts.callbackUri ?? "/auth/callback";
  const authorizeEndpoint = opts.authUrl ? `${opts.authUrl.replace(/\/$/, "")}/oauth/authorize` : await getAuthorizationEndpoint(opts.issuer ?? DEFAULT_ISSUER);
  const pkce = await generatePkce();
  const state = generateState();
  const params = new URLSearchParams({
    response_type: RESPONSE_TYPE_CODE,
    response_mode: RESPONSE_MODE_WEB_MESSAGE,
    prompt: PROMPT_NONE,
    client_id: opts.clientId,
    redirect_uri: opts.redirectUri,
    scope: opts.scope ?? DEFAULT_SCOPE,
    state,
    code_challenge: pkce.challenge,
    code_challenge_method: pkce.method
  });
  const src = `${authorizeEndpoint}?${params.toString()}`;
  const expectedOrigin = new URL(authorizeEndpoint).origin;
  const iframe = document.createElement("iframe");
  iframe.style.display = "none";
  iframe.setAttribute("aria-hidden", "true");
  iframe.setAttribute("sandbox", "allow-scripts allow-same-origin");
  iframe.src = src;
  document.body.appendChild(iframe);
  const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
  return new Promise((resolve) => {
    let settled = false;
    const cleanup = () => {
      window.removeEventListener("message", handler);
      iframe.remove();
      clearTimeout(timer);
    };
    const finish = (result) => {
      if (settled) return;
      settled = true;
      cleanup();
      resolve(result);
    };
    const timer = setTimeout(() => finish({ ok: false, reason: "timeout" }), timeoutMs);
    const handler = async (event) => {
      if (event.origin !== expectedOrigin) return;
      const data = event.data;
      if (!data || typeof data !== "object" || data.type !== AUTHORIZATION_RESPONSE_MESSAGE_TYPE) return;
      const response = data.response;
      if (response.error === ERROR_LOGIN_REQUIRED) {
        finish({ ok: false, reason: ERROR_LOGIN_REQUIRED });
        return;
      }
      if (response.error || !response.code) {
        finish({ ok: false, reason: ERROR_LOGIN_REQUIRED });
        return;
      }
      if (response.state !== state) {
        finish({ ok: false, reason: "state_mismatch" });
        return;
      }
      try {
        const res = await fetch(callbackUri, {
          method: "POST",
          credentials: "include",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ code: response.code, codeVerifier: pkce.verifier, state })
        });
        finish(res.ok ? { ok: true } : { ok: false, reason: "callback_failed" });
      } catch {
        finish({ ok: false, reason: "exception" });
      }
    };
    window.addEventListener("message", handler);
  });
}

export { signInSilent };
