@moonbase.sh/vue 0.1.25

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/dist/index.cjs ADDED
@@ -0,0 +1,309 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/index.ts
22
+ var src_exports = {};
23
+ __export(src_exports, {
24
+ createStorefront: () => createStorefront,
25
+ findBestPrice: () => findBestPrice,
26
+ storefrontKey: () => storefrontKey,
27
+ useAuth: () => useAuth,
28
+ useBundle: () => useBundle,
29
+ useBundles: () => useBundles,
30
+ useCart: () => useCart,
31
+ useProduct: () => useProduct,
32
+ useProducts: () => useProducts
33
+ });
34
+ module.exports = __toCommonJS(src_exports);
35
+ var import_api_client3 = require("@moonbase.sh/api-client");
36
+
37
+ // src/context.ts
38
+ var import_api_client = require("@moonbase.sh/api-client");
39
+ var import_uuid = require("uuid");
40
+ var import_vue = require("vue");
41
+
42
+ // src/symbols.ts
43
+ var storefrontKey = Symbol("storefront");
44
+
45
+ // src/utils/debounce.ts
46
+ function debounce(func, waitMs = 100) {
47
+ let timeoutToken = 0;
48
+ const debounced = async (...args) => {
49
+ clearTimeout(timeoutToken);
50
+ timeoutToken = setTimeout(() => {
51
+ func(...args);
52
+ }, waitMs);
53
+ };
54
+ return debounced;
55
+ }
56
+
57
+ // src/context.ts
58
+ var StorefrontContextImpl = class {
59
+ constructor(configuration, client) {
60
+ this.configuration = configuration;
61
+ this.client = client;
62
+ this.currentUser = (0, import_vue.ref)(null);
63
+ this.loadedUser = (0, import_vue.ref)(false);
64
+ this.debouncedPushOrderContent = debounce((order) => this.client.orders.pushContent(order), 500);
65
+ window.addEventListener("storage", (event) => this.handleStorageUpdate(event));
66
+ const cachedOrderJson = localStorage.getItem("moonbase_session");
67
+ if (cachedOrderJson) {
68
+ this.currentOrder = (0, import_vue.ref)(JSON.parse(cachedOrderJson));
69
+ } else {
70
+ this.currentOrder = (0, import_vue.ref)({
71
+ id: (0, import_uuid.v4)(),
72
+ status: import_api_client.OrderStatus.Open,
73
+ currency: "",
74
+ items: [],
75
+ couponsApplied: []
76
+ });
77
+ localStorage.setItem("moonbase_session", JSON.stringify(this.currentOrder.value));
78
+ }
79
+ const cachedStorefrontJson = localStorage.getItem("moonbase_storefront");
80
+ if (cachedStorefrontJson) {
81
+ this.storefront = (0, import_vue.ref)(JSON.parse(cachedStorefrontJson));
82
+ this.loadedStorefront = (0, import_vue.ref)(true);
83
+ } else {
84
+ this.storefront = (0, import_vue.ref)({
85
+ suggestedCurrency: "",
86
+ bundles: [],
87
+ products: []
88
+ });
89
+ this.loadedStorefront = (0, import_vue.ref)(false);
90
+ }
91
+ const _2 = this.updateStorefront();
92
+ const _3 = this.updateUser();
93
+ }
94
+ install(app) {
95
+ app.provide(storefrontKey, this);
96
+ console.log("Storefront installed");
97
+ }
98
+ async updateUser() {
99
+ try {
100
+ this.currentUser.value = await this.client.identity.get();
101
+ } catch (err) {
102
+ if (!(err instanceof import_api_client.NotAuthenticatedError))
103
+ console.error("Could not load user", err);
104
+ } finally {
105
+ this.loadedUser.value = true;
106
+ }
107
+ }
108
+ async updateStorefront() {
109
+ const latestStorefront = await this.client.storefront.get();
110
+ if (latestStorefront) {
111
+ localStorage.setItem("moonbase_storefront", JSON.stringify(latestStorefront));
112
+ this.storefront.value = latestStorefront;
113
+ this.loadedStorefront.value = true;
114
+ if (!this.currentOrder.value.currency) {
115
+ this.currentOrder.value.currency = latestStorefront.suggestedCurrency;
116
+ const _ = this.pushOrderContent();
117
+ }
118
+ }
119
+ }
120
+ async pushOrderContent() {
121
+ localStorage.setItem("moonbase_session", JSON.stringify(this.currentOrder.value));
122
+ const _ = this.debouncedPushOrderContent(this.currentOrder.value);
123
+ }
124
+ handleStorageUpdate(event) {
125
+ switch (event.key) {
126
+ case "moonbase_session":
127
+ this.currentOrder.value = JSON.parse(event.newValue);
128
+ break;
129
+ case "moonbase_storefront":
130
+ this.storefront.value = JSON.parse(event.newValue);
131
+ break;
132
+ }
133
+ }
134
+ };
135
+
136
+ // src/index.ts
137
+ __reExport(src_exports, require("@moonbase.sh/api-client"), module.exports);
138
+
139
+ // src/composables/useBundle.ts
140
+ var import_vue2 = require("vue");
141
+ function useBundle(bundleId) {
142
+ const storefront = (0, import_vue2.inject)(storefrontKey);
143
+ if (!storefront)
144
+ throw new Error("No storefront configured");
145
+ return (0, import_vue2.computed)(() => storefront.storefront.value.bundles.find((b) => b.id === bundleId) || null);
146
+ }
147
+
148
+ // src/composables/useBundles.ts
149
+ var import_vue3 = require("vue");
150
+ function useBundles() {
151
+ const storefront = (0, import_vue3.inject)(storefrontKey);
152
+ if (!storefront)
153
+ throw new Error("No storefront configured");
154
+ return (0, import_vue3.computed)(() => storefront.storefront.value.bundles);
155
+ }
156
+
157
+ // src/composables/useProduct.ts
158
+ var import_vue4 = require("vue");
159
+ function useProduct(productId) {
160
+ const storefront = (0, import_vue4.inject)(storefrontKey);
161
+ if (!storefront)
162
+ throw new Error("No storefront configured");
163
+ return (0, import_vue4.computed)(() => storefront.storefront.value.products.find((p) => p.id === productId) || null);
164
+ }
165
+
166
+ // src/composables/useProducts.ts
167
+ var import_vue5 = require("vue");
168
+ function useProducts() {
169
+ const storefront = (0, import_vue5.inject)(storefrontKey);
170
+ if (!storefront)
171
+ throw new Error("No storefront configured");
172
+ return (0, import_vue5.computed)(() => storefront.storefront.value.products);
173
+ }
174
+
175
+ // src/composables/useCart.ts
176
+ var import_api_client2 = require("@moonbase.sh/api-client");
177
+ var import_vue6 = require("vue");
178
+
179
+ // src/utils/findBestPrice.ts
180
+ function findBestPrice(variations, currency, model) {
181
+ const prices = variations.filter((v) => v.model === model && v.prices[currency] !== void 0).map((v) => v.prices[currency]);
182
+ prices.sort((a, b) => b - a);
183
+ return prices.length === 0 ? 0 : prices[0];
184
+ }
185
+
186
+ // src/composables/useCart.ts
187
+ function useCart() {
188
+ const storefront = (0, import_vue6.inject)(storefrontKey);
189
+ if (!storefront)
190
+ throw new Error("No storefront configured");
191
+ return {
192
+ items: (0, import_vue6.computed)(() => storefront.currentOrder.value.items),
193
+ currency: (0, import_vue6.computed)(() => storefront.currentOrder.value.currency || storefront.storefront.value.suggestedCurrency),
194
+ total: (0, import_vue6.computed)(() => {
195
+ const currency = storefront.currentOrder.value.currency || storefront.storefront.value.suggestedCurrency;
196
+ const total = storefront.currentOrder.value.items.reduce((agg, item) => {
197
+ var _a, _b;
198
+ let bestPrice;
199
+ if (item.type === "Product") {
200
+ const variations = ((_a = useProduct(item.productId).value) == null ? void 0 : _a.pricing) || [];
201
+ bestPrice = findBestPrice(variations, currency, item.pricingModel);
202
+ } else {
203
+ const variations = ((_b = useBundle(item.bundleId).value) == null ? void 0 : _b.pricing) || [];
204
+ bestPrice = findBestPrice(variations, currency, import_api_client2.PricingModel.Purchase);
205
+ }
206
+ return agg + bestPrice * item.quantity;
207
+ }, 0);
208
+ return { amount: total, currency };
209
+ }),
210
+ addToCart: (item, model = import_api_client2.PricingModel.Purchase) => {
211
+ let lineItem = storefront.currentOrder.value.items.find((i) => i.type === "Product" && i.productId === item.id && i.pricingModel === model || i.type === "Bundle" && i.bundleId === item.id);
212
+ if (!lineItem) {
213
+ if (item.type === "bundle") {
214
+ lineItem = {
215
+ type: "Bundle",
216
+ bundleId: item.id,
217
+ bundle: item,
218
+ quantity: 1
219
+ };
220
+ storefront.currentOrder.value.items.push(lineItem);
221
+ } else if (item.type === "product") {
222
+ lineItem = {
223
+ type: "Product",
224
+ pricingModel: model,
225
+ productId: item.id,
226
+ product: item,
227
+ quantity: 1
228
+ };
229
+ storefront.currentOrder.value.items.push(lineItem);
230
+ }
231
+ } else {
232
+ lineItem.quantity += 1;
233
+ }
234
+ const _ = storefront.pushOrderContent();
235
+ },
236
+ removeFromCart: (cartItem) => {
237
+ const index = storefront.currentOrder.value.items.findIndex((i) => i.type === "Bundle" && cartItem.type === "Bundle" && i.bundleId === cartItem.bundleId || i.type === "Product" && cartItem.type === "Product" && i.productId === cartItem.productId);
238
+ storefront.currentOrder.value.items.splice(index, 1);
239
+ const _ = storefront.pushOrderContent();
240
+ },
241
+ checkout: async (returnUrl) => {
242
+ const absoluteReturnUrl = new URL(returnUrl, document.baseURI).href;
243
+ const updatedOrder = await storefront.client.orders.pushContent(storefront.currentOrder.value, {
244
+ returnUrl: absoluteReturnUrl
245
+ });
246
+ storefront.currentOrder.value = updatedOrder;
247
+ if (updatedOrder.checkoutUrl)
248
+ window.location.href = updatedOrder.checkoutUrl;
249
+ else
250
+ throw new Error("No checkout URL found");
251
+ }
252
+ };
253
+ }
254
+
255
+ // src/composables/useAuth.ts
256
+ var import_vue7 = require("vue");
257
+ function useAuth() {
258
+ const storefront = (0, import_vue7.inject)(storefrontKey);
259
+ if (!storefront)
260
+ throw new Error("No storefront configured");
261
+ return {
262
+ user: storefront.currentUser,
263
+ loaded: storefront.loadedUser,
264
+ signIn: async (email, password) => {
265
+ const user = await storefront.client.identity.signIn(email, password);
266
+ storefront.currentUser.value = user;
267
+ const _ = storefront.updateStorefront();
268
+ return user;
269
+ },
270
+ update: async (name, email, emailConfirmationToken) => {
271
+ const result = await storefront.client.identity.update(name, email, emailConfirmationToken);
272
+ if (storefront.currentUser.value)
273
+ storefront.currentUser.value.name = name;
274
+ return result;
275
+ },
276
+ setPassword: async (currentPassword, newPassword) => {
277
+ if (!storefront.currentUser.value)
278
+ throw new Error("No user loaded");
279
+ await storefront.client.identity.setPassword(storefront.currentUser.value.email, currentPassword, newPassword);
280
+ },
281
+ forgotPassword: async (email) => {
282
+ await storefront.client.identity.forgotPassword(email);
283
+ },
284
+ resetPassword: async (email, newPassword, code) => {
285
+ await storefront.client.identity.resetPassword(email, newPassword, code);
286
+ }
287
+ };
288
+ }
289
+
290
+ // src/index.ts
291
+ function createStorefront(endpoint) {
292
+ const configuration = {
293
+ endpoint
294
+ };
295
+ return new StorefrontContextImpl(configuration, new import_api_client3.MoonbaseClient(configuration));
296
+ }
297
+ // Annotate the CommonJS export names for ESM import in node:
298
+ 0 && (module.exports = {
299
+ createStorefront,
300
+ findBestPrice,
301
+ storefrontKey,
302
+ useAuth,
303
+ useBundle,
304
+ useBundles,
305
+ useCart,
306
+ useProduct,
307
+ useProducts,
308
+ ...require("@moonbase.sh/api-client")
309
+ });
@@ -0,0 +1,77 @@
1
+ import { Storefront, Order, User, MoonbaseClient, StorefrontBundle, StorefrontProduct, PricingModel, PricingVariation, OpenLineItem } from '@moonbase.sh/api-client';
2
+ export * from '@moonbase.sh/api-client';
3
+ import * as vue from 'vue';
4
+ import { Ref, App, InjectionKey } from 'vue';
5
+
6
+ interface StorefrontContext {
7
+ storefront: Ref<Storefront>;
8
+ loadedStorefront: Ref<boolean>;
9
+ currentOrder: Ref<Order>;
10
+ currentUser: Ref<User | null>;
11
+ loadedUser: Ref<boolean>;
12
+ client: MoonbaseClient;
13
+ updateStorefront(): Promise<void>;
14
+ pushOrderContent(): Promise<void>;
15
+ /**
16
+ * Called automatically by `app.use(storefront)`. Should not be called manually by
17
+ * the user.
18
+ *
19
+ * @internal
20
+ * @param app - Application that uses the storefront
21
+ */
22
+ install(app: App): any;
23
+ }
24
+
25
+ declare function useBundle(bundleId: string): Ref<StorefrontBundle | null>;
26
+
27
+ declare function useBundles(): Ref<StorefrontBundle[]>;
28
+
29
+ declare function useProduct(productId: string): Ref<StorefrontProduct | null>;
30
+
31
+ declare function useProducts(): Ref<StorefrontProduct[]>;
32
+
33
+ declare function useCart(): {
34
+ items: vue.ComputedRef<CartItem[]>;
35
+ currency: vue.ComputedRef<string>;
36
+ total: vue.ComputedRef<{
37
+ amount: number;
38
+ currency: string;
39
+ }>;
40
+ addToCart: (item: StorefrontProduct | StorefrontBundle, model?: PricingModel) => void;
41
+ removeFromCart: (cartItem: CartItem) => void;
42
+ checkout: (returnUrl: string) => Promise<void>;
43
+ };
44
+
45
+ declare function useAuth(): {
46
+ user: vue.Ref<{
47
+ id: string;
48
+ email: string;
49
+ name: string;
50
+ tenantId: string;
51
+ } | null>;
52
+ loaded: vue.Ref<boolean>;
53
+ signIn: (email: string, password: string) => Promise<{
54
+ id: string;
55
+ email: string;
56
+ name: string;
57
+ tenantId: string;
58
+ }>;
59
+ update: (name: string, email: string, emailConfirmationToken?: string) => Promise<{
60
+ needsEmailConfirmationToken: boolean;
61
+ }>;
62
+ setPassword: (currentPassword: string, newPassword: string) => Promise<void>;
63
+ forgotPassword: (email: string) => Promise<void>;
64
+ resetPassword: (email: string, newPassword: string, code: string) => Promise<void>;
65
+ };
66
+
67
+ declare const storefrontKey: InjectionKey<StorefrontContext>;
68
+
69
+ declare function findBestPrice(variations: PricingVariation[], currency: string, model: PricingModel): number;
70
+
71
+ interface Cart {
72
+ items: CartItem[];
73
+ }
74
+ type CartItem = OpenLineItem & {};
75
+ declare function createStorefront(endpoint: string): StorefrontContext;
76
+
77
+ export { Cart, CartItem, createStorefront, findBestPrice, storefrontKey, useAuth, useBundle, useBundles, useCart, useProduct, useProducts };
@@ -0,0 +1,77 @@
1
+ import { Storefront, Order, User, MoonbaseClient, StorefrontBundle, StorefrontProduct, PricingModel, PricingVariation, OpenLineItem } from '@moonbase.sh/api-client';
2
+ export * from '@moonbase.sh/api-client';
3
+ import * as vue from 'vue';
4
+ import { Ref, App, InjectionKey } from 'vue';
5
+
6
+ interface StorefrontContext {
7
+ storefront: Ref<Storefront>;
8
+ loadedStorefront: Ref<boolean>;
9
+ currentOrder: Ref<Order>;
10
+ currentUser: Ref<User | null>;
11
+ loadedUser: Ref<boolean>;
12
+ client: MoonbaseClient;
13
+ updateStorefront(): Promise<void>;
14
+ pushOrderContent(): Promise<void>;
15
+ /**
16
+ * Called automatically by `app.use(storefront)`. Should not be called manually by
17
+ * the user.
18
+ *
19
+ * @internal
20
+ * @param app - Application that uses the storefront
21
+ */
22
+ install(app: App): any;
23
+ }
24
+
25
+ declare function useBundle(bundleId: string): Ref<StorefrontBundle | null>;
26
+
27
+ declare function useBundles(): Ref<StorefrontBundle[]>;
28
+
29
+ declare function useProduct(productId: string): Ref<StorefrontProduct | null>;
30
+
31
+ declare function useProducts(): Ref<StorefrontProduct[]>;
32
+
33
+ declare function useCart(): {
34
+ items: vue.ComputedRef<CartItem[]>;
35
+ currency: vue.ComputedRef<string>;
36
+ total: vue.ComputedRef<{
37
+ amount: number;
38
+ currency: string;
39
+ }>;
40
+ addToCart: (item: StorefrontProduct | StorefrontBundle, model?: PricingModel) => void;
41
+ removeFromCart: (cartItem: CartItem) => void;
42
+ checkout: (returnUrl: string) => Promise<void>;
43
+ };
44
+
45
+ declare function useAuth(): {
46
+ user: vue.Ref<{
47
+ id: string;
48
+ email: string;
49
+ name: string;
50
+ tenantId: string;
51
+ } | null>;
52
+ loaded: vue.Ref<boolean>;
53
+ signIn: (email: string, password: string) => Promise<{
54
+ id: string;
55
+ email: string;
56
+ name: string;
57
+ tenantId: string;
58
+ }>;
59
+ update: (name: string, email: string, emailConfirmationToken?: string) => Promise<{
60
+ needsEmailConfirmationToken: boolean;
61
+ }>;
62
+ setPassword: (currentPassword: string, newPassword: string) => Promise<void>;
63
+ forgotPassword: (email: string) => Promise<void>;
64
+ resetPassword: (email: string, newPassword: string, code: string) => Promise<void>;
65
+ };
66
+
67
+ declare const storefrontKey: InjectionKey<StorefrontContext>;
68
+
69
+ declare function findBestPrice(variations: PricingVariation[], currency: string, model: PricingModel): number;
70
+
71
+ interface Cart {
72
+ items: CartItem[];
73
+ }
74
+ type CartItem = OpenLineItem & {};
75
+ declare function createStorefront(endpoint: string): StorefrontContext;
76
+
77
+ export { Cart, CartItem, createStorefront, findBestPrice, storefrontKey, useAuth, useBundle, useBundles, useCart, useProduct, useProducts };
package/dist/index.js ADDED
@@ -0,0 +1,274 @@
1
+ // src/index.ts
2
+ import { MoonbaseClient } from "@moonbase.sh/api-client";
3
+
4
+ // src/context.ts
5
+ import { NotAuthenticatedError, OrderStatus } from "@moonbase.sh/api-client";
6
+ import { v4 as uuidv4 } from "uuid";
7
+ import { ref } from "vue";
8
+
9
+ // src/symbols.ts
10
+ var storefrontKey = Symbol("storefront");
11
+
12
+ // src/utils/debounce.ts
13
+ function debounce(func, waitMs = 100) {
14
+ let timeoutToken = 0;
15
+ const debounced = async (...args) => {
16
+ clearTimeout(timeoutToken);
17
+ timeoutToken = setTimeout(() => {
18
+ func(...args);
19
+ }, waitMs);
20
+ };
21
+ return debounced;
22
+ }
23
+
24
+ // src/context.ts
25
+ var StorefrontContextImpl = class {
26
+ constructor(configuration, client) {
27
+ this.configuration = configuration;
28
+ this.client = client;
29
+ this.currentUser = ref(null);
30
+ this.loadedUser = ref(false);
31
+ this.debouncedPushOrderContent = debounce((order) => this.client.orders.pushContent(order), 500);
32
+ window.addEventListener("storage", (event) => this.handleStorageUpdate(event));
33
+ const cachedOrderJson = localStorage.getItem("moonbase_session");
34
+ if (cachedOrderJson) {
35
+ this.currentOrder = ref(JSON.parse(cachedOrderJson));
36
+ } else {
37
+ this.currentOrder = ref({
38
+ id: uuidv4(),
39
+ status: OrderStatus.Open,
40
+ currency: "",
41
+ items: [],
42
+ couponsApplied: []
43
+ });
44
+ localStorage.setItem("moonbase_session", JSON.stringify(this.currentOrder.value));
45
+ }
46
+ const cachedStorefrontJson = localStorage.getItem("moonbase_storefront");
47
+ if (cachedStorefrontJson) {
48
+ this.storefront = ref(JSON.parse(cachedStorefrontJson));
49
+ this.loadedStorefront = ref(true);
50
+ } else {
51
+ this.storefront = ref({
52
+ suggestedCurrency: "",
53
+ bundles: [],
54
+ products: []
55
+ });
56
+ this.loadedStorefront = ref(false);
57
+ }
58
+ const _2 = this.updateStorefront();
59
+ const _3 = this.updateUser();
60
+ }
61
+ install(app) {
62
+ app.provide(storefrontKey, this);
63
+ console.log("Storefront installed");
64
+ }
65
+ async updateUser() {
66
+ try {
67
+ this.currentUser.value = await this.client.identity.get();
68
+ } catch (err) {
69
+ if (!(err instanceof NotAuthenticatedError))
70
+ console.error("Could not load user", err);
71
+ } finally {
72
+ this.loadedUser.value = true;
73
+ }
74
+ }
75
+ async updateStorefront() {
76
+ const latestStorefront = await this.client.storefront.get();
77
+ if (latestStorefront) {
78
+ localStorage.setItem("moonbase_storefront", JSON.stringify(latestStorefront));
79
+ this.storefront.value = latestStorefront;
80
+ this.loadedStorefront.value = true;
81
+ if (!this.currentOrder.value.currency) {
82
+ this.currentOrder.value.currency = latestStorefront.suggestedCurrency;
83
+ const _ = this.pushOrderContent();
84
+ }
85
+ }
86
+ }
87
+ async pushOrderContent() {
88
+ localStorage.setItem("moonbase_session", JSON.stringify(this.currentOrder.value));
89
+ const _ = this.debouncedPushOrderContent(this.currentOrder.value);
90
+ }
91
+ handleStorageUpdate(event) {
92
+ switch (event.key) {
93
+ case "moonbase_session":
94
+ this.currentOrder.value = JSON.parse(event.newValue);
95
+ break;
96
+ case "moonbase_storefront":
97
+ this.storefront.value = JSON.parse(event.newValue);
98
+ break;
99
+ }
100
+ }
101
+ };
102
+
103
+ // src/index.ts
104
+ export * from "@moonbase.sh/api-client";
105
+
106
+ // src/composables/useBundle.ts
107
+ import { computed, inject } from "vue";
108
+ function useBundle(bundleId) {
109
+ const storefront = inject(storefrontKey);
110
+ if (!storefront)
111
+ throw new Error("No storefront configured");
112
+ return computed(() => storefront.storefront.value.bundles.find((b) => b.id === bundleId) || null);
113
+ }
114
+
115
+ // src/composables/useBundles.ts
116
+ import { computed as computed2, inject as inject2 } from "vue";
117
+ function useBundles() {
118
+ const storefront = inject2(storefrontKey);
119
+ if (!storefront)
120
+ throw new Error("No storefront configured");
121
+ return computed2(() => storefront.storefront.value.bundles);
122
+ }
123
+
124
+ // src/composables/useProduct.ts
125
+ import { computed as computed3, inject as inject3 } from "vue";
126
+ function useProduct(productId) {
127
+ const storefront = inject3(storefrontKey);
128
+ if (!storefront)
129
+ throw new Error("No storefront configured");
130
+ return computed3(() => storefront.storefront.value.products.find((p) => p.id === productId) || null);
131
+ }
132
+
133
+ // src/composables/useProducts.ts
134
+ import { computed as computed4, inject as inject4 } from "vue";
135
+ function useProducts() {
136
+ const storefront = inject4(storefrontKey);
137
+ if (!storefront)
138
+ throw new Error("No storefront configured");
139
+ return computed4(() => storefront.storefront.value.products);
140
+ }
141
+
142
+ // src/composables/useCart.ts
143
+ import { PricingModel } from "@moonbase.sh/api-client";
144
+ import { computed as computed5, inject as inject5 } from "vue";
145
+
146
+ // src/utils/findBestPrice.ts
147
+ function findBestPrice(variations, currency, model) {
148
+ const prices = variations.filter((v) => v.model === model && v.prices[currency] !== void 0).map((v) => v.prices[currency]);
149
+ prices.sort((a, b) => b - a);
150
+ return prices.length === 0 ? 0 : prices[0];
151
+ }
152
+
153
+ // src/composables/useCart.ts
154
+ function useCart() {
155
+ const storefront = inject5(storefrontKey);
156
+ if (!storefront)
157
+ throw new Error("No storefront configured");
158
+ return {
159
+ items: computed5(() => storefront.currentOrder.value.items),
160
+ currency: computed5(() => storefront.currentOrder.value.currency || storefront.storefront.value.suggestedCurrency),
161
+ total: computed5(() => {
162
+ const currency = storefront.currentOrder.value.currency || storefront.storefront.value.suggestedCurrency;
163
+ const total = storefront.currentOrder.value.items.reduce((agg, item) => {
164
+ var _a, _b;
165
+ let bestPrice;
166
+ if (item.type === "Product") {
167
+ const variations = ((_a = useProduct(item.productId).value) == null ? void 0 : _a.pricing) || [];
168
+ bestPrice = findBestPrice(variations, currency, item.pricingModel);
169
+ } else {
170
+ const variations = ((_b = useBundle(item.bundleId).value) == null ? void 0 : _b.pricing) || [];
171
+ bestPrice = findBestPrice(variations, currency, PricingModel.Purchase);
172
+ }
173
+ return agg + bestPrice * item.quantity;
174
+ }, 0);
175
+ return { amount: total, currency };
176
+ }),
177
+ addToCart: (item, model = PricingModel.Purchase) => {
178
+ let lineItem = storefront.currentOrder.value.items.find((i) => i.type === "Product" && i.productId === item.id && i.pricingModel === model || i.type === "Bundle" && i.bundleId === item.id);
179
+ if (!lineItem) {
180
+ if (item.type === "bundle") {
181
+ lineItem = {
182
+ type: "Bundle",
183
+ bundleId: item.id,
184
+ bundle: item,
185
+ quantity: 1
186
+ };
187
+ storefront.currentOrder.value.items.push(lineItem);
188
+ } else if (item.type === "product") {
189
+ lineItem = {
190
+ type: "Product",
191
+ pricingModel: model,
192
+ productId: item.id,
193
+ product: item,
194
+ quantity: 1
195
+ };
196
+ storefront.currentOrder.value.items.push(lineItem);
197
+ }
198
+ } else {
199
+ lineItem.quantity += 1;
200
+ }
201
+ const _ = storefront.pushOrderContent();
202
+ },
203
+ removeFromCart: (cartItem) => {
204
+ const index = storefront.currentOrder.value.items.findIndex((i) => i.type === "Bundle" && cartItem.type === "Bundle" && i.bundleId === cartItem.bundleId || i.type === "Product" && cartItem.type === "Product" && i.productId === cartItem.productId);
205
+ storefront.currentOrder.value.items.splice(index, 1);
206
+ const _ = storefront.pushOrderContent();
207
+ },
208
+ checkout: async (returnUrl) => {
209
+ const absoluteReturnUrl = new URL(returnUrl, document.baseURI).href;
210
+ const updatedOrder = await storefront.client.orders.pushContent(storefront.currentOrder.value, {
211
+ returnUrl: absoluteReturnUrl
212
+ });
213
+ storefront.currentOrder.value = updatedOrder;
214
+ if (updatedOrder.checkoutUrl)
215
+ window.location.href = updatedOrder.checkoutUrl;
216
+ else
217
+ throw new Error("No checkout URL found");
218
+ }
219
+ };
220
+ }
221
+
222
+ // src/composables/useAuth.ts
223
+ import { inject as inject6 } from "vue";
224
+ function useAuth() {
225
+ const storefront = inject6(storefrontKey);
226
+ if (!storefront)
227
+ throw new Error("No storefront configured");
228
+ return {
229
+ user: storefront.currentUser,
230
+ loaded: storefront.loadedUser,
231
+ signIn: async (email, password) => {
232
+ const user = await storefront.client.identity.signIn(email, password);
233
+ storefront.currentUser.value = user;
234
+ const _ = storefront.updateStorefront();
235
+ return user;
236
+ },
237
+ update: async (name, email, emailConfirmationToken) => {
238
+ const result = await storefront.client.identity.update(name, email, emailConfirmationToken);
239
+ if (storefront.currentUser.value)
240
+ storefront.currentUser.value.name = name;
241
+ return result;
242
+ },
243
+ setPassword: async (currentPassword, newPassword) => {
244
+ if (!storefront.currentUser.value)
245
+ throw new Error("No user loaded");
246
+ await storefront.client.identity.setPassword(storefront.currentUser.value.email, currentPassword, newPassword);
247
+ },
248
+ forgotPassword: async (email) => {
249
+ await storefront.client.identity.forgotPassword(email);
250
+ },
251
+ resetPassword: async (email, newPassword, code) => {
252
+ await storefront.client.identity.resetPassword(email, newPassword, code);
253
+ }
254
+ };
255
+ }
256
+
257
+ // src/index.ts
258
+ function createStorefront(endpoint) {
259
+ const configuration = {
260
+ endpoint
261
+ };
262
+ return new StorefrontContextImpl(configuration, new MoonbaseClient(configuration));
263
+ }
264
+ export {
265
+ createStorefront,
266
+ findBestPrice,
267
+ storefrontKey,
268
+ useAuth,
269
+ useBundle,
270
+ useBundles,
271
+ useCart,
272
+ useProduct,
273
+ useProducts
274
+ };
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@moonbase.sh/vue",
3
+ "type": "module",
4
+ "version": "0.1.25",
5
+ "description": "Package to let you build vue.js storefronts with Moonbase.sh as payment and delivery provider",
6
+ "author": "Tobias Lønnerød Madsen <m@dsen.tv>",
7
+ "license": "MIT",
8
+ "sideEffects": false,
9
+ "main": "./dist/index.js",
10
+ "module": "./dist/index.js",
11
+ "types": "./dist/index.d.ts",
12
+ "files": [
13
+ "dist/**"
14
+ ],
15
+ "scripts": {
16
+ "build": "tsup src/index.ts --format esm,cjs --dts",
17
+ "dev": "tsup src/index.ts --format esm,cjs --watch --dts"
18
+ },
19
+ "dependencies": {
20
+ "@moonbase.sh/api-client": "workspace:*",
21
+ "@vue/devtools-api": "^6.5.0",
22
+ "uuid": "^9.0.0"
23
+ },
24
+ "peerDependencies": {
25
+ "vue": "^3.2.0"
26
+ },
27
+ "devDependencies": {
28
+ "@types/uuid": "^9.0.1",
29
+ "rimraf": "^5.0.0",
30
+ "tsup": "^7.1.0",
31
+ "typescript": "~5.1.6",
32
+ "vue": "^3.3.4"
33
+ }
34
+ }