HEX
Server: LiteSpeed
System: Linux eko108.isimtescil.net 4.18.0-477.21.1.lve.1.el8.x86_64 #1 SMP Tue Sep 5 23:08:35 UTC 2023 x86_64
User: uyarreklamcomtr (11202)
PHP: 7.4.33
Disabled: opcache_get_status
Upload Files
File: /var/www/vhosts/uyarreklam.com.tr/httpdocs/types.tar
KeyboardShortcut.ts000064400000002252151542115230010410 0ustar00import { _x } from '@wordpress/i18n'

export const KEYBOARD_KEYS = <const> {
	'Cmd': _x('Cmd', 'keyboard key', 'code-snippets'),
	'Ctrl': _x('Ctrl', 'keyboard key', 'code-snippets'),
	'Shift': _x('Shift', 'keyboard key', 'code-snippets'),
	'Option': _x('Option', 'keyboard key', 'code-snippets'),
	'Alt': _x('Alt', 'keyboard key', 'code-snippets'),
	'Tab': _x('Tab', 'keyboard key', 'code-snippets'),
	'Up': _x('Up', 'keyboard key', 'code-snippets'),
	'Down': _x('Down', 'keyboard key', 'code-snippets'),
	'A': _x('A', 'keyboard key', 'code-snippets'),
	'D': _x('D', 'keyboard key', 'code-snippets'),
	'F': _x('F', 'keyboard key', 'code-snippets'),
	'G': _x('G', 'keyboard key', 'code-snippets'),
	'R': _x('R', 'keyboard key', 'code-snippets'),
	'S': _x('S', 'keyboard key', 'code-snippets'),
	'Y': _x('Y', 'keyboard key', 'code-snippets'),
	'Z': _x('Z', 'keyboard key', 'code-snippets'),
	'/': _x('/', 'keyboard key', 'code-snippets'),
	'[': _x(']', 'keyboard key', 'code-snippets'),
	']': _x(']', 'keyboard key', 'code-snippets')
}

export type KeyboardKey = keyof typeof KEYBOARD_KEYS

export interface KeyboardShortcut {
	label: string
	mod: KeyboardKey | KeyboardKey[]
	key: KeyboardKey
}
ScreenNotice.ts000064400000000071151542115230007472 0ustar00export type ScreenNotice = ['error' | 'updated', string]
SelectOption.ts000064400000000270151542115230007522 0ustar00import type { GroupBase } from 'react-select'

export interface SelectOption<T> {
	readonly value: T
	readonly label: string
}

export type SelectGroup<T> = GroupBase<SelectOption<T>>
Shortcodes.ts000064400000000305151542115230007226 0ustar00export interface SourceShortcodeAtts {
	id: string
	line_numbers: boolean
}

export interface ContentShortcodeAtts {
	id: string
	name: string
	php: boolean
	format: boolean
	shortcodes: boolean
}
Snippet.ts000064400000001602151542115230006534 0ustar00export interface Snippet {
	id: number
	name: string
	desc: string
	code: string
	tags: string[]
	scope: SnippetScope
	priority: number
	active: boolean
	network?: boolean
	shared_network?: boolean | null
	modified?: string
	code_error?: [string, number] | null
}

export type SnippetType = typeof SNIPPET_TYPES[number]
export type SnippetScope = typeof SNIPPET_SCOPES[number]

export const SNIPPET_SCOPES = <const> [
	'global', 'admin', 'front-end', 'single-use',
	'content', 'head-content', 'footer-content',
	'admin-css', 'site-css',
	'site-head-js', 'site-footer-js'
]

export const SNIPPET_TYPES = <const> ['php', 'html', 'css', 'js']

export const SNIPPET_TYPE_SCOPES: Record<SnippetType, SnippetScope[]> = {
	php: ['global', 'admin', 'front-end', 'single-use'],
	html: ['content', 'head-content', 'footer-content'],
	css: ['admin-css', 'site-css'],
	js: ['site-head-js', 'site-footer-js']
}
SnippetsExport.ts000064400000000214151542115230010117 0ustar00import type { Snippet } from './Snippet'

export interface SnippetsExport {
	generator: string
	date_created: string
	snippets: Snippet[]
}
Window.ts000064400000002662151542115230006370 0ustar00import type Prism from 'prismjs'
import type tinymce from 'tinymce'
import type { Snippet } from './Snippet'
import type { CodeEditorInstance, EditorOption, WordPressCodeEditor } from './WordPressCodeEditor'
import type { WordPressEditor } from './WordPressEditor'

declare global {
	interface Window {
		readonly wp: {
			readonly editor?: WordPressEditor
			readonly codeEditor: WordPressCodeEditor
		}
		readonly pagenow: string
		readonly ajaxurl: string
		readonly tinymce?: tinymce.EditorManager
		readonly wpActiveEditor?: string
		code_snippets_editor_preview?: CodeEditorInstance
		readonly code_snippets_editor_settings: EditorOption[]
		CODE_SNIPPETS_PRISM?: typeof Prism
		readonly CODE_SNIPPETS?: {
			isLicensed: boolean
			restAPI: {
				base: string
				snippets: string
				cloud: string
				nonce: string
				localToken: string
			}
			urls: {
				plugin: string
				manage: string
				addNew: string
				edit: string
				connectCloud: string
			}
		}
		readonly CODE_SNIPPETS_EDIT?: {
			snippet: Snippet
			pageTitleActions: Record<string, string>
			isPreview: boolean
			isLicensed: boolean
			enableDownloads: boolean
			scrollToNotices: boolean
			extraSaveButtons: boolean
			activateByDefault: boolean
			enableDescription: boolean
			editorTheme: string
			tagOptions: {
				enabled: boolean
				allowSpaces: boolean
				availableTags: string[]
			}
			descEditorOptions: {
				rows: number
				mediaButtons: boolean
			}
		}
	}
}
WordPressCodeEditor.ts000064400000001354151542115230011010 0ustar00import type { Editor, EditorConfiguration } from 'codemirror'

export interface EditorOption {
	name: string
	type: 'checkbox' | 'number' | 'select'
	codemirror: keyof EditorConfiguration
}

export interface CodeEditorInstance {
	codemirror: Editor
	settings: CodeEditorSettings
}

export interface CodeEditorSettings {
	codemirror: EditorConfiguration
	csslint: Record<string, unknown>
	htmlhint: Record<string, unknown>
	jshint: Record<string, unknown>
	onTabNext: () => void
	onTabPrevious: () => void
	onChangeLintingErrors: () => void
	onUpdateErrorNotice: () => void
}

export interface WordPressCodeEditor {
	initialize: (textarea: Element, options?: Partial<CodeEditorSettings>) => CodeEditorInstance
	defaultSettings: CodeEditorSettings
}
WordPressEditor.ts000064400000001144151542115230010212 0ustar00import type tinymce from 'tinymce'

export interface VisualEditorSettings {
	tinymce: boolean | tinymce.Settings & {
		toolbar1?: string | string[]
		toolbar2?: string | string[]
		toolbar3?: string | string[]
		toolbar4?: string | string[]
	}
	quicktags: boolean | Record<string, string>
	mediaButtons: boolean
}

export interface WordPressEditor {
	initialize: (id: string, settings?: Partial<VisualEditorSettings>) => void
	remove: (id: string) => void
	getContent: (id: string) => string
}

export interface LocalisedEditor extends tinymce.Editor {
	getLang: (s: string) => string | Record<string, string>
}
wp/Page.ts000064400000000326151542115230006416 0ustar00import type { Post } from './Post'

export const PAGES_ENDPOINT = '/wp/v2/pages'

export interface Page extends Omit<Post, 'categories' | 'tags'> {
	parent: number
	menu_order: number
}

export type Pages = Page[]
wp/Post.ts000064400000001735151542115230006474 0ustar00export const POSTS_ENDPOINT = '/wp/v2/posts'

export interface Post {
	id: number
	date: string | null
	date_gmt?: string | null
	readonly guid?: { rendered: string }
	link: string
	modified?: string
	modified_gmt?: string
	slug: string
	status?: PostStatus
	readonly type: string
	password?: string
	readonly permalink_template?: string
	readonly generated_slug?: string
	title: { rendered: string }
	content?: {
		rendered: string
		protected: boolean
	}
	excerpt: {
		rendered: string
		protected: false
	}
	author: number
	featured_media: number
	comment_status?: 'open' | 'closed'
	ping_status?: 'open' | 'closed'
	format?: PostFormat
	meta?: Record<string, unknown>
	sticky?: boolean
	template?: string
	categories?: number[]
	tags?: number[]
}

export type PostStatus = 'publish' | 'future' | 'draft' | 'pending' | 'private'

export type PostFormat =
	'standard' | 'aside' | 'chat' | 'gallery' | 'link' | 'image' | 'quote' | 'status' | 'video' | 'audio'

export type Posts = Post[]
wp/PostType.ts000064400000000460151542115230007330 0ustar00export const POST_TYPES_ENDPOINT = '/wp/v2/types'

export interface PostType {
	description: string
	hierarchical: boolean
	has_archive: boolean
	name: string
	slug: string
	icon: string
	taxonomies: string[]
	rest_base: string
	rest_namespace: string
}

export type PostTypes = Record<string, PostType>
wp/Term.ts000064400000001042151542115230006445 0ustar00export const TAGS_ENDPOINT = '/wp/v2/tags'
export const CATEGORIES_ENDPOINT = '/wp/v2/categories'

export interface Term {
	id: number
	count: number
	description: string
	link: string
	name: string
	slug: string
	taxonomy: Taxonomy
	meta: Record<string, unknown>
}

export type PostTag = Term

export interface Category extends Term {
	parent: number
}

export type Taxonomy = 'category' | 'post_tag' | 'nav_menu' | 'link_category' | 'post_format'

export type Terms = Term[]
export type PostTags = PostTag[]
export type Categories = Category[]
wp/User.ts000064400000001037151542115230006460 0ustar00export const USERS_ENDPOINT = '/wp/v2/users'

export interface User {
	readonly id: number
	username?: string
	name: string
	first_name?: string
	last_name?: string
	email?: string
	url: string
	description: string
	readonly link: string
	locale?: string
	nickname?: string
	slug: string
	registered_date?: string
	roles?: string[]
	readonly capabilities?: Record<string, boolean>
	readonly extra_capabilities?: Record<string, boolean>
	readonly avatar_urls: Record<string, string>
	meta: Record<string, unknown>
}

export type Users = User[]
index.ts000064400000000074151550203500006220 0ustar00export * from './type-defs';
export * from './type-guards';
type-defs/add-to-cart-form.js000064400000005517151550203500012046 0ustar00/**
 * @typedef {Object} AddToCartFormDispatchActions
 *
 * @property {function():void}         resetForm          Dispatches an action that resets the form to a
 *                                                        pristine state.
 * @property {function():void}         submitForm         Dispatches an action that tells the form to submit.
 * @property {function(number):void}   setQuantity        Dispatches an action that sets the quantity to
 *                                                        the given value.
 * @property {function(Object):void}   setRequestParams   Dispatches an action that sets params for the
 *                                                        add to cart request (key value pairs).
 * @property {function(boolean=):void} setHasError        Dispatches an action that sets the status to
 *                                                        having an error.
 * @property {function(Object):void}   setAfterProcessing Dispatches an action that sets the status to
 *                                                        after processing and also sets the response
 *                                                        data accordingly.
 */

/**
 * @typedef {Object} AddToCartFormEventRegistration
 *
 * @property {function(function():boolean|Object,number=):function():void} onAddToCartAfterProcessingWithSuccess Used to register a callback that will fire after form has been processed and there are no errors.
 * @property {function(function():boolean|Object,number=):function():void} onAddToCartAfterProcessingWithError   Used to register a callback that will fire when the form has been processed and has an error.
 * @property {function(function():boolean|Object,number=):function():void} onAddToCartBeforeProcessing           Used to register a callback that will fire when the form has been submitted before being sent off to the server.
 */

/**
 * @typedef {Object} AddToCartFormStatusConstants
 *
 * @property {string} PRISTINE          Form is in it's initialized state.
 * @property {string} IDLE              When form state has changed but there is no
 *                                      activity happening.
 * @property {string} DISABLED          If the form cannot be submitted due to missing
 *                                      constraints, this status is assigned.
 * @property {string} BEFORE_PROCESSING This is the state before form processing
 *                                      begins after the add to cart button has been
 *                                      pressed. Validation occurs at point point.
 * @property {string} PROCESSING        After BEFORE_PROCESSING status emitters have
 *                                      finished successfully.
 * @property {string} AFTER_PROCESSING  After server side processing is completed
 *                                      this status is set.
 */

export {};
type-defs/address-fields.js000064400000001733151550203500011673 0ustar00/**
 * @typedef {Object} AddressField
 *
 * @property {string}  label         The label for the field.
 * @property {string}  optionalLabel The label for the field if made optional.
 * @property {string}  autocomplete  The HTML autocomplete attribute value. See
 *                                   https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete
 * @property {boolean} required      Set to true if the field is required.
 * @property {boolean} hidden        Set to true if the field should not be
 *                                   rendered.
 * @property {number}  index         Fields will be sorted and render in this
 *                                   order, lowest to highest.
 */

/**
 * @typedef {string} CountryCode ISO 3166 Country code.
 */

/**
 * @typedef {string} AddressFieldKey Key for an address field, e.g. first_name.
 */

/**
 * @typedef {Object <CountryCode, Object <AddressFieldKey, AddressField>>} CountryAddressFields
 */

export {};
type-defs/api-error-response.ts000064400000001467151550203500012554 0ustar00/**
 * Internal dependencies
 */
import type { CartResponse } from './cart-response';

// This is the standard API response data when an error is returned.
export type ApiErrorResponse = {
	code: string;
	message: string;
	data?: ApiErrorResponseData | undefined;
};

// API errors contain data with the status, and more in-depth error details. This may be null.
export type ApiErrorResponseData = {
	status: number;
	params: Record< string, string >;
	details: Record< string, ApiErrorResponseDataDetails >;
	// Some endpoints return cart data to update the client.
	cart?: CartResponse | undefined;
} | null;

// The details object lists individual errors for each field.
export type ApiErrorResponseDataDetails = {
	code: string;
	message: string;
	data: ApiErrorResponseData;
	additional_errors: ApiErrorResponse[];
};
type-defs/api-response.ts000064400000001350151550203500011414 0ustar00export interface ApiResponse< T > {
	body: Record< string, unknown >;
	headers: Headers;
	status: number;
	ok: boolean;
	json: () => Promise< T >;
}

export function assertBatchResponseIsValid(
	response: unknown
): asserts response is {
	responses: ApiResponse< unknown >[];
	headers: Headers;
} {
	if (
		typeof response === 'object' &&
		response !== null &&
		response.hasOwnProperty( 'responses' )
	) {
		return;
	}
	throw new Error( 'Response not valid' );
}

export function assertResponseIsValid< T >(
	response: unknown
): asserts response is ApiResponse< T > {
	if (
		typeof response === 'object' &&
		response !== null &&
		'body' in response &&
		'headers' in response
	) {
		return;
	}
	throw new Error( 'Response not valid' );
}
type-defs/attributes.ts000064400000001533151550203500011200 0ustar00export interface AttributeSetting {
	attribute_id: string;
	attribute_name: string;
	attribute_label: string;
	attribute_orderby: 'menu_order' | 'name' | 'name_num' | 'id';
	attribute_public: 0 | 1;
	attribute_type: string;
}

export interface AttributeObject {
	count: number;
	has_archives: boolean;
	id: number;
	label: string;
	name: string;
	order: 'menu_order' | 'name' | 'name_num' | 'id';
	parent: number;
	taxonomy: string;
	type: string;
}

export interface AttributeQuery {
	attribute: string;
	operator: 'in' | 'and';
	slug: string[];
}

export interface AttributeTerm {
	attr_slug: string;
	count: number;
	description: string;
	id: number;
	name: string;
	parent: number;
	slug: string;
}

export interface AttributeMetadata {
	taxonomy: string;
	termId: number;
}

export type AttributeWithTerms = AttributeObject & { terms: AttributeTerm[] };
type-defs/billing.js000064400000001475151550203500010425 0ustar00/**
 * @typedef {Object} BillingData
 *
 * @property {string} email      The email for the billing address
 * @property {string} first_name First name of billing customer
 * @property {string} last_name  Last name of billing customer
 * @property {string} company    Company name for the billing address
 * @property {string} address_1  First line of the billing address
 * @property {string} address_2  Second line of the billing address
 * @property {string} city       The city of the billing address
 * @property {string} state      The state of the billing address (ISO or name)
 * @property {string} postcode   The postal or zip code for the billing address
 * @property {string} country    The country for the billing address (ISO)
 * @property {string} phone      The phone number for the billing address
 */

export {};
type-defs/blocks.ts000064400000000557151550203500010274 0ustar00/**
 * External dependencies
 */
import type { BlockEditProps, BlockInstance } from '@wordpress/blocks';
import type { LazyExoticComponent } from 'react';

export type EditorBlock< T > = BlockInstance< T > & BlockEditProps< T >;

export type RegisteredBlockComponent =
	| LazyExoticComponent< React.ComponentType< unknown > >
	| ( () => JSX.Element | null )
	| null;
type-defs/cart-response.ts000064400000010112151550203500011570 0ustar00/**
 * Internal dependencies
 */
import type { CurrencyResponse } from './currency';
import type { CartItem } from './cart';
import type { ProductResponseItem } from './product-response';

export interface CartResponseTotalsItem extends CurrencyResponse {
	total_discount: string;
	total_discount_tax: string;
}

export interface CartResponseCouponItem {
	code: string;
	discount_type: string;
	totals: CartResponseTotalsItem;
}

export interface CartResponseCouponItemWithLabel
	extends CartResponseCouponItem {
	label: string;
}

export type CartResponseCoupons = CartResponseCouponItemWithLabel[];

export interface ResponseFirstNameLastName {
	first_name: string;
	last_name: string;
}

export interface ResponseBaseAddress {
	address_1: string;
	address_2: string;
	city: string;
	state: string;
	postcode: string;
	country: string;
}

export interface ShippingRateItem {
	key: string;
	name: string;
	quantity: number;
}

export interface MetaKeyValue {
	key: string;
	value: string;
}

export type ExtensionsData =
	| Record< string, unknown >
	| Record< string, never >;

export interface CartResponseShippingPackageShippingRate
	extends CurrencyResponse {
	rate_id: string;
	name: string;
	description: string;
	delivery_time: string;
	price: string;
	taxes: string;
	instance_id: number;
	method_id: string;
	meta_data: Array< MetaKeyValue >;
	selected: boolean;
}

export interface CartResponseShippingRate {
	/* PackageId can be a string, WooCommerce Subscriptions uses strings for example, but WooCommerce core uses numbers */
	package_id: number | string;
	name: string;
	destination: ResponseBaseAddress;
	items: Array< ShippingRateItem >;
	shipping_rates: Array< CartResponseShippingPackageShippingRate >;
}

export interface CartResponseShippingAddress
	extends ResponseBaseAddress,
		ResponseFirstNameLastName {
	company: string;
	phone: string;
}

export interface CartResponseBillingAddress
	extends CartResponseShippingAddress {
	email: string;
}

export interface CartResponseImageItem {
	id: number;
	src: string;
	thumbnail: string;
	srcset: string;
	sizes: string;
	name: string;
	alt: string;
}

export interface CartResponseVariationItem {
	attribute: string;
	value: string;
}

export interface CartResponseItemPrices extends CurrencyResponse {
	price: string;
	regular_price: string;
	sale_price: string;
	price_range: null | { min_amount: string; max_amount: string };
	raw_prices: {
		precision: number;
		price: string;
		regular_price: string;
		sale_price: string;
	};
}

export interface CartResponseItemTotals extends CurrencyResponse {
	line_subtotal: string;
	line_subtotal_tax: string;
	line_total: string;
	line_total_tax: string;
}

export type CartResponseItem = CartItem;
export interface CartResponseTotalsTaxLineItem {
	name: string;
	price: string;
	rate: string;
}

export interface CartResponseFeeItemTotals extends CurrencyResponse {
	total: string;
	total_tax: string;
}

export type CartResponseFeeItem = {
	id: string;
	name: string;
	totals: CartResponseFeeItemTotals;
};

export interface CartResponseTotals extends CurrencyResponse {
	total_items: string;
	total_items_tax: string;
	total_fees: string;
	total_fees_tax: string;
	total_discount: string;
	total_discount_tax: string;
	total_shipping: string;
	total_shipping_tax: string;
	total_price: string;
	total_tax: string;
	tax_lines: Array< CartResponseTotalsTaxLineItem >;
}

export interface CartResponseErrorItem {
	code: string;
	message: string;
}

export interface CartResponseExtensionItem {
	[ key: string ]: unknown;
}

export interface CartResponse {
	coupons: Array< CartResponseCouponItem >;
	shipping_rates: Array< CartResponseShippingRate >;
	shipping_address: CartResponseShippingAddress;
	billing_address: CartResponseBillingAddress;
	items: Array< CartResponseItem >;
	items_count: number;
	items_weight: number;
	cross_sells: Array< ProductResponseItem >;
	needs_payment: boolean;
	needs_shipping: boolean;
	has_calculated_shipping: boolean;
	fees: Array< CartResponseFeeItem >;
	totals: CartResponseTotals;
	errors: Array< CartResponseErrorItem >;
	payment_methods: string[];
	payment_requirements: string[];
	extensions: ExtensionsData;
}
type-defs/cart.js000064400000030632151550203500007733 0ustar00/**
 * @typedef {import('./shipping').ShippingAddress} CartShippingAddress
 */

/**
 * @typedef {Object} CartTotalItem
 *
 * @property {string} label        Label for total item
 * @property {number} value        The value of the total item (in subunits).
 * @property {number} valueWithTax The value of the total item with tax
 *                                 included (in subunits).
 */

/**
 * @typedef {Object} CartItemImage
 *
 * @property {number} id        Image id.
 * @property {string} src       Full size image URL.
 * @property {string} thumbnail Thumbnail URL.
 * @property {string} srcset    Thumbnail srcset for responsive image.
 * @property {string} sizes     Thumbnail sizes for responsive images.
 * @property {string} name      Image name.
 * @property {string} alt       Image alternative text.
 */

/**
 * @typedef {Object} CartItemVariation
 *
 * @property {string} attribute Variation attribute name.
 * @property {string} value     Variation attribute value.
 */

/**
 * @typedef {Object} CartItemTotals
 *
 * @property {string} currency_code               The ISO code for the currency.
 * @property {number} currency_minor_unit         The precision (decimal
 *                                                places).
 * @property {string} currency_symbol             The symbol for the currency
 *                                                (eg '$')
 * @property {string} currency_prefix             Price prefix for the currency
 *                                                which can be used to format
 *                                                returned prices.
 * @property {string} currency_suffix             Price suffix for the currency
 *                                                which can be used to format
 *                                                returned prices.
 * @property {string} currency_decimal_separator  The string used for the
 *                                                decimal separator.
 * @property {string} currency_thousand_separator The string used for the
 *                                                thousands separator.
 * @property {string} line_subtotal               Line subtotal (the price of
 *                                                the product before coupon
 *                                                discounts have been applied
 *                                                in subunits).
 * @property {string} line_subtotal_tax           Line subtotal tax (in
 *                                                subunits).
 * @property {string} line_total                  Line total (the price of the
 *                                                product after coupon
 *                                                discounts have been applied
 *                                                in subunits).
 * @property {string} line_total_tax              Line total tax (in subunits).
 */

/**
 * @typedef {Object} CartItemPriceRange
 *
 * @property {string} min_amount Price min amount in range.
 * @property {string} max_amount Price max amount in range.
 */

/**
 * @typedef {Object} CartItemPrices
 *
 * @property {string}                  currency_code               The ISO code for the
 *                                                                 currency.
 * @property {number}                  currency_minor_unit         The precision (decimal
 *                                                                 places).
 * @property {string}                  currency_symbol             The symbol for the
 *                                                                 currency (eg '$')
 * @property {string}                  currency_prefix             Price prefix for the
 *                                                                 currency which can be
 *                                                                 used to format returned
 *                                                                 prices.
 * @property {string}                  currency_suffix             Price suffix for the
 *                                                                 currency which can be
 *                                                                 used to format returned
 *                                                                 prices.
 * @property {string}                  currency_decimal_separator  The string used for the
 *                                                                 decimal separator.
 * @property {string}                  currency_thousand_separator The string used for the
 *                                                                 thousands separator.
 * @property {string}                  price                       Current product price
 *                                                                 in subunits.
 * @property {string}                  regular_price               Regular product price
 *                                                                 in subunits.
 * @property {string}                  sale_price                  Sale product price, if
 *                                                                 applicable (in subunits).
 * @property {CartItemPriceRange|null} price_range                 Price range, if
 *                                                                 applicable.
 *
 */

/**
 * @typedef {Object} CartItem
 *
 * @property {string}              key                  Unique identifier for the
 *                                                      item within the cart.
 * @property {number}              id                   The cart item product or
 *                                                      variation id.
 * @property {number}              quantity             The quantity of this item
 *                                                      in the cart.
 * @property {string}              name                 Product name.
 * @property {string}              summary              A short summary (or
 *                                                      excerpt from the full
 *                                                      description).
 * @property {string}              short_description    Product short description
 *                                                      in HTML format.
 * @property {string}              sku                  Stock keeping unit, if
 *                                                      applicable.
 * @property {number|null}         low_stock_remaining  Quantity left in stock if
 *                                                      stock is low, or null if
 *                                                      not applicable.
 * @property {boolean}             backorders_allowed   True if backorders are
 *                                                      allowed past stock
 *                                                      availability.
 * @property {boolean}             show_backorder_badge Whether a notification
 *                                                      should be shown about the
 *                                                      product being available on
 *                                                      backorder.
 * @property {boolean}             sold_individually    If true, only one item of
 *                                                      this product is allowed
 *                                                      for purchase in a single
 *                                                      order.
 * @property {string}              permalink            Product URL.
 * @property {CartItemImage[]}     images               List of images attached
 *                                                      to the cart item
 *                                                      product/variation.
 * @property {CartItemVariation[]} variation            Chosen attributes (for
 *                                                      variations).
 * @property {CartItemPrices}      prices               Item prices.
 * @property {CartItemTotals}      totals               Item total amounts
 *                                                      provided using the
 *                                                      smallest unit of the
 *                                                      currency.
 * @property {Object}              extensions           Extra data registered
 *                                                      by plugins.
 */

/**
 * @typedef {Object} CartData
 *
 * @property {Array}               coupons         Coupons applied to cart.
 * @property {Array}               shippingRates   Array of selected shipping
 *                                                 rates.
 * @property {CartShippingAddress} shippingAddress Shipping address for the
 *                                                 cart.
 * @property {Array}               items           Items in the cart.
 * @property {number}              itemsCount      Number of items in the cart.
 * @property {number}              itemsWeight     Weight of items in the cart.
 * @property {boolean}             needsShipping   True if the cart needs
 *                                                 shipping.
 * @property {CartTotals}          totals          Cart total amounts.
 */

/**
 * @typedef {Object} CartTotals
 *
 * @property {string} currency_code               Currency code (in ISO format)
 *                                                for returned prices.
 * @property {string} currency_symbol             Currency symbol for the
 *                                                currency which can be used to
 *                                                format returned prices.
 * @property {number} currency_minor_unit         Currency minor unit (number of
 *                                                digits after the decimal
 *                                                separator) for returned
 *                                                prices.
 * @property {string} currency_decimal_separator  Decimal separator for the
 *                                                currency which can be used to
 *                                                format returned prices.
 * @property {string} currency_thousand_separator Thousand separator for the
 *                                                currency which can be used to
 *                                                format returned prices.
 * @property {string} currency_prefix             Price prefix for the currency
 *                                                which can be used to format
 *                                                returned prices.
 * @property {string} currency_suffix             Price prefix for the currency
 *                                                which can be used to format
 *                                                returned prices.
 * @property {number} total_items                 Total price of items in the
 *                                                cart (in subunits).
 * @property {number} total_items_tax             Total tax on items in the
 *                                                cart (in subunits).
 * @property {number} total_fees                  Total price of any applied
 *                                                fees (in subunits).
 * @property {number} total_fees_tax              Total tax on fees (
 *                                                in subunits).
 * @property {number} total_discount              Total discount from applied
 *                                                coupons (in subunits).
 * @property {number} total_discount_tax          Total tax removed due to
 *                                                discount from applied coupons
 *                                                (in subunits).
 * @property {number} total_shipping              Total price of shipping
 *                                                (in subunits).
 * @property {number} total_shipping_tax          Total tax on shipping
 *                                                (in subunits).
 * @property {number} total_price                 Total price the customer will
 *                                                pay (in subunits).
 * @property {number} total_tax                   Total tax applied to items and
 *                                                shipping (in subunits).
 * @property {Array}  tax_lines                   Lines of taxes applied to
 *                                                items and shipping
 *                                                (in subunits).
 */

export {};
type-defs/cart.ts000064400000011267151550203500007750 0ustar00/**
 * External dependencies
 */
import type { CurrencyCode } from '@woocommerce/types';

/**
 * Internal dependencies
 */
import {
	MetaKeyValue,
	ShippingRateItem,
	ExtensionsData,
} from './cart-response';

import {
	ProductResponseItemData,
	ProductResponseItem,
} from './product-response';

export interface CurrencyInfo {
	currency_code: CurrencyCode;
	currency_symbol: string;
	currency_minor_unit: number;
	currency_decimal_separator: string;
	currency_thousand_separator: string;
	currency_prefix: string;
	currency_suffix: string;
}

export interface CartTotalsItem extends CurrencyInfo {
	total_discount: string;
	total_discount_tax: string;
}

export interface CartCouponItem {
	code: string;
	label: string;
	discount_type: string;
	totals: CartTotalsItem;
}

export interface FirstNameLastName {
	first_name: string;
	last_name: string;
}

export interface BaseAddress {
	address_1: string;
	address_2: string;
	city: string;
	state: string;
	postcode: string;
	country: string;
}

export interface CartShippingPackageShippingRate extends CurrencyInfo {
	rate_id: string;
	name: string;
	description: string;
	delivery_time: string;
	price: string;
	taxes: string;
	instance_id: number;
	method_id: string;
	meta_data: Array< MetaKeyValue >;
	selected: boolean;
}

export interface CartShippingRate {
	package_id: string | number;
	name: string;
	destination: BaseAddress;
	items: Array< ShippingRateItem >;
	shipping_rates: Array< CartShippingPackageShippingRate >;
}

export interface CartShippingAddress extends BaseAddress, FirstNameLastName {
	company: string;
	phone: string;
}

export interface CartBillingAddress extends CartShippingAddress {
	email: string;
}

export interface CartImageItem {
	id: number;
	src: string;
	thumbnail: string;
	srcset: string;
	sizes: string;
	name: string;
	alt: string;
}

export interface CartVariationItem {
	attribute: string;
	value: string;
}

export interface CartItemPrices extends CurrencyInfo {
	price: string;
	regular_price: string;
	sale_price: string;
	price_range: null | { min_amount: string; max_amount: string };
	raw_prices: {
		precision: number;
		price: string;
		regular_price: string;
		sale_price: string;
	};
}

export interface CartItemTotals extends CurrencyInfo {
	line_subtotal: string;
	line_subtotal_tax: string;
	line_total: string;
	line_total_tax: string;
}

export type CatalogVisibility = 'catalog' | 'hidden' | 'search' | 'visible';

export interface CartItem {
	key: string;
	id: number;
	quantity: number;
	catalog_visibility: CatalogVisibility;
	quantity_limits: {
		minimum: number;
		maximum: number;
		multiple_of: number;
		editable: boolean;
	};
	name: string;
	summary: string;
	short_description: string;
	description: string;
	sku: string;
	low_stock_remaining: null | number;
	backorders_allowed: boolean;
	show_backorder_badge: boolean;
	sold_individually: boolean;
	permalink: string;
	images: Array< CartImageItem >;
	variation: Array< CartVariationItem >;
	prices: CartItemPrices;
	totals: CartItemTotals;
	extensions: ExtensionsData;
	item_data: ProductResponseItemData[];
}

export interface CartTotalsTaxLineItem {
	name: string;
	price: string;
	rate: string;
}

export interface CartFeeItemTotals extends CurrencyInfo {
	total: string;
	total_tax: string;
}

export interface CartFeeItem {
	id: string;
	name: string;
	totals: CartFeeItemTotals;
}

export interface CartTotals extends CurrencyInfo {
	total_items: string;
	total_items_tax: string;
	total_fees: string;
	total_fees_tax: string;
	total_discount: string;
	total_discount_tax: string;
	total_shipping: string;
	total_shipping_tax: string;
	total_price: string;
	total_tax: string;
	tax_lines: Array< CartTotalsTaxLineItem >;
}

export interface CartErrorItem {
	code: string;
	message: string;
}

export interface Cart extends Record< string, unknown > {
	coupons: Array< CartCouponItem >;
	shippingRates: Array< CartShippingRate >;
	shippingAddress: CartShippingAddress;
	billingAddress: CartBillingAddress;
	items: Array< CartItem >;
	itemsCount: number;
	itemsWeight: number;
	crossSells: Array< ProductResponseItem >;
	needsPayment: boolean;
	needsShipping: boolean;
	hasCalculatedShipping: boolean;
	fees: Array< CartFeeItem >;
	totals: CartTotals;
	errors: Array< CartErrorItem >;
	paymentMethods: Array< string >;
	paymentRequirements: Array< string >;
	extensions: ExtensionsData;
}
export interface CartMeta {
	updatingCustomerData: boolean;
	updatingSelectedRate: boolean;
	isCartDataStale: boolean;
	applyingCoupon: string;
	removingCoupon: string;
}
export interface ExtensionCartUpdateArgs {
	data: Record< string, unknown >;
	namespace: string;
}

export interface BillingAddressShippingAddress {
	billing_address: Partial< CartBillingAddress >;
	shipping_address: Partial< CartShippingAddress >;
}
type-defs/checkout.ts000064400000001447151550203500010623 0ustar00/**
 * External dependencies
 */
import type { ShippingAddress, BillingAddress } from '@woocommerce/settings';

/**
 * Internal dependencies
 */
import type { ApiErrorResponse } from './api-error-response';

export interface CheckoutResponseSuccess {
	billing_address: BillingAddress;
	customer_id: number;
	customer_note: string;
	extensions: Record< string, unknown >;
	order_id: number;
	order_key: string;
	payment_method: string;
	payment_result: {
		payment_details: Record< string, string > | Record< string, never >;
		payment_status: 'success' | 'failure' | 'pending' | 'error';
		redirect_url: string;
	};
	shipping_address: ShippingAddress;
	status: string;
}

export type CheckoutResponseError = ApiErrorResponse;

export type CheckoutResponse = CheckoutResponseSuccess | CheckoutResponseError;
type-defs/contexts.js000064400000032053151550203500010650 0ustar00// Disabling eslint here as we are moving to typescript and this file will soon be redundant
/* eslint-disable jsdoc/valid-types */
/**
 * @typedef {import('./billing').BillingData} BillingData
 * @typedef {import('./shipping').ShippingAddress} CartShippingAddress
 * @typedef {import('./cart').CartData} CartData
 * @typedef {import('./checkout').CheckoutDispatchActions} CheckoutDispatchActions
 * @typedef {import('./add-to-cart-form').AddToCartFormDispatchActions} AddToCartFormDispatchActions
 * @typedef {import('./add-to-cart-form').AddToCartFormEventRegistration} AddToCartFormEventRegistration
 */

/**
 * @typedef {Object} ShippingErrorStatus
 *
 * @property {boolean} isPristine        Whether the status is pristine.
 * @property {boolean} isValid           Whether the status is valid.
 * @property {boolean} hasInvalidAddress Whether the address is invalid.
 * @property {boolean} hasError          Whether an error has happened.
 */

/**
 * @typedef {Object} ShippingErrorTypes
 *
 * @property {string} NONE            No shipping error.
 * @property {string} INVALID_ADDRESS Error due to an invalid address for calculating shipping.
 * @property {string} UNKNOWN         When an unknown error has occurred in calculating/retrieving shipping rates.
 */

/**
 * A saved customer payment method object (if exists)
 *
 * @typedef {Object} CustomerPaymentMethod
 *
 * @property {Object}  method     The payment method object (varies on what it might contain)
 * @property {string}  expires    Short form of expiry for payment method.
 * @property {boolean} is_default Whether it is the default payment method of the customer or not.
 * @property {number}  tokenId    The id of the saved payment method.
 * @property {Object}  actions    Varies, actions that can be done to interact with the payment method.
 */

/**
 * @typedef {Object} ShippingDataResponse
 *
 * @property {CartShippingAddress} address The address selected for shipping.
 */

/**
 * @typedef {Object} PaymentStatusDispatchers
 *
 * @property {function(Object=)}                 started    Sets started status.
 * @property {function()}                        processing Sets processing status.
 * @property {function()}                        completed  Sets complete status.
 * @property {function(string)}                  error      Sets error status.
 * @property {function(string, Object, Object=)} failed     Sets failed status.
 * @property {function(Object=,Object=,Object=)} success    Sets success status.
 */

/**
 * @typedef {function():PaymentStatusDispatchers} PaymentStatusDispatch
 */

/**
 * @typedef {Object} CheckoutDataContext
 *
 * @property {function()}                   onSubmit                             The callback to register with the
 *                                                                               checkout submit button.
 * @property {boolean}                      isComplete                           True when checkout is complete and
 *                                                                               ready for redirect.
 * @property {boolean}                      isBeforeProcessing                   True during any observers executing
 *                                                                               logic before checkout processing
 *                                                                               (eg. validation).
 * @property {boolean}                      isAfterProcessing                    True when checkout status is
 *                                                                               AFTER_PROCESSING.
 * @property {boolean}                      isIdle                               True when the checkout state has
 *                                                                               changed and checkout has no activity.
 * @property {boolean}                      isProcessing                         True when checkout has been submitted
 *                                                                               and is being processed. Note, payment
 *                                                                               related processing happens during this
 *                                                                               state. When payment status is success,
 *                                                                               processing happens on the server.
 * @property {boolean}                      isCalculating                        True when something in the checkout is
 *                                                                               resulting in totals being calculated.
 * @property {boolean}                      hasError                             True when the checkout is in an error
 *                                                                               state. Whatever caused the error
 *                                                                               (validation/payment method) will likely
 *                                                                               have triggered a notice.
 * @property {string}                       redirectUrl                          This is the url that checkout will
 *                                                                               redirect to when it's ready.
 * @property {function(function(),number=)} onCheckoutValidationBeforeProcessing Used to register a callback that will
 *                                                                               fire when the validation of the submitted checkout
 *                                                                               data happens, before it's sent off to the
 *                                                                               server.
 * @property {function(function(),number=)} onCheckoutAfterProcessingWithSuccess Used to register a callback that will
 *                                                                               fire after checkout has been processed
 *                                                                               and there are no errors.
 * @property {function(function(),number=)} onCheckoutAfterProcessingWithError   Used to register a callback that will
 *                                                                               fire when the checkout has been
 *                                                                               processed and has an error.
 * @property {CheckoutDispatchActions}      dispatchActions                      Various actions that can be dispatched
 *                                                                               for the checkout context data.
 * @property {number}                       orderId                              This is the ID for the draft order if
 *                                                                               one exists.
 * @property {number}                       orderNotes                           Order notes introduced by the user in
 *                                                                               the checkout form.
 * @property {boolean}                      hasOrder                             True when the checkout has a draft
 *                                                                               order from the API.
 * @property {boolean}                      isCart                               When true, means the provider is
 *                                                                               providing data for the cart.
 * @property {number}                       customerId                           This is the ID of the customer the
 *                                                                               draft order belongs to.
 * @property {boolean}                      shouldCreateAccount                  Should a user account be created?
 * @property {function(boolean)}            setShouldCreateAccount               Function to update the
 *                                                                               shouldCreateAccount property.
 */

/**
 * @typedef {Object} AddToCartFormContext
 *
 * @property {Object}                         product              The product object to add to the cart.
 * @property {string}                         productType          The name of the product type.
 * @property {boolean}                        productIsPurchasable True if the product can be purchased.
 * @property {boolean}                        productHasOptions    True if the product has additional options and thus
 *                                                                 needs a cart form.
 * @property {boolean}                        supportsFormElements True if the product type supports form elements.
 * @property {boolean}                        showFormElements     True if showing a full add to cart form (enabled and
 *                                                                 supported).
 * @property {number}                         quantity             Stores the quantity being added to the cart.
 * @property {number}                         minQuantity          Min quantity that can be added to the cart.
 * @property {number}                         maxQuantity          Max quantity than can be added to the cart.
 * @property {Object}                         requestParams        List of params to send to the API.
 * @property {boolean}                        isIdle               True when the form state has changed and has no
 *                                                                 activity.
 * @property {boolean}                        isDisabled           True when the form cannot be submitted.
 * @property {boolean}                        isProcessing         True when the form has been submitted and is being
 *                                                                 processed.
 * @property {boolean}                        isBeforeProcessing   True during any observers executing logic before form
 *                                                                 processing (eg. validation).
 * @property {boolean}                        isAfterProcessing    True when form status is AFTER_PROCESSING.
 * @property {boolean}                        hasError             True when the form is in an error state. Whatever
 *                                                                 caused the error (validation/payment method) will
 *                                                                 likely have triggered a notice.
 * @property {AddToCartFormEventRegistration} eventRegistration    Event emitters that can be subscribed to.
 * @property {AddToCartFormDispatchActions}   dispatchActions      Various actions that can be dispatched for the add to
 *                                                                 cart form context data.
 */

/**
 * @typedef {Object} ValidationContextError
 *
 * @property {number}  id      Error ID.
 * @property {string}  message Error message.
 * @property {boolean} hidden  Error visibility.
 *
 */

/**
 * @typedef {Object} ValidationContext
 *
 * @property {(id:string)=>ValidationContextError} getValidationError       Return validation error for the given property.
 * @property {function(Object)}                    setValidationErrors      Receive an object of properties and  error messages as
 *                                                                          strings and adds to the validation error state.
 * @property {function(string)}                    clearValidationError     Clears a validation error for the given property name.
 * @property {function()}                          clearAllValidationErrors Clears all validation errors currently in state.
 * @property {function(string)}                    getValidationErrorId     Returns the css id for the
 *                                                                          validation error using the given inputId string.
 * @property {function(string)}                    hideValidationError      Sets the hidden prop of a specific error to true.
 * @property {function(string)}                    showValidationError      Sets the hidden prop of a specific error to false.
 * @property {function()}                          showAllValidationErrors  Sets the hidden prop of all errors to false.
 * @property {boolean}                             hasValidationErrors      True if there is at least one error.
 */

/**
 * @typedef StoreNoticeObject
 *
 * @property {string} type   The type of notice.
 * @property {string} status The status of the notice.
 * @property {string} id     The id of the notice.
 */

/**
 * @typedef {Object} ContainerWidthContext
 *
 * @property {boolean} hasContainerWidth  True once the class name has been derived.
 * @property {string}  containerClassName The class name derived from the width of the container.
 * @property {boolean} isMobile           True if the derived container width is mobile.
 * @property {boolean} isSmall            True if the derived container width is small.
 * @property {boolean} isMedium           True if the derived container width is medium.
 * @property {boolean} isLarge            True if the derived container width is large.
 */

export {};
type-defs/contexts.ts000064400000001050151550203500010653 0ustar00export type ValidationContextError = {
	message: string;
	hidden: boolean;
};

export type ValidationData = {
	hasValidationErrors: boolean;
	getValidationError: ( validationErrorId: string ) => ValidationContextError;
	clearValidationError: ( validationErrorId: string ) => void;
	hideValidationError: ( validationErrorId: string ) => void;
	setValidationErrors: (
		errors: Record< string, ValidationContextError >
	) => void;
};

export enum SHIPPING_ERROR_TYPES {
	NONE = 'none',
	INVALID_ADDRESS = 'invalid_address',
	UNKNOWN = 'unknown_error',
}
type-defs/currency.ts000064400000004726151550203500010653 0ustar00export interface Currency {
	/**
	 * ISO 4217 Currency Code
	 */
	code: CurrencyCode;
	/**
	 * String which separates the decimals from the integer
	 */
	decimalSeparator: string;
	/**
	 * @todo Description of this currently unknown
	 */
	minorUnit: number;
	/**
	 * String to prefix the currency with.
	 *
	 * This property is generally exclusive with `suffix`.
	 */
	prefix: string;
	/**
	 * String to suffix the currency with.
	 *
	 * This property is generally exclusive with `prefix`.
	 */
	suffix: string;
	/**
	 * Currency symbol
	 */
	symbol: string; // @todo create a list of allowed currency symbols
	/**
	 * String which separates the thousands
	 */
	thousandSeparator: string;
}

export interface CurrencyResponse {
	currency_code: CurrencyCode;
	currency_symbol: string;
	currency_minor_unit: number;
	currency_decimal_separator: string;
	currency_thousand_separator: string;
	currency_prefix: string;
	currency_suffix: string;
}

export type SymbolPosition = 'left' | 'left_space' | 'right' | 'right_space';

export type CurrencyCode =
	| 'AED'
	| 'AFN'
	| 'ALL'
	| 'AMD'
	| 'ANG'
	| 'AOA'
	| 'ARS'
	| 'AUD'
	| 'AWG'
	| 'AZN'
	| 'BAM'
	| 'BBD'
	| 'BDT'
	| 'BGN'
	| 'BHD'
	| 'BIF'
	| 'BMD'
	| 'BND'
	| 'BOB'
	| 'BRL'
	| 'BSD'
	| 'BTC'
	| 'BTN'
	| 'BWP'
	| 'BYR'
	| 'BYN'
	| 'BZD'
	| 'CAD'
	| 'CDF'
	| 'CHF'
	| 'CLP'
	| 'CNY'
	| 'COP'
	| 'CRC'
	| 'CUC'
	| 'CUP'
	| 'CVE'
	| 'CZK'
	| 'DJF'
	| 'DKK'
	| 'DOP'
	| 'DZD'
	| 'EGP'
	| 'ERN'
	| 'ETB'
	| 'EUR'
	| 'FJD'
	| 'FKP'
	| 'GBP'
	| 'GEL'
	| 'GGP'
	| 'GHS'
	| 'GIP'
	| 'GMD'
	| 'GNF'
	| 'GTQ'
	| 'GYD'
	| 'HKD'
	| 'HNL'
	| 'HRK'
	| 'HTG'
	| 'HUF'
	| 'IDR'
	| 'ILS'
	| 'IMP'
	| 'INR'
	| 'IQD'
	| 'IRR'
	| 'IRT'
	| 'ISK'
	| 'JEP'
	| 'JMD'
	| 'JOD'
	| 'JPY'
	| 'KES'
	| 'KGS'
	| 'KHR'
	| 'KMF'
	| 'KPW'
	| 'KRW'
	| 'KWD'
	| 'KYD'
	| 'KZT'
	| 'LAK'
	| 'LBP'
	| 'LKR'
	| 'LRD'
	| 'LSL'
	| 'LYD'
	| 'MAD'
	| 'MDL'
	| 'MGA'
	| 'MKD'
	| 'MMK'
	| 'MNT'
	| 'MOP'
	| 'MRU'
	| 'MUR'
	| 'MVR'
	| 'MWK'
	| 'MXN'
	| 'MYR'
	| 'MZN'
	| 'NAD'
	| 'NGN'
	| 'NIO'
	| 'NOK'
	| 'NPR'
	| 'NZD'
	| 'OMR'
	| 'PAB'
	| 'PEN'
	| 'PGK'
	| 'PHP'
	| 'PKR'
	| 'PLN'
	| 'PRB'
	| 'PYG'
	| 'QAR'
	| 'RON'
	| 'RSD'
	| 'RUB'
	| 'RWF'
	| 'SAR'
	| 'SBD'
	| 'SCR'
	| 'SDG'
	| 'SEK'
	| 'SGD'
	| 'SHP'
	| 'SLL'
	| 'SOS'
	| 'SRD'
	| 'SSP'
	| 'STN'
	| 'SYP'
	| 'SZL'
	| 'THB'
	| 'TJS'
	| 'TMT'
	| 'TND'
	| 'TOP'
	| 'TRY'
	| 'TTD'
	| 'TWD'
	| 'TZS'
	| 'UAH'
	| 'UGX'
	| 'USD'
	| 'UYU'
	| 'UZS'
	| 'VEF'
	| 'VES'
	| 'VND'
	| 'VUV'
	| 'WST'
	| 'XAF'
	| 'XCD'
	| 'XOF'
	| 'XPF'
	| 'YER'
	| 'ZAR'
	| 'ZMW';
type-defs/events.ts000064400000000204151550203500010310 0ustar00export interface AddToCartEventDetail {
	// Whether cart data in the data store should be preserved.
	preserveCartData?: boolean;
}
type-defs/hocs.ts000064400000001303151550203500007741 0ustar00/**
 * External dependencies
 */
import { ErrorObject } from '@woocommerce/editor-components/error-placeholder';
import type { ProductResponseItem } from '@woocommerce/types';

export interface WithInjectedProductVariations {
	error: ErrorObject | null;
	/**
	 * The id of the currently expanded product
	 */
	expandedProduct: number | null;
	variations: Record< number, ProductResponseItem[] >;
	variationsLoading: boolean;
}

export interface WithInjectedSearchedProducts {
	error: ErrorObject | null;
	isLoading: boolean;
	onSearch: ( ( search: string ) => void ) | null;
	products: ProductResponseItem[];
	selected: number[];
}

export interface WithInjectedInstanceId {
	instanceId: string | number;
}
type-defs/hooks.js000064400000022356151550203500010131 0ustar00/**
 * @typedef {import('./cart').CartData} CartData
 * @typedef {import('./shipping').ShippingAddress} CartShippingAddress
 * @typedef {import('./contexts').StoreNoticeObject} StoreNoticeObject
 * @typedef {import('@woocommerce/type-defs/billing').BillingData} CartBillingAddress
 */

/**
 * @typedef {Object} StoreCart
 *
 * @property {Array}                cartCoupons               An array of coupons applied
 *                                                            to the cart.
 * @property {Array}                cartItems                 An array of items in the
 *                                                            cart.
 * @property {Array}                cartFees                  An array of fees in the
 *                                                            cart.
 * @property {number}               cartItemsCount            The number of items in the
 *                                                            cart.
 * @property {number}               cartItemsWeight           The weight of all items in
 *                                                            the cart.
 * @property {boolean}              cartNeedsPayment          True when the cart will
 *                                                            require payment.
 * @property {boolean}              cartNeedsShipping         True when the cart will
 *                                                            require shipping.
 * @property {Array}                cartItemErrors            Item validation errors.
 * @property {Object}               cartTotals                Cart and line total
 *                                                            amounts.
 * @property {boolean}              cartIsLoading             True when cart data is
 *                                                            being loaded.
 * @property {Array}                cartErrors                An array of errors thrown
 *                                                            by the cart.
 * @property {CartBillingAddress}   billingAddress            Billing address for the
 *                                                            cart.
 * @property {CartShippingAddress}  shippingAddress           Shipping address for the
 *                                                            cart.
 * @property {Array}                shippingRates             array of selected shipping
 *                                                            rates.
 * @property {Object}               extensions                Values provided by  *                                                      extensions.
 * @property {boolean}              shippingRatesLoading      Whether or not the
 *                                                            shipping rates are
 *                                                            being loaded.
 * @property {boolean}              cartHasCalculatedShipping Whether or not the cart has calculated shipping yet.
 * @property {Array}                paymentRequirements       List of features required from payment gateways.
 * @property {function(Object):any} receiveCart               Dispatcher to receive
 *                                                            updated cart.
 */

/**
 * @typedef {Object} StoreCartCoupon
 *
 * @property {Array}    appliedCoupons   Collection of applied coupons from the
 *                                       API.
 * @property {boolean}  isLoading        True when coupon data is being loaded.
 * @property {Function} applyCoupon      Callback for applying a coupon by code.
 * @property {Function} removeCoupon     Callback for removing a coupon by code.
 * @property {boolean}  isApplyingCoupon True when a coupon is being applied.
 * @property {boolean}  isRemovingCoupon True when a coupon is being removed.
 */

/**
 * @typedef {Object} StoreCartItemAddToCart
 *
 * @property {number}   cartQuantity  The quantity of the item in the
 *                                    cart.
 * @property {boolean}  addingToCart  Whether the cart item is still
 *                                    being added or not.
 * @property {boolean}  cartIsLoading Whether the cart is being loaded.
 * @property {Function} addToCart     Callback for adding a cart item.
 */

/**
 * @typedef {Object} CheckoutNotices
 *
 * @property {StoreNoticeObject[]} checkoutNotices       Array of notices in the
 *                                                       checkout context.
 * @property {StoreNoticeObject[]} expressPaymentNotices Array of notices in the
 *                                                       express payment context.
 * @property {StoreNoticeObject[]} paymentNotices        Array of notices in the
 *                                                       payment context.
 */

/**
 * @typedef {Object} EmitResponseTypes
 *
 * @property {string} SUCCESS To indicate a success response.
 * @property {string} FAIL    To indicate a failed response.
 * @property {string} ERROR   To indicate an error response.
 */

/**
 * @typedef {Object} NoticeContexts
 *
 * @property {string} PAYMENTS         Notices for the payments step.
 * @property {string} EXPRESS_PAYMENTS Notices for the express payments step.
 */

/* eslint-disable jsdoc/valid-types */
// Enum format below triggers the above rule even though VSCode interprets it fine.
/**
 * @typedef {NoticeContexts['PAYMENTS']|NoticeContexts['EXPRESS_PAYMENTS']} NoticeContextsEnum
 */

/**
 * @typedef {Object} EmitSuccessResponse
 *
 * @property {EmitResponseTypes['SUCCESS']} type          Should have the value of
 *                                                        EmitResponseTypes.SUCCESS.
 * @property {string}                       [redirectUrl] If the redirect url should be changed set
 *                                                        this. Note, this is ignored for some
 *                                                        emitters.
 * @property {Object}                       [meta]        Additional data returned for the success
 *                                                        response. This varies between context
 *                                                        emitters.
 */

/**
 * @typedef {Object} EmitFailResponse
 *
 * @property {EmitResponseTypes['FAIL']} type             Should have the value of
 *                                                        EmitResponseTypes.FAIL
 * @property {string}                    message          A message to trigger a notice for.
 * @property {NoticeContextsEnum}        [messageContext] What context to display any message in.
 * @property {Object}                    [meta]           Additional data returned for the fail
 *                                                        response. This varies between context
 *                                                        emitters.
 */

/**
 * @typedef {Object} EmitErrorResponse
 *
 * @property {EmitResponseTypes['ERROR']} type               Should have the value of
 *                                                           EmitResponseTypes.ERROR
 * @property {string}                     message            A message to trigger a notice for.
 * @property {boolean}                    retry              If false, then it means an
 *                                                           irrecoverable error so don't allow for
 *                                                           shopper to retry checkout (which may
 *                                                           mean either a different payment or
 *                                                           fixing validation errors).
 * @property {Object}                     [validationErrors] If provided, will be set as validation
 *                                                           errors in the validation context.
 * @property {NoticeContextsEnum}         [messageContext]   What context to display any message in.
 * @property {Object}                     [meta]             Additional data returned for the fail
 *                                                           response. This varies between context
 *                                                           emitters.
 */
/* eslint-enable jsdoc/valid-types */

/**
 * @typedef {Object} EmitResponseApi
 *
 * @property {EmitResponseTypes}        responseTypes     An object of various response types that can
 *                                                        be used in returned response objects.
 * @property {NoticeContexts}           noticeContexts    An object of various notice contexts that can
 *                                                        be used for targeting where a notice appears.
 * @property {function(Object):boolean} shouldRetry       Returns whether the user is allowed to retry
 *                                                        the payment after a failed one.
 * @property {function(Object):boolean} isSuccessResponse Returns whether the given response is of a
 *                                                        success response type.
 * @property {function(Object):boolean} isErrorResponse   Returns whether the given response is of an
 *                                                        error response type.
 * @property {function(Object):boolean} isFailResponse    Returns whether the given response is of a
 *                                                        fail response type.
 */

export {};
type-defs/hooks.ts000064400000003733151550203500010141 0ustar00/**
 * External dependencies
 */
import type { ProductResponseItem } from '@woocommerce/types';

/**
 * Internal dependencies
 */
import type {
	CartResponseErrorItem,
	CartResponseCouponItem,
	CartResponseItem,
	CartResponseFeeItem,
	CartResponseTotals,
	CartResponseShippingAddress,
	CartResponseBillingAddress,
	CartResponseShippingRate,
	CartResponse,
	CartResponseCoupons,
} from './cart-response';
import type { ApiErrorResponse } from './api-error-response';
export interface StoreCartItemQuantity {
	isPendingDelete: boolean;
	quantity: number;
	setItemQuantity: React.Dispatch< React.SetStateAction< number > >;
	removeItem: () => Promise< boolean >;
	cartItemQuantityErrors: CartResponseErrorItem[];
}

// An object exposing data and actions from/for the store api /cart/coupons endpoint.
export interface StoreCartCoupon {
	appliedCoupons: CartResponseCouponItem[];
	isLoading: boolean;
	applyCoupon: ( coupon: string ) => Promise< boolean >;
	removeCoupon: ( coupon: string ) => Promise< boolean >;
	isApplyingCoupon: boolean;
	isRemovingCoupon: boolean;
}

export interface StoreCart {
	cartCoupons: CartResponseCoupons;
	cartItems: CartResponseItem[];
	crossSellsProducts: ProductResponseItem[];
	cartFees: CartResponseFeeItem[];
	cartItemsCount: number;
	cartItemsWeight: number;
	cartNeedsPayment: boolean;
	cartNeedsShipping: boolean;
	cartItemErrors: CartResponseErrorItem[];
	cartTotals: CartResponseTotals;
	cartIsLoading: boolean;
	cartErrors: ApiErrorResponse[];
	billingAddress: CartResponseBillingAddress;
	shippingAddress: CartResponseShippingAddress;
	shippingRates: CartResponseShippingRate[];
	extensions: Record< string, unknown >;
	isLoadingRates: boolean;
	cartHasCalculatedShipping: boolean;
	paymentMethods: string[];
	paymentRequirements: string[];
	receiveCart: ( cart: CartResponse ) => void;
	receiveCartContents: ( cart: CartResponse ) => void;
}

export type Query = {
	catalog_visibility: 'catalog';
	per_page: number;
	page: number;
	orderby: string;
	order: string;
};
type-defs/index.ts000064400000001204151550203500010114 0ustar00export * from './api-error-response';
export * from './api-response';
export * from './attributes';
export * from './blocks';
export * from './cart-response';
export * from './cart';
export * from './checkout';
export * from './contexts';
export * from './currency';
export * from './events';
export * from './hocs';
export * from './hooks';
export * from './notices';
export * from './objects';
export * from './payment-method-interface';
export * from './payments';
export * from './product-response';
export * from './shipping';
export * from './stock-status';
export * from './taxes';
export * from './utils';
export * from './validation';
type-defs/notices.ts000064400000000466151550203500010462 0ustar00/**
 * External dependencies
 */
import type { Notice } from '@wordpress/notices';

export interface NoticeType extends Partial< Omit< Notice, 'status' > > {
	id: string;
	content: string;
	status: 'success' | 'error' | 'info' | 'warning' | 'default';
	isDismissible: boolean;
	context?: string | undefined;
}
type-defs/objects.ts000064400000000153151550203500010440 0ustar00export type ObjectType = Record< string, unknown >;
export type EmptyObjectType = Record< string, never >;
type-defs/payment-method-interface.ts000064400000017142151550203500013706 0ustar00/* eslint-disable @typescript-eslint/naming-convention */
/**
 * External dependencies
 */
import type PaymentMethodLabel from '@woocommerce/base-components/cart-checkout/payment-method-label';
import type PaymentMethodIcons from '@woocommerce/base-components/cart-checkout/payment-method-icons';
import type LoadingMask from '@woocommerce/base-components/loading-mask';
import type { ValidationInputError } from '@woocommerce/blocks-checkout';

/**
 * Internal dependencies
 */
import type { Currency } from './currency';
import type { CartBillingAddress, CartShippingRate } from './cart';
import type {
	emitterCallback,
	responseTypes,
	noticeContexts,
} from '../../base/context/event-emit';
import type {
	CartResponseShippingAddress,
	CartResponseCouponItem,
	CartResponseItem,
	CartResponseFeeItem,
	ExtensionsData,
} from './cart-response';
import type { SHIPPING_ERROR_TYPES } from './contexts';

export interface PreparedCartTotalItem {
	// The label for the total item.
	label: string;
	// The value for the total item.
	value: number;
}

export interface BillingDataProps {
	// All the coupons that were applied to the cart/order.
	appliedCoupons: CartResponseCouponItem[];
	// The address used for billing.
	billingData: CartBillingAddress;
	billingAddress: CartBillingAddress;
	// The total item for the cart.
	cartTotal: PreparedCartTotalItem;
	// The various subtotal amounts.
	cartTotalItems: PreparedCartTotalItem[];
	// Currency object.
	currency: Currency;
	// The customer Id the order belongs to.
	customerId: number;
	// True means that the site is configured to display prices including tax.
	displayPricesIncludingTax: boolean;
}

export interface CartDataProps {
	cartItems: CartResponseItem[];
	cartFees: CartResponseFeeItem[];
	extensions: ExtensionsData;
}

export interface CheckoutStatusProps {
	// If true then totals are being calculated in the checkout.
	isCalculating: boolean;
	// If true then the checkout has completed it's processing.
	isComplete: boolean;
	// If true then the checkout is idle (no  activity happening).
	isIdle: boolean;
	// If true then checkout is processing (finalizing) the order with the server.
	isProcessing: boolean;
}

export interface ComponentProps {
	// A wrapper component used for showing a loading state when the isLoading prop is true.
	LoadingMask: typeof LoadingMask;
	// A component used for displaying payment method icons.
	PaymentMethodIcons: typeof PaymentMethodIcons;
	// A component used for displaying payment method labels, including an icon.
	PaymentMethodLabel: typeof PaymentMethodLabel;
	// A container for holding validation errors
	ValidationInputError: typeof ValidationInputError;
}

export interface EmitResponseProps {
	// Response types that can be returned from emitter observers.
	responseTypes: typeof responseTypes;
	// Available contexts that can be returned as the value for the messageContext property on the object  returned from an emitter observer.
	noticeContexts: typeof noticeContexts;
}

export interface EventRegistrationProps {
	// Deprecated in favour of onCheckoutFail.
	onCheckoutAfterProcessingWithError: ReturnType< typeof emitterCallback >;
	// Deprecated in favour of onCheckoutSuccess.
	onCheckoutAfterProcessingWithSuccess: ReturnType< typeof emitterCallback >;
	// Used to subscribe callbacks firing before checkout begins processing.
	onCheckoutBeforeProcessing: ReturnType< typeof emitterCallback >;
	// Used to register a callback that will fire if the api call to /checkout is successful
	onCheckoutSuccess: ReturnType< typeof emitterCallback >;
	// Used to register a callback that will fire if the api call to /checkout fails
	onCheckoutFail: ReturnType< typeof emitterCallback >;
	// Used to register a callback that will fire when the checkout performs validation on the form
	onCheckoutValidation: ReturnType< typeof emitterCallback >;
	// Deprecated in favour of onCheckoutValidation.
	onCheckoutValidationBeforeProcessing: ReturnType< typeof emitterCallback >;
	// Deprecated in favour of onPaymentSetup
	onPaymentProcessing: ReturnType< typeof emitterCallback >;
	// Event registration callback for registering observers for the payment setup event.
	onPaymentSetup: ReturnType< typeof emitterCallback >;
	// Used to subscribe callbacks that will fire when retrieving shipping rates failed.
	onShippingRateFail: ReturnType< typeof emitterCallback >;
	// Used to subscribe callbacks that will fire after selecting a shipping rate unsuccessfully.
	onShippingRateSelectFail: ReturnType< typeof emitterCallback >;
	// Used to subscribe callbacks that will fire after selecting a shipping rate successfully.
	onShippingRateSelectSuccess: ReturnType< typeof emitterCallback >;
	// Used to subscribe callbacks that will fire when shipping rates for a given address have been received successfully.
	onShippingRateSuccess: ReturnType< typeof emitterCallback >;
}

export interface ShippingDataProps {
	// True when rates are being selected.
	isSelectingRate: boolean;
	// True if cart requires shipping.
	needsShipping: boolean;
	// An object containing package IDs as the key and selected rate as the value (rate ids).
	selectedRates: Record< string, unknown >;
	// A function for setting selected rates (receives id).
	setSelectedRates: (
		newShippingRateId: string,
		packageId: string | number
	) => unknown;
	// A function for setting the shipping address.
	setShippingAddress: ( data: CartResponseShippingAddress ) => void;
	// The current set shipping address.
	shippingAddress: CartResponseShippingAddress;
	// All the available shipping rates.
	shippingRates: CartShippingRate[];
	// Whether the rates are loading or not.
	shippingRatesLoading: boolean;
}

export interface ShippingStatusProps {
	// Current error status for shipping.
	shippingErrorStatus: {
		// Whether the status is pristine.
		isPristine: boolean;
		// Whether the status is valid.
		isValid: boolean;
		// Whether the address is invalid.
		hasInvalidAddress: boolean;
		// Whether an error has happened.
		hasError: boolean;
	};
	// An object containing all the possible types for shipping error status.
	shippingErrorTypes: SHIPPING_ERROR_TYPES;
}

export type PaymentMethodInterface = {
	// Indicates what the active payment method is.
	activePaymentMethod: string;
	// Various billing data items.
	billing: BillingDataProps;
	// Data exposed from the cart including items, fees, and any registered extension data. Note that this data should
	// be treated as immutable (should not be modified/mutated) or it will result in errors in your application.
	cartData: CartDataProps;
	// The current checkout status exposed as various boolean state.
	checkoutStatus: CheckoutStatusProps;
	// Components exposed to payment methods for use.
	components: ComponentProps;
	// Utilities for usage in event observer response objects.
	emitResponse: EmitResponseProps;
	// Various event registration helpers for subscribing callbacks for events.
	eventRegistration: EventRegistrationProps;
	// Used to trigger checkout processing.
	onSubmit: () => void;
	// Various payment status helpers.
	paymentStatus: {
		isPristine: boolean;
		isIdle: boolean;
		isStarted: boolean;
		isProcessing: boolean;
		isFinished: boolean;
		hasError: boolean;
		hasFailed: boolean;
		isSuccessful: boolean;
		isDoingExpressPayment: boolean;
	};
	// Deprecated. For setting an error (error message string) for express payment methods. Does not change payment status.
	setExpressPaymentError: ( errorMessage?: string ) => void;
	// Various data related to shipping.
	shippingData: ShippingDataProps;
	// Various shipping status helpers.
	shippingStatus: ShippingStatusProps;
	// A boolean which indicates whether the shopper has checked the save payment method checkbox.
	shouldSavePayment: boolean;
};
type-defs/payments.ts000064400000013330151550203500010650 0ustar00/**
 * External dependencies
 */
import type { ReactNode } from 'react';
import { ApiErrorResponse } from '@woocommerce/types';

/**
 * Internal dependencies
 */
import type { CartTotals } from './cart';
import type {
	CartResponse,
	CartResponseBillingAddress,
	CartResponseShippingAddress,
} from './cart-response';
import type { EmptyObjectType } from './objects';
import type { CheckoutResponseSuccess } from './checkout';

/**
 * The shape of objects on the `globalPaymentMethods` object from `allSettings`.
 */
export interface GlobalPaymentMethod {
	id: string | number;
	title: string;
	description: string;
}

export interface SupportsConfiguration {
	showSavedCards?: boolean;
	showSaveOption?: boolean;
	features?: string[];
	// Deprecated, in favour of showSavedCards and showSaveOption
	savePaymentInfo?: boolean;
}

// we assign a value in the class for supports.features
export interface Supports extends SupportsConfiguration {
	features: string[];
}

export interface CanMakePaymentArgument {
	cart: CanMakePaymentArgumentCart;
	cartTotals: CartTotals;
	cartNeedsShipping: boolean;
	billingData: CartResponseBillingAddress; // This needs to stay as billingData as third parties already use this key
	shippingAddress: CartResponseShippingAddress;
	billingAddress: CartResponseBillingAddress;
	selectedShippingMethods: Record< string, unknown >;
	paymentRequirements: string[];
	paymentMethods: string[];
}

export interface CanMakePaymentArgumentCart {
	billingAddress: CartResponse[ 'billing_address' ];
	billingData: CartResponse[ 'billing_address' ];
	cartCoupons: CartResponse[ 'coupons' ];
	cartErrors: ApiErrorResponse[];
	cartFees: CartResponse[ 'fees' ];
	cartHasCalculatedShipping: CartResponse[ 'has_calculated_shipping' ];
	cartIsLoading: boolean;
	cartItemErrors: CartResponse[ 'errors' ];
	cartItems: CartResponse[ 'items' ];
	cartItemsCount: CartResponse[ 'items_count' ];
	cartItemsWeight: CartResponse[ 'items_weight' ];
	cartNeedsPayment: CartResponse[ 'needs_payment' ];
	cartNeedsShipping: CartResponse[ 'needs_shipping' ];
	cartTotals: CartResponse[ 'totals' ];
	extensions: CartResponse[ 'extensions' ];
	crossSellsProducts: CartResponse[ 'cross_sells' ];
	isLoadingRates: boolean;
	paymentRequirements: CartResponse[ 'payment_requirements' ];
	receiveCart: ( response: CartResponse ) => void;
	shippingAddress: CartResponse[ 'shipping_address' ];
	shippingRates: CartResponse[ 'shipping_rates' ];
}

export type CanMakePaymentReturnType =
	| boolean
	| Promise< boolean | { error: { message: string } } >;

export type CanMakePaymentCallback = (
	cartData: CanMakePaymentArgument
) => CanMakePaymentReturnType;

export type CanMakePaymentExtensionCallback = (
	cartData: CanMakePaymentArgument
) => boolean;

export interface PaymentMethodIcon {
	id: string;
	src: string | null;
	alt: string;
}

export type PaymentMethodIcons = ( PaymentMethodIcon | string )[];

export interface PaymentMethodConfiguration {
	// A unique string to identify the payment method client side.
	name: string;
	// A react node for your payment method UI.
	content: ReactNode;
	// A react node to display a preview of your payment method in the editor.
	edit: ReactNode;
	// A callback to determine whether the payment method should be shown in the checkout.
	canMakePayment: CanMakePaymentCallback;
	// A unique string to represent the payment method server side. If not provided, defaults to name.
	paymentMethodId?: string;
	// Object that describes various features provided by the payment method.
	supports: SupportsConfiguration;
	// Array of card types (brands) supported by the payment method.
	icons?: null | PaymentMethodIcons;
	// A react node that will be used as a label for the payment method in the checkout.
	label: ReactNode;
	// An accessibility label. Screen readers will output this label when the payment method is selected.
	ariaLabel: string;
	// Optionally customize the label text for the checkout submit (`Place Order`) button.
	placeOrderButtonLabel?: string;
	// A React node that contains logic handling any processing your payment method has to do with saved payment methods if your payment method supports them
	savedTokenComponent?: ReactNode | null;
}

export type ExpressPaymentMethodConfiguration = Omit<
	PaymentMethodConfiguration,
	'icons' | 'label' | 'ariaLabel' | 'placeOrderButtonLabel'
>;

export type PaymentMethods =
	| Record< string, PaymentMethodConfigInstance >
	| EmptyObjectType;

/**
 * Used to represent payment methods in a context where storing objects is not allowed, i.e. in data stores.
 */
export type PlainPaymentMethods = Record< string, { name: string } >;

/**
 * Used to represent payment methods in a context where storing objects is not allowed, i.e. in data stores.
 */
export type PlainExpressPaymentMethods = PlainPaymentMethods;

export type ExpressPaymentMethods =
	| Record< string, ExpressPaymentMethodConfigInstance >
	| EmptyObjectType;

export interface PaymentMethodConfigInstance {
	name: string;
	content: ReactNode;
	edit: ReactNode;
	paymentMethodId?: string;
	supports: Supports;
	icons: null | PaymentMethodIcons;
	label: ReactNode;
	ariaLabel: string;
	placeOrderButtonLabel?: string;
	savedTokenComponent?: ReactNode | null;
	canMakePaymentFromConfig: CanMakePaymentCallback;
	canMakePayment: CanMakePaymentCallback;
}

export interface ExpressPaymentMethodConfigInstance {
	name: string;
	content: ReactNode;
	edit: ReactNode;
	paymentMethodId?: string;
	placeOrderButtonLabel?: string;
	supports: Supports;
	canMakePaymentFromConfig: CanMakePaymentCallback;
	canMakePayment: CanMakePaymentCallback;
}

export interface PaymentResult {
	message: string;
	paymentStatus:
		| CheckoutResponseSuccess[ 'payment_result' ][ 'payment_status' ]
		| 'not set';
	paymentDetails: Record< string, string > | Record< string, never >;
	redirectUrl: string;
}
type-defs/product-response.ts000064400000004054151550203500012327 0ustar00/**
 * Internal dependencies
 */
import type { CurrencyResponse } from './currency';

export interface ProductResponseItemPrices extends CurrencyResponse {
	price: string;
	regular_price: string;
	sale_price: string;
	price_range: null | { min_amount: string; max_amount: string };
}

export interface ProductResponseItemBaseData {
	value: string;
	display?: string;
	hidden?: boolean;
	className?: string;
}

export type ProductResponseItemData = ProductResponseItemBaseData &
	( { key: string; name?: never } | { key?: never; name: string } );

export interface ProductResponseImageItem {
	id: number;
	src: string;
	thumbnail: string;
	srcset: string;
	sizes: string;
	name: string;
	alt: string;
}

export interface ProductResponseTermItem {
	default?: boolean;
	id: number;
	name: string;
	slug: string;
	link?: string;
}

export interface ProductResponseAttributeItem {
	id: number;
	name: string;
	taxonomy: string;
	has_variations: boolean;
	terms: Array< ProductResponseTermItem >;
}

export interface ProductResponseVariationsItem {
	id: number;
	attributes: Array< ProductResponseVariationAttributeItem >;
}

export interface ProductResponseVariationAttributeItem {
	name: string;
	value: string;
}

export interface ProductResponseItem {
	id: number;
	name: string;
	parent: number;
	type: string;
	variation: string;
	permalink: string;
	sku: string;
	short_description: string;
	description: string;
	on_sale: boolean;
	prices: ProductResponseItemPrices;
	price_html: string;
	average_rating: string;
	review_count: number;
	images: Array< ProductResponseImageItem >;
	categories: Array< ProductResponseTermItem >;
	tags: Array< ProductResponseTermItem >;
	attributes: Array< ProductResponseAttributeItem >;
	variations: Array< ProductResponseVariationsItem >;
	has_options: boolean;
	is_purchasable: boolean;
	is_in_stock: boolean;
	is_on_backorder: boolean;
	low_stock_remaining: null | number;
	sold_individually: boolean;
	add_to_cart: {
		text: string;
		description: string;
		url: string;
		minimum: number;
		maximum: number;
		multiple_of: number;
	};
	slug: string;
}
type-defs/settings.js000064400000005770151550203500010647 0ustar00/**
 * @typedef {Object} WooCommerceSiteCurrency
 *
 * @property {string} code              The ISO code for the currency.
 * @property {number} precision         The precision (decimal places).
 * @property {string} symbol            The symbol for the currency (eg '$')
 * @property {string} symbolPosition    The position for the symbol ('left',
 *                                      or 'right')
 * @property {string} decimalSeparator  The string used for the decimal
 *                                      separator.
 * @property {string} thousandSeparator The string used for the thousands
 *                                      separator.
 * @property {string} priceFormat       The format string use for displaying
 *                                      an amount in this currency.
 */

/**
 * @typedef {Object} WooCommerceSiteLocale
 *
 * @property {string}        siteLocale    The locale string for the current
 *                                         site.
 * @property {string}        userLocale    The locale string for the current
 *                                         user.
 * @property {Array<string>} weekdaysShort An array of short weekday strings
 *                                         in the current user's locale.
 */

/**
 * @typedef {Object} WooCommerceSharedSettings
 *
 * @property {string}                  adminUrl         The url for the current
 *                                                      site's dashboard.
 * @property {Object}                  countries        An object of countries
 *                                                      where the keys are
 *                                                      Country codes and values
 *                                                      are country names
 *                                                      localized for the site's
 *                                                      current language.
 * @property {WooCommerceSiteCurrency} currency         The current site
 *                                                      currency object.
 * @property {string}                  defaultDateRange The default date range
 *                                                      query string to use.
 * @property {WooCommerceSiteLocale}   locale           Locale information for
 *                                                      the site.
 * @property {Object}                  orderStatuses    An object of order
 *                                                      statuses indexed by
 *                                                      status key and localized
 *                                                      status value.
 * @property {string}                  siteTitle        The current title of the
 *                                                      site.
 * @property {string}                  wcAssetUrl       The url to the assets
 *                                                      directory for the
 *                                                      WooCommerce plugin.
 */

export {};
type-defs/shipping.js000064400000001255151550203500010622 0ustar00/**
 * @typedef {Object} ShippingAddress
 *
 * @property {string} first_name First name of recipient
 * @property {string} last_name  Last name of recipient
 * @property {string} company    Company name for the shipping address
 * @property {string} address_1  First line of the shipping address
 * @property {string} address_2  Second line of the shipping address
 * @property {string} city       The city of the shipping address
 * @property {string} state      The state of the shipping address (ISO or name)
 * @property {string} postcode   The postal or zip code for the shipping address
 * @property {string} country    The country for the shipping address (ISO)
 */

export {};
type-defs/shipping.ts000064400000000520151550203500010626 0ustar00/**
 * External dependencies
 */
import type { ReactElement } from 'react';

export interface PackageRateOption {
	label: string;
	value: string;
	description?: string | ReactElement | undefined;
	secondaryLabel?: string | ReactElement | undefined;
	secondaryDescription?: string | ReactElement | undefined;
	id?: string | undefined;
}
type-defs/stock-status.ts000064400000000214151550203500011451 0ustar00export type StockStatus = 'instock' | 'outofstock' | 'onbackorder';

export type StockStatusOptions = {
	[ key in StockStatus ]: string;
};
type-defs/taxes.ts000064400000000162151550203500010133 0ustar00export type TaxRate = {
	country: string;
	rate: string;
	name: string;
	shipping: boolean;
	priority: number;
};
type-defs/trim-html.d.ts000064400000001630151550203500011147 0ustar00interface Opts {
	/**
	 * Character limit
	 *
	 * @default 100
	 */
	limit: number;
	/**
	 * Link to full content
	 *
	 * @default ''
	 */
	moreLink: string;
	/**
	 * Text for the link to the full content
	 *
	 * @default 'ยป'
	 */
	moreText: string;
	/**
	 * Whether to strip or preserve HTML tags
	 *
	 * @default true
	 */
	preserveTags: boolean;
	/**
	 * Whether to strip or preserve white space
	 *
	 * @default false
	 */
	preserveWhiteSpace: boolean;
	/**
	 * Suffix to add at the end of the trimmed text
	 */
	suffix: string;
	/**
	 * Break text if limit is reached within the boundaries of a word
	 *
	 * @default false
	 */
	wordBreak: boolean;
}

interface TrimResult {
	/**
	 * The trimmed HTML
	 */
	html: string;
	/**
	 * Whether the trimming was necessary
	 */
	more: boolean;
}

declare module 'trim-html' {
	export default function trimHtml(
		html: string,
		options: Partial< Opts >
	): TrimResult;
}
type-defs/utils.ts000064400000000605151550203500010151 0ustar00export type Dictionary = Record< string, string >;

/**
 * Allow for the entire object to be passed, with only some properties
 * required.
 */
export type LooselyMustHave< T, K extends keyof T > = Partial< T > &
	Pick< T, K >;

export type Require< T, K extends keyof T > = T & {
	[ P in K ]-?: T[ K ];
};

export type HTMLElementEvent< T extends HTMLElement > = Event & {
	target: T;
};
type-defs/validation.ts000064400000001047151550203500011144 0ustar00/**
 * An interface to describe the validity of a Checkout field. This is what will be stored in the wc/store/validation
 * data store.
 */
export interface FieldValidationStatus {
	/**
	 * The message to display to the user.
	 */
	message: string;
	/**
	 * Whether this validation error should be hidden. Note, hidden errors still prevent checkout. Adding a hidden error
	 * allows required fields to be validated, but not show the error to the user until they interact with the input
	 * element, or try to submit the form.
	 */
	hidden: boolean;
}
type-guards/address.ts000064400000001174151550203500011004 0ustar00/**
 * External dependencies
 */
import type { BillingAddress, ShippingAddress } from '@woocommerce/settings';
import { objectHasProp } from '@woocommerce/types';

export const isShippingAddress = (
	address: unknown
): address is ShippingAddress => {
	const keys = [
		'first_name',
		'last_name',
		'company',
		'address_1',
		'address_2',
		'city',
		'state',
		'postcode',
		'country',
		'phone',
	];
	return keys.every( ( key ) => objectHasProp( address, key ) );
};
export const isBillingAddress = (
	address: unknown
): address is BillingAddress => {
	return isShippingAddress( address ) && objectHasProp( address, 'email' );
};
type-guards/api-error-response.ts000064400000000605151550203500013111 0ustar00/**
 * Internal dependencies
 */
import { isObject, objectHasProp } from './object';
import type { ApiErrorResponse } from '../type-defs';

// Type guard for ApiErrorResponse.
export const isApiErrorResponse = (
	response: unknown
): response is ApiErrorResponse => {
	return (
		isObject( response ) &&
		objectHasProp( response, 'code' ) &&
		objectHasProp( response, 'message' )
	);
};
type-guards/attributes.ts000064400000002562151550203500011547 0ustar00/**
 * Internal dependencies
 */
import type { AttributeTerm, AttributeQuery } from '../type-defs';
import { objectHasProp } from './object';

export const isAttributeTerm = ( term: unknown ): term is AttributeTerm => {
	return (
		objectHasProp( term, 'count' ) &&
		objectHasProp( term, 'description' ) &&
		objectHasProp( term, 'id' ) &&
		objectHasProp( term, 'name' ) &&
		objectHasProp( term, 'parent' ) &&
		objectHasProp( term, 'slug' ) &&
		typeof term.count === 'number' &&
		typeof term.description === 'string' &&
		typeof term.id === 'number' &&
		typeof term.name === 'string' &&
		typeof term.parent === 'number' &&
		typeof term.slug === 'string'
	);
};

export const isAttributeTermCollection = (
	terms: unknown
): terms is AttributeTerm[] => {
	return Array.isArray( terms ) && terms.every( isAttributeTerm );
};

export const isAttributeQuery = ( query: unknown ): query is AttributeQuery => {
	return (
		objectHasProp( query, 'attribute' ) &&
		objectHasProp( query, 'operator' ) &&
		objectHasProp( query, 'slug' ) &&
		typeof query.attribute === 'string' &&
		typeof query.operator === 'string' &&
		Array.isArray( query.slug ) &&
		query.slug.every( ( slug ) => typeof slug === 'string' )
	);
};

export const isAttributeQueryCollection = (
	queries: unknown
): queries is AttributeQuery[] => {
	return Array.isArray( queries ) && queries.every( isAttributeQuery );
};
type-guards/boolean.ts000064400000000147151550203500010775 0ustar00export const isBoolean = ( term: unknown ): term is boolean => {
	return typeof term === 'boolean';
};
type-guards/cart-response-totals.ts000064400000002200151550203500013437 0ustar00/**
 * Internal dependencies
 */
import type { CartResponseTotals } from '../type-defs';
import { isObject } from './object';

// It is the only way to create a type that contains all the object's keys and gets type-checking.
// This is useful because we want to check that the keys object ALWAYS contains all the object's keys.
// https://stackoverflow.com/questions/52028791/make-a-generic-type-arraykeyof-t-require-all-keys-of-t

type CartResponseTotalsKeys = Record< keyof CartResponseTotals, 0 >;

export const isCartResponseTotals = (
	value: unknown
): value is CartResponseTotals => {
	if ( ! isObject( value ) ) {
		return false;
	}

	const keys: CartResponseTotalsKeys = {
		total_items: 0,
		total_items_tax: 0,
		total_fees: 0,
		total_fees_tax: 0,
		total_discount: 0,
		total_discount_tax: 0,
		total_shipping: 0,
		total_shipping_tax: 0,
		total_price: 0,
		total_tax: 0,
		tax_lines: 0,
		currency_code: 0,
		currency_symbol: 0,
		currency_minor_unit: 0,
		currency_decimal_separator: 0,
		currency_thousand_separator: 0,
		currency_prefix: 0,
		currency_suffix: 0,
	};

	return Object.keys( keys ).every( ( key ) => key in value );
};
type-guards/empty.ts000064400000000373151550203500010515 0ustar00export const isEmpty = ( value: unknown ): boolean => {
	return (
		value === null ||
		value === undefined ||
		( typeof value === 'object' && Object.keys( value ).length === 0 ) ||
		( typeof value === 'string' && value.trim().length === 0 )
	);
};
type-guards/error.ts000064400000000137151550203500010506 0ustar00export const isError = ( term: unknown ): term is Error => {
	return term instanceof Error;
};
type-guards/function.ts000064400000000264151550203500011203 0ustar00// eslint-disable-next-line @typescript-eslint/ban-types
export const isFunction = < T extends Function, U >(
	term: T | U
): term is T => {
	return typeof term === 'function';
};
type-guards/index.ts000064400000000566151550203500010472 0ustar00export * from './boolean';
export * from './cart-response-totals';
export * from './error';
export * from './function';
export * from './null';
export * from './number';
export * from './empty';
export * from './object';
export * from './string';
export * from './attributes';
export * from './ratings';
export * from './stock-status';
export * from './api-error-response';
type-guards/null.ts000064400000000133151550203500010323 0ustar00export const isNull = < T >( term: T | null ): term is null => {
	return term === null;
};
type-guards/number.ts000064400000000154151550203500010644 0ustar00export const isNumber = < U >( term: number | U ): term is number => {
	return typeof term === 'number';
};
type-guards/object.ts000064400000001227151550203500010624 0ustar00/**
 * Internal dependencies
 */

import { isNull } from './null';

export const isObject = < T extends Record< string, unknown >, U >(
	term: T | U
): term is NonNullable< T > => {
	return (
		! isNull( term ) &&
		term instanceof Object &&
		term.constructor === Object
	);
};

export function objectHasProp< P extends PropertyKey >(
	target: unknown,
	property: P
): target is { [ K in P ]: unknown } {
	// The `in` operator throws a `TypeError` for non-object values.
	return isObject( target ) && property in target;
}

export const isEmptyObject = < T extends { [ key: string ]: unknown } >(
	object: T
) => {
	return Object.keys( object ).length === 0;
};
type-guards/observers.ts000064400000000575151550203500011375 0ustar00/**
 * External dependencies
 */
import { ObserverResponse } from '@woocommerce/base-context';
import { isObject, objectHasProp } from '@woocommerce/types';

/**
 * Whether the passed object is an ObserverResponse.
 */
export const isObserverResponse = (
	response: unknown
): response is ObserverResponse => {
	return isObject( response ) && objectHasProp( response, 'type' );
};
type-guards/ratings.ts000064400000000360151550203500011022 0ustar00type Rating = '1' | '2' | '3' | '4' | '5';

export const isRatingQueryCollection = (
	value: unknown
): value is Rating[] => {
	return (
		Array.isArray( value ) &&
		value.every( ( v ) => [ '1', '2', '3', '4', '5' ].includes( v ) )
	);
};
type-guards/stock-status.ts000064400000001130151550203500012013 0ustar00/**
 * Internal dependencies
 */
import type { StockStatus, StockStatusOptions } from '../type-defs';
import { isObject } from './object';

export const isStockStatusQueryCollection = (
	value: unknown
): value is StockStatus[] => {
	return (
		Array.isArray( value ) &&
		value.every( ( v ) =>
			[ 'instock', 'outofstock', 'onbackorder' ].includes( v )
		)
	);
};

export const isStockStatusOptions = (
	value: unknown
): value is StockStatusOptions => {
	return (
		isObject( value ) &&
		Object.keys( value ).every( ( v ) =>
			[ 'instock', 'outofstock', 'onbackorder' ].includes( v )
		)
	);
};
type-guards/string.ts000064400000000154151550203500010662 0ustar00export const isString = < U >( term: string | U ): term is string => {
	return typeof term === 'string';
};
type-guards/test/empty.ts000064400000001271151550203500011472 0ustar00/**
 * External dependencies
 */
import { isEmpty } from '@woocommerce/types';

describe( 'Testing isEmpty()', () => {
	it( 'Correctly handles null', () => {
		expect( isEmpty( null ) ).toBe( true );
	} );
	it( 'Correctly handles undefined', () => {
		expect( isEmpty( undefined ) ).toBe( true );
	} );
	it( 'Correctly handles empty objects', () => {
		expect( isEmpty( {} ) ).toBe( true );
	} );
	it( 'Correctly handles empty arrays', () => {
		expect( isEmpty( [] ) ).toBe( true );
	} );
	it( 'Correctly handles empty strings', () => {
		expect( isEmpty( '' ) ).toBe( true );
	} );
	it( 'Correctly handles object with values', () => {
		expect( isEmpty( { a: '1' } ) ).toBe( false );
	} );
} );
type-guards/test/index.ts000064400000004720151550203500011445 0ustar00/**
 * External dependencies
 */
import { isObject } from '@woocommerce/types';

/**
 * Internal dependencies
 */
import { isBillingAddress, isShippingAddress } from '../address';

describe( 'type-guards', () => {
	describe( 'Testing isObject()', () => {
		it( 'Correctly identifies an object', () => {
			expect( isObject( {} ) ).toBe( true );
			expect( isObject( { test: 'object' } ) ).toBe( true );
		} );
		it( 'Correctly rejects object-like things', () => {
			expect( isObject( [] ) ).toBe( false );
			expect( isObject( null ) ).toBe( false );
		} );
	} );

	describe( 'testing isShippingAddress()', () => {
		it( 'Correctly identifies a shipping address object', () => {
			expect( isShippingAddress( {} ) ).toBe( false );
			expect( isShippingAddress( { test: 'object' } ) ).toBe( false );

			const shippingAddress = {
				first_name: 'John',
				last_name: 'Doe',
				company: 'ACME',
				address_1: '123 Main St',
				address_2: 'Suite 1',
				city: 'Anytown',
				state: 'CA',
				postcode: '12345',
				country: 'US',
				phone: '555-555-5555',
			};
			expect( isShippingAddress( shippingAddress ) ).toBe( true );
		} );

		it( 'Correctly rejects non-shipping address objects', () => {
			const nonShippingAddress = {
				first_name: 'John',
				last_name: 'Doe',
				company: 'ACME',
				address_1: '123 Main St',
				city: 'Anytown',
				state: 'CA',
				postcode: '12345',
				country: 'US',
				phone: '555-555-5555',
				email: '',
			};
			expect( isShippingAddress( nonShippingAddress ) ).toBe( false );
		} );
	} );
	describe( 'testing isBillingAddress()', () => {
		it( 'Correctly identifies a shipping address object', () => {
			expect( isBillingAddress( {} ) ).toBe( false );
			expect( isBillingAddress( { test: 'object' } ) ).toBe( false );

			const billingAddress = {
				first_name: 'John',
				last_name: 'Doe',
				company: 'ACME',
				address_1: '123 Main St',
				address_2: 'Suite 1',
				city: 'Anytown',
				state: 'CA',
				postcode: '12345',
				country: 'US',
				phone: '555-555-5555',
				email: 'jon@doe.com',
			};
			expect( isBillingAddress( billingAddress ) ).toBe( true );
		} );

		it( 'Correctly rejects non-billing address objects', () => {
			const nonBillingAddress = {
				first_name: 'John',
				last_name: 'Doe',
				company: 'ACME',
				address_1: '123 Main St',
				city: 'Anytown',
				state: 'CA',
				country: 'US',
				phone: '555-555-5555',
				email: '',
			};
			expect( isBillingAddress( nonBillingAddress ) ).toBe( false );
		} );
	} );
} );
type-guards/test/object.ts000064400000001412151550203500011577 0ustar00/**
 * External dependencies
 */
import { isEmptyObject, isObject } from '@woocommerce/types';

describe( 'Object type-guards', () => {
	describe( 'Testing isObject()', () => {
		it( 'Correctly identifies an object', () => {
			expect( isObject( {} ) ).toBe( true );
			expect( isObject( { test: 'object' } ) ).toBe( true );
		} );
		it( 'Correctly rejects object-like things', () => {
			expect( isObject( [] ) ).toBe( false );
			expect( isObject( null ) ).toBe( false );
		} );
	} );
	describe( 'Testing isEmptyObject()', () => {
		it( 'Correctly identifies an empty object', () => {
			expect( isEmptyObject( {} ) ).toBe( true );
		} );
		it( 'Correctly identifies an not empty object', () => {
			expect( isEmptyObject( { name: 'Woo' } ) ).toBe( false );
		} );
	} );
} );
type-guards/test/validation.ts000064400000002560151550203500012470 0ustar00/**
 * Internal dependencies
 */
import {
	isValidFieldValidationStatus,
	isValidValidationErrorsObject,
} from '../validation';

describe( 'validation type guards', () => {
	describe( 'isValidFieldValidationStatus', () => {
		it( 'identifies valid objects', () => {
			const valid = {
				message: 'message',
				hidden: false,
			};
			expect( isValidFieldValidationStatus( valid ) ).toBe( true );
		} );
		it( 'identifies invalid objects', () => {
			const invalid = {
				message: 'message',
				hidden: 'string',
			};
			expect( isValidFieldValidationStatus( invalid ) ).toBe( false );
			const noMessage = {
				hidden: false,
			};
			expect( isValidFieldValidationStatus( noMessage ) ).toBe( false );
		} );
	} );

	describe( 'isValidValidationErrorsObject', () => {
		it( 'identifies valid objects', () => {
			const valid = {
				'billing.first-name': {
					message: 'message',
					hidden: false,
				},
			};
			expect( isValidValidationErrorsObject( valid ) ).toBe( true );
		} );
		it( 'identifies invalid objects', () => {
			const invalid = {
				'billing.first-name': {
					message: 'message',
					hidden: 'string',
				},
			};
			expect( isValidValidationErrorsObject( invalid ) ).toBe( false );
			const noMessage = {
				'billing.first-name': {
					hidden: false,
				},
			};
			expect( isValidValidationErrorsObject( noMessage ) ).toBe( false );
		} );
	} );
} );
type-guards/validation.ts000064400000001664151550203500011515 0ustar00/**
 * External dependencies
 */
import {
	FieldValidationStatus,
	isBoolean,
	isObject,
	isString,
	objectHasProp,
} from '@woocommerce/types';

/**
 * Whether the given status is a valid FieldValidationStatus.
 */
export const isValidFieldValidationStatus = (
	status: unknown
): status is FieldValidationStatus => {
	return (
		isObject( status ) &&
		objectHasProp( status, 'message' ) &&
		objectHasProp( status, 'hidden' ) &&
		isString( status.message ) &&
		isBoolean( status.hidden )
	);
};

/**
 * Whether the passed object is a valid validation errors object. If this is true, it can be set on the
 * wc/store/validation store without any issue.
 */
export const isValidValidationErrorsObject = (
	errors: unknown
): errors is Record< string, FieldValidationStatus > => {
	return (
		isObject( errors ) &&
		Object.entries( errors ).every(
			( [ key, value ] ) =>
				isString( key ) && isValidFieldValidationStatus( value )
		)
	);
};