@openshop/svelte 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 OpenShop contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,89 @@
1
+ import { Readable, Writable } from 'svelte/store';
2
+ import { ReadableStore, Selector, EqualityFn, Cart, CartStatus, CartStore, OptionSelection, ProductVariant, OptionValueState, Product, PredictiveSearchResult, Locale, I18n } from '@openshop/core';
3
+ export { formatMoney } from '@openshop/core';
4
+
5
+ /**
6
+ * Adapt an OpenShop reactive store into a Svelte `Readable` of a selected
7
+ * slice. The Svelte store contract (subscribe-with-immediate-value) maps
8
+ * cleanly onto the core's `subscribeRaw` + selector model, and the underlying
9
+ * subscription is released when the last Svelte subscriber leaves.
10
+ */
11
+ declare function selectStore<T, R>(store: ReadableStore<T>, selector: Selector<T, R>, equals?: EqualityFn<R>): Readable<R>;
12
+
13
+ interface CartStores {
14
+ cart: Readable<Cart | null>;
15
+ count: Readable<number>;
16
+ status: Readable<CartStatus>;
17
+ isUpdating: Readable<boolean>;
18
+ error: Readable<string | null>;
19
+ actions: {
20
+ addLine: CartStore["addLine"];
21
+ addLines: CartStore["addLines"];
22
+ updateLine: CartStore["updateLine"];
23
+ removeLine: CartStore["removeLine"];
24
+ setDiscountCodes: CartStore["setDiscountCodes"];
25
+ refresh: CartStore["refresh"];
26
+ };
27
+ }
28
+ /**
29
+ * Derive a set of Svelte stores (plus bound actions) from a `CartStore`.
30
+ * Each store updates only when its slice changes.
31
+ *
32
+ * ```svelte
33
+ * <script>
34
+ * import { createCartStores } from "@openshop/svelte";
35
+ * const { count, actions } = createCartStores(cart);
36
+ * </script>
37
+ * <button on:click={() => actions.addLine({ merchandiseId })}>Cart {$count}</button>
38
+ * ```
39
+ */
40
+ declare function createCartStores(cart: CartStore): CartStores;
41
+
42
+ interface VariantSelectionStores {
43
+ selection: Writable<OptionSelection>;
44
+ selectedVariant: Readable<ProductVariant | undefined>;
45
+ options: Readable<{
46
+ name: string;
47
+ values: OptionValueState[];
48
+ }[]>;
49
+ setOption: (optionName: string, value: string) => void;
50
+ }
51
+ /** Svelte stores driving variant selection for a product. */
52
+ declare function createVariantSelection(product: Product, initial?: OptionSelection): VariantSelectionStores;
53
+
54
+ interface PredictiveSearchOptions {
55
+ debounceMs?: number;
56
+ minLength?: number;
57
+ }
58
+ interface PredictiveSearchStores {
59
+ term: Writable<string>;
60
+ results: Readable<PredictiveSearchResult>;
61
+ loading: Readable<boolean>;
62
+ error: Readable<unknown>;
63
+ clear: () => void;
64
+ /** Stop watching `term`. Call when the component is destroyed. */
65
+ destroy: () => void;
66
+ }
67
+ /**
68
+ * Debounced predictive search as Svelte stores, with stale-response protection.
69
+ * Bind an input to `term`; read `$results` / `$loading`.
70
+ */
71
+ declare function createPredictiveSearch(search: (term: string) => Promise<PredictiveSearchResult>, options?: PredictiveSearchOptions): PredictiveSearchStores;
72
+
73
+ interface I18nHelpers {
74
+ locale: Locale;
75
+ locales: Locale[];
76
+ localizePath: (path: string, locale?: Locale) => string;
77
+ alternates: (path: string) => {
78
+ locale: Locale;
79
+ href: string;
80
+ }[];
81
+ }
82
+ /**
83
+ * Build locale helpers bound to the active locale. Framework-neutral (no Svelte
84
+ * context dependency) so it works in load functions and components alike; stash
85
+ * the result in Svelte context yourself if you want app-wide access.
86
+ */
87
+ declare function createI18nHelpers(i18n: I18n, locale: Locale, origin?: string): I18nHelpers;
88
+
89
+ export { type CartStores, type I18nHelpers, type PredictiveSearchOptions, type PredictiveSearchStores, type VariantSelectionStores, createCartStores, createI18nHelpers, createPredictiveSearch, createVariantSelection, selectStore };
package/dist/index.js ADDED
@@ -0,0 +1,124 @@
1
+ import { readable, writable, derived } from 'svelte/store';
2
+ import { refEquals, getInitialSelection, findVariantBySelection, getOptionValueStates } from '@openshop/core';
3
+ export { formatMoney } from '@openshop/core';
4
+
5
+ // src/store.ts
6
+ function selectStore(store, selector, equals = refEquals) {
7
+ return readable(selector(store.get()), (set) => {
8
+ let current = selector(store.get());
9
+ set(current);
10
+ return store.subscribeRaw(() => {
11
+ const next = selector(store.get());
12
+ if (!equals(current, next)) {
13
+ current = next;
14
+ set(next);
15
+ }
16
+ });
17
+ });
18
+ }
19
+
20
+ // src/cart.ts
21
+ function createCartStores(cart) {
22
+ return {
23
+ cart: selectStore(cart, (s) => s.cart),
24
+ count: selectStore(cart, (s) => s.cart?.totalQuantity ?? 0),
25
+ status: selectStore(cart, (s) => s.status),
26
+ isUpdating: selectStore(cart, (s) => s.status === "updating"),
27
+ error: selectStore(cart, (s) => s.error),
28
+ actions: {
29
+ addLine: cart.addLine.bind(cart),
30
+ addLines: cart.addLines.bind(cart),
31
+ updateLine: cart.updateLine.bind(cart),
32
+ removeLine: cart.removeLine.bind(cart),
33
+ setDiscountCodes: cart.setDiscountCodes.bind(cart),
34
+ refresh: cart.refresh.bind(cart)
35
+ }
36
+ };
37
+ }
38
+ function createVariantSelection(product, initial) {
39
+ const selection = writable(
40
+ initial ?? getInitialSelection(product)
41
+ );
42
+ const selectedVariant = derived(
43
+ selection,
44
+ ($selection) => findVariantBySelection(product, $selection)
45
+ );
46
+ const options = derived(
47
+ selection,
48
+ ($selection) => product.options.map((option) => ({
49
+ name: option.name,
50
+ values: getOptionValueStates(product, option.name, $selection)
51
+ }))
52
+ );
53
+ function setOption(optionName, value) {
54
+ selection.update((prev) => ({ ...prev, [optionName]: value }));
55
+ }
56
+ return { selection, selectedVariant, options, setOption };
57
+ }
58
+ var EMPTY = {
59
+ products: [],
60
+ collections: [],
61
+ pages: [],
62
+ articles: [],
63
+ queries: []
64
+ };
65
+ function createPredictiveSearch(search, options = {}) {
66
+ const { debounceMs = 200, minLength = 2 } = options;
67
+ const term = writable("");
68
+ const results = writable(EMPTY);
69
+ const loading = writable(false);
70
+ const error = writable(null);
71
+ let requestId = 0;
72
+ let timer;
73
+ const unsubscribe = term.subscribe((value) => {
74
+ if (timer) clearTimeout(timer);
75
+ const trimmed = value.trim();
76
+ if (trimmed.length < minLength) {
77
+ results.set(EMPTY);
78
+ loading.set(false);
79
+ return;
80
+ }
81
+ const id = ++requestId;
82
+ loading.set(true);
83
+ timer = setTimeout(async () => {
84
+ try {
85
+ const next = await search(trimmed);
86
+ if (id === requestId) {
87
+ results.set(next);
88
+ error.set(null);
89
+ }
90
+ } catch (err) {
91
+ if (id === requestId) error.set(err);
92
+ } finally {
93
+ if (id === requestId) loading.set(false);
94
+ }
95
+ }, debounceMs);
96
+ });
97
+ function clear() {
98
+ requestId += 1;
99
+ if (timer) clearTimeout(timer);
100
+ term.set("");
101
+ results.set(EMPTY);
102
+ loading.set(false);
103
+ error.set(null);
104
+ }
105
+ function destroy() {
106
+ if (timer) clearTimeout(timer);
107
+ unsubscribe();
108
+ }
109
+ return { term, results, loading, error, clear, destroy };
110
+ }
111
+
112
+ // src/i18n.ts
113
+ function createI18nHelpers(i18n, locale, origin) {
114
+ return {
115
+ locale,
116
+ locales: i18n.locales,
117
+ localizePath: (path, target = locale) => i18n.localizePath(path, target, origin),
118
+ alternates: (path) => i18n.alternates(path, origin)
119
+ };
120
+ }
121
+
122
+ export { createCartStores, createI18nHelpers, createPredictiveSearch, createVariantSelection, selectStore };
123
+ //# sourceMappingURL=index.js.map
124
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/store.ts","../src/cart.ts","../src/product.ts","../src/search.ts","../src/i18n.ts"],"names":["writable"],"mappings":";;;;;AAcO,SAAS,WAAA,CACd,KAAA,EACA,QAAA,EACA,MAAA,GAAwB,SAAA,EACX;AACb,EAAA,OAAO,SAAS,QAAA,CAAS,KAAA,CAAM,KAAK,CAAA,EAAG,CAAC,GAAA,KAAQ;AAC9C,IAAA,IAAI,OAAA,GAAU,QAAA,CAAS,KAAA,CAAM,GAAA,EAAK,CAAA;AAClC,IAAA,GAAA,CAAI,OAAO,CAAA;AACX,IAAA,OAAO,KAAA,CAAM,aAAa,MAAM;AAC9B,MAAA,MAAM,IAAA,GAAO,QAAA,CAAS,KAAA,CAAM,GAAA,EAAK,CAAA;AACjC,MAAA,IAAI,CAAC,MAAA,CAAO,OAAA,EAAS,IAAI,CAAA,EAAG;AAC1B,QAAA,OAAA,GAAU,IAAA;AACV,QAAA,GAAA,CAAI,IAAI,CAAA;AAAA,MACV;AAAA,IACF,CAAC,CAAA;AAAA,EACH,CAAC,CAAA;AACH;;;ACEO,SAAS,iBAAiB,IAAA,EAA6B;AAC5D,EAAA,OAAO;AAAA,IACL,MAAM,WAAA,CAAY,IAAA,EAAM,CAAC,CAAA,KAAM,EAAE,IAAI,CAAA;AAAA,IACrC,KAAA,EAAO,YAAY,IAAA,EAAM,CAAC,MAAM,CAAA,CAAE,IAAA,EAAM,iBAAiB,CAAC,CAAA;AAAA,IAC1D,QAAQ,WAAA,CAAY,IAAA,EAA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EAAQ,MAAM,CAAA;AAAA,IACxC,YAAY,CAAC,IAAA,KAAS,IAAA,CAAK,UAAA,CAAW,MAAM,MAAM;AAAA,GACpD;AACF","file":"index.js","sourcesContent":["import { readable, type Readable } from \"svelte/store\";\r\nimport {\r\n refEquals,\r\n type EqualityFn,\r\n type ReadableStore,\r\n type Selector,\r\n} from \"@openshop/core\";\r\n\r\n/**\r\n * Adapt an OpenShop reactive store into a Svelte `Readable` of a selected\r\n * slice. The Svelte store contract (subscribe-with-immediate-value) maps\r\n * cleanly onto the core's `subscribeRaw` + selector model, and the underlying\r\n * subscription is released when the last Svelte subscriber leaves.\r\n */\r\nexport function selectStore<T, R>(\r\n store: ReadableStore<T>,\r\n selector: Selector<T, R>,\r\n equals: EqualityFn<R> = refEquals,\r\n): Readable<R> {\r\n return readable(selector(store.get()), (set) => {\r\n let current = selector(store.get());\r\n set(current);\r\n return store.subscribeRaw(() => {\r\n const next = selector(store.get());\r\n if (!equals(current, next)) {\r\n current = next;\r\n set(next);\r\n }\r\n });\r\n });\r\n}\r\n","import type { Readable } from \"svelte/store\";\r\nimport type { Cart, CartStatus, CartStore } from \"@openshop/core\";\r\nimport { selectStore } from \"./store.js\";\r\n\r\nexport interface CartStores {\r\n cart: Readable<Cart | null>;\r\n count: Readable<number>;\r\n status: Readable<CartStatus>;\r\n isUpdating: Readable<boolean>;\r\n error: Readable<string | null>;\r\n actions: {\r\n addLine: CartStore[\"addLine\"];\r\n addLines: CartStore[\"addLines\"];\r\n updateLine: CartStore[\"updateLine\"];\r\n removeLine: CartStore[\"removeLine\"];\r\n setDiscountCodes: CartStore[\"setDiscountCodes\"];\r\n refresh: CartStore[\"refresh\"];\r\n };\r\n}\r\n\r\n/**\r\n * Derive a set of Svelte stores (plus bound actions) from a `CartStore`.\r\n * Each store updates only when its slice changes.\r\n *\r\n * ```svelte\r\n * <script>\r\n * import { createCartStores } from \"@openshop/svelte\";\r\n * const { count, actions } = createCartStores(cart);\r\n * </script>\r\n * <button on:click={() => actions.addLine({ merchandiseId })}>Cart {$count}</button>\r\n * ```\r\n */\r\nexport function createCartStores(cart: CartStore): CartStores {\r\n return {\r\n cart: selectStore(cart, (s) => s.cart),\r\n count: selectStore(cart, (s) => s.cart?.totalQuantity ?? 0),\r\n status: selectStore(cart, (s) => s.status),\r\n isUpdating: selectStore(cart, (s) => s.status === \"updating\"),\r\n error: selectStore(cart, (s) => s.error),\r\n actions: {\r\n addLine: cart.addLine.bind(cart),\r\n addLines: cart.addLines.bind(cart),\r\n updateLine: cart.updateLine.bind(cart),\r\n removeLine: cart.removeLine.bind(cart),\r\n setDiscountCodes: cart.setDiscountCodes.bind(cart),\r\n refresh: cart.refresh.bind(cart),\r\n },\r\n };\r\n}\r\n","import { derived, writable, type Readable, type Writable } from \"svelte/store\";\r\nimport {\r\n findVariantBySelection,\r\n getInitialSelection,\r\n getOptionValueStates,\r\n type OptionSelection,\r\n type OptionValueState,\r\n type Product,\r\n type ProductVariant,\r\n} from \"@openshop/core\";\r\n\r\nexport interface VariantSelectionStores {\r\n selection: Writable<OptionSelection>;\r\n selectedVariant: Readable<ProductVariant | undefined>;\r\n options: Readable<{ name: string; values: OptionValueState[] }[]>;\r\n setOption: (optionName: string, value: string) => void;\r\n}\r\n\r\n/** Svelte stores driving variant selection for a product. */\r\nexport function createVariantSelection(\r\n product: Product,\r\n initial?: OptionSelection,\r\n): VariantSelectionStores {\r\n const selection = writable<OptionSelection>(\r\n initial ?? getInitialSelection(product),\r\n );\r\n\r\n const selectedVariant = derived(selection, ($selection) =>\r\n findVariantBySelection(product, $selection),\r\n );\r\n\r\n const options = derived(selection, ($selection) =>\r\n product.options.map((option) => ({\r\n name: option.name,\r\n values: getOptionValueStates(product, option.name, $selection),\r\n })),\r\n );\r\n\r\n function setOption(optionName: string, value: string): void {\r\n selection.update((prev) => ({ ...prev, [optionName]: value }));\r\n }\r\n\r\n return { selection, selectedVariant, options, setOption };\r\n}\r\n","import { writable, type Readable, type Writable } from \"svelte/store\";\r\nimport type { PredictiveSearchResult } from \"@openshop/core\";\r\n\r\nconst EMPTY: PredictiveSearchResult = {\r\n products: [],\r\n collections: [],\r\n pages: [],\r\n articles: [],\r\n queries: [],\r\n};\r\n\r\nexport interface PredictiveSearchOptions {\r\n debounceMs?: number;\r\n minLength?: number;\r\n}\r\n\r\nexport interface PredictiveSearchStores {\r\n term: Writable<string>;\r\n results: Readable<PredictiveSearchResult>;\r\n loading: Readable<boolean>;\r\n error: Readable<unknown>;\r\n clear: () => void;\r\n /** Stop watching `term`. Call when the component is destroyed. */\r\n destroy: () => void;\r\n}\r\n\r\n/**\r\n * Debounced predictive search as Svelte stores, with stale-response protection.\r\n * Bind an input to `term`; read `$results` / `$loading`.\r\n */\r\nexport function createPredictiveSearch(\r\n search: (term: string) => Promise<PredictiveSearchResult>,\r\n options: PredictiveSearchOptions = {},\r\n): PredictiveSearchStores {\r\n const { debounceMs = 200, minLength = 2 } = options;\r\n const term = writable(\"\");\r\n const results = writable<PredictiveSearchResult>(EMPTY);\r\n const loading = writable(false);\r\n const error = writable<unknown>(null);\r\n\r\n let requestId = 0;\r\n let timer: ReturnType<typeof setTimeout> | undefined;\r\n\r\n const unsubscribe = term.subscribe((value) => {\r\n if (timer) clearTimeout(timer);\r\n const trimmed = value.trim();\r\n if (trimmed.length < minLength) {\r\n results.set(EMPTY);\r\n loading.set(false);\r\n return;\r\n }\r\n const id = ++requestId;\r\n loading.set(true);\r\n timer = setTimeout(async () => {\r\n try {\r\n const next = await search(trimmed);\r\n if (id === requestId) {\r\n results.set(next);\r\n error.set(null);\r\n }\r\n } catch (err) {\r\n if (id === requestId) error.set(err);\r\n } finally {\r\n if (id === requestId) loading.set(false);\r\n }\r\n }, debounceMs);\r\n });\r\n\r\n function clear(): void {\r\n requestId += 1;\r\n if (timer) clearTimeout(timer);\r\n term.set(\"\");\r\n results.set(EMPTY);\r\n loading.set(false);\r\n error.set(null);\r\n }\r\n\r\n function destroy(): void {\r\n if (timer) clearTimeout(timer);\r\n unsubscribe();\r\n }\r\n\r\n return { term, results, loading, error, clear, destroy };\r\n}\r\n","import type { I18n, Locale } from \"@openshop/core\";\r\n\r\nexport interface I18nHelpers {\r\n locale: Locale;\r\n locales: Locale[];\r\n localizePath: (path: string, locale?: Locale) => string;\r\n alternates: (path: string) => { locale: Locale; href: string }[];\r\n}\r\n\r\n/**\r\n * Build locale helpers bound to the active locale. Framework-neutral (no Svelte\r\n * context dependency) so it works in load functions and components alike; stash\r\n * the result in Svelte context yourself if you want app-wide access.\r\n */\r\nexport function createI18nHelpers(\r\n i18n: I18n,\r\n locale: Locale,\r\n origin?: string,\r\n): I18nHelpers {\r\n return {\r\n locale,\r\n locales: i18n.locales,\r\n localizePath: (path, target = locale) =>\r\n i18n.localizePath(path, target, origin),\r\n alternates: (path) => i18n.alternates(path, origin),\r\n };\r\n}\r\n"]}
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@openshop/svelte",
3
+ "version": "0.2.0",
4
+ "description": "Svelte stores for OpenShop's framework-agnostic commerce core.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "files": [
9
+ "dist"
10
+ ],
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.js"
15
+ }
16
+ },
17
+ "peerDependencies": {
18
+ "svelte": ">=4.0.0"
19
+ },
20
+ "dependencies": {
21
+ "@openshop/core": "0.2.0"
22
+ },
23
+ "devDependencies": {
24
+ "svelte": "^5.15.0",
25
+ "tsup": "^8.3.5",
26
+ "typescript": "^5.7.2",
27
+ "vitest": "^2.1.8"
28
+ },
29
+ "scripts": {
30
+ "build": "tsup",
31
+ "dev": "tsup --watch",
32
+ "test": "vitest run",
33
+ "test:watch": "vitest",
34
+ "typecheck": "tsc --noEmit",
35
+ "clean": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\""
36
+ }
37
+ }