@capivv/capacitor-sdk 0.1.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/dist/plugin.js ADDED
@@ -0,0 +1,664 @@
1
+ var capacitorCapivv = (function (exports, core) {
2
+ 'use strict';
3
+
4
+ /**
5
+ * Product type for purchases
6
+ */
7
+ exports.ProductType = void 0;
8
+ (function (ProductType) {
9
+ /** One-time purchase */
10
+ ProductType["INAPP"] = "INAPP";
11
+ /** Subscription */
12
+ ProductType["SUBSCRIPTION"] = "SUBSCRIPTION";
13
+ })(exports.ProductType || (exports.ProductType = {}));
14
+ /**
15
+ * Purchase state
16
+ */
17
+ exports.PurchaseState = void 0;
18
+ (function (PurchaseState) {
19
+ PurchaseState["PENDING"] = "PENDING";
20
+ PurchaseState["PURCHASED"] = "PURCHASED";
21
+ PurchaseState["FAILED"] = "FAILED";
22
+ })(exports.PurchaseState || (exports.PurchaseState = {}));
23
+
24
+ /**
25
+ * Capivv SDK Localization
26
+ *
27
+ * Provides localized strings for the Capivv SDK UI components.
28
+ */
29
+ const translations = {
30
+ en: {
31
+ 'common.continue': 'Continue',
32
+ 'common.cancel': 'Cancel',
33
+ 'common.close': 'Close',
34
+ 'common.done': 'Done',
35
+ 'common.loading': 'Loading...',
36
+ 'common.processing': 'Processing...',
37
+ 'common.error': 'Error',
38
+ 'common.success': 'Success',
39
+ 'common.tryAgain': 'Try Again',
40
+ 'paywall.restore': 'Restore Purchases',
41
+ 'paywall.restoring': 'Restoring...',
42
+ 'paywall.purchasing': 'Purchasing...',
43
+ 'paywall.startTrial': 'Start %d-day free trial',
44
+ 'paywall.then': 'Then %@',
45
+ 'paywall.perMonth': '/month',
46
+ 'paywall.perYear': '/year',
47
+ 'paywall.perWeek': '/week',
48
+ 'paywall.bestValue': 'Best Value',
49
+ 'paywall.mostPopular': 'Most Popular',
50
+ 'paywall.save': 'Save %d%%',
51
+ 'paywall.freeTrialIncluded': 'Free trial included',
52
+ 'paywall.termsAndPrivacy': 'Terms of Service & Privacy Policy',
53
+ 'paywall.legalDisclaimer': 'Payment will be charged to your account at confirmation of purchase. Subscription automatically renews unless it is canceled at least 24 hours before the end of the current period.',
54
+ 'paywall.unlockPremium': 'Unlock Premium',
55
+ 'paywall.noProductsAvailable': 'No products available',
56
+ 'error.unableToLoad': 'Unable to Load',
57
+ 'error.purchaseFailed': 'Purchase Failed',
58
+ 'error.restoreFailed': 'Restore Failed',
59
+ 'error.networkError': 'Network Error',
60
+ 'error.somethingWentWrong': 'Something went wrong',
61
+ 'error.dismiss': 'Dismiss',
62
+ 'error.failedToLoadOfferings': 'Failed to load offerings',
63
+ 'faq.title': 'Frequently Asked Questions',
64
+ 'socialProof.rating': 'Rating',
65
+ 'socialProof.reviews': 'reviews',
66
+ 'socialProof.downloads': 'downloads',
67
+ 'countdown.days': 'd',
68
+ 'countdown.hours': 'h',
69
+ 'countdown.minutes': 'm',
70
+ 'countdown.seconds': 's',
71
+ },
72
+ es: {
73
+ 'common.continue': 'Continuar',
74
+ 'common.cancel': 'Cancelar',
75
+ 'common.close': 'Cerrar',
76
+ 'common.done': 'Hecho',
77
+ 'common.loading': 'Cargando...',
78
+ 'common.processing': 'Procesando...',
79
+ 'common.error': 'Error',
80
+ 'common.success': 'Exito',
81
+ 'common.tryAgain': 'Intentar de nuevo',
82
+ 'paywall.restore': 'Restaurar compras',
83
+ 'paywall.restoring': 'Restaurando...',
84
+ 'paywall.purchasing': 'Comprando...',
85
+ 'paywall.startTrial': 'Comenzar prueba de %d dias',
86
+ 'paywall.then': 'Luego %@',
87
+ 'paywall.perMonth': '/mes',
88
+ 'paywall.perYear': '/ano',
89
+ 'paywall.perWeek': '/semana',
90
+ 'paywall.bestValue': 'Mejor valor',
91
+ 'paywall.mostPopular': 'Mas popular',
92
+ 'paywall.save': 'Ahorra %d%%',
93
+ 'paywall.freeTrialIncluded': 'Prueba gratuita incluida',
94
+ 'paywall.termsAndPrivacy': 'Terminos de servicio y politica de privacidad',
95
+ 'paywall.legalDisclaimer': 'El pago se cargara a su cuenta en la confirmacion de la compra. La suscripcion se renueva automaticamente a menos que se cancele al menos 24 horas antes del final del periodo actual.',
96
+ 'paywall.unlockPremium': 'Desbloquear Premium',
97
+ 'paywall.noProductsAvailable': 'No hay productos disponibles',
98
+ 'error.unableToLoad': 'No se puede cargar',
99
+ 'error.purchaseFailed': 'Compra fallida',
100
+ 'error.restoreFailed': 'Restauracion fallida',
101
+ 'error.networkError': 'Error de red',
102
+ 'error.somethingWentWrong': 'Algo salio mal',
103
+ 'error.dismiss': 'Descartar',
104
+ 'error.failedToLoadOfferings': 'Error al cargar ofertas',
105
+ 'faq.title': 'Preguntas frecuentes',
106
+ 'socialProof.rating': 'Calificacion',
107
+ 'socialProof.reviews': 'resenas',
108
+ 'socialProof.downloads': 'descargas',
109
+ 'countdown.days': 'd',
110
+ 'countdown.hours': 'h',
111
+ 'countdown.minutes': 'm',
112
+ 'countdown.seconds': 's',
113
+ },
114
+ fr: {
115
+ 'common.continue': 'Continuer',
116
+ 'common.cancel': 'Annuler',
117
+ 'common.close': 'Fermer',
118
+ 'common.done': 'Termine',
119
+ 'common.loading': 'Chargement...',
120
+ 'common.processing': 'Traitement...',
121
+ 'common.error': 'Erreur',
122
+ 'common.success': 'Succes',
123
+ 'common.tryAgain': 'Reessayer',
124
+ 'paywall.restore': 'Restaurer les achats',
125
+ 'paywall.restoring': 'Restauration...',
126
+ 'paywall.purchasing': 'Achat...',
127
+ 'paywall.startTrial': "Commencer l'essai de %d jours",
128
+ 'paywall.then': 'Puis %@',
129
+ 'paywall.perMonth': '/mois',
130
+ 'paywall.perYear': '/an',
131
+ 'paywall.perWeek': '/semaine',
132
+ 'paywall.bestValue': 'Meilleur rapport qualite-prix',
133
+ 'paywall.mostPopular': 'Le plus populaire',
134
+ 'paywall.save': 'Economisez %d%%',
135
+ 'paywall.freeTrialIncluded': 'Essai gratuit inclus',
136
+ 'paywall.termsAndPrivacy': "Conditions d'utilisation et politique de confidentialite",
137
+ 'paywall.legalDisclaimer': "Le paiement sera debite de votre compte lors de la confirmation de l'achat. L'abonnement se renouvelle automatiquement sauf annulation au moins 24 heures avant la fin de la periode en cours.",
138
+ 'paywall.unlockPremium': 'Debloquer Premium',
139
+ 'paywall.noProductsAvailable': 'Aucun produit disponible',
140
+ 'error.unableToLoad': 'Impossible de charger',
141
+ 'error.purchaseFailed': "Echec de l'achat",
142
+ 'error.restoreFailed': 'Echec de la restauration',
143
+ 'error.networkError': 'Erreur reseau',
144
+ 'error.somethingWentWrong': "Une erreur s'est produite",
145
+ 'error.dismiss': 'Fermer',
146
+ 'error.failedToLoadOfferings': 'Echec du chargement des offres',
147
+ 'faq.title': 'Questions frequentes',
148
+ 'socialProof.rating': 'Note',
149
+ 'socialProof.reviews': 'avis',
150
+ 'socialProof.downloads': 'telechargements',
151
+ 'countdown.days': 'j',
152
+ 'countdown.hours': 'h',
153
+ 'countdown.minutes': 'm',
154
+ 'countdown.seconds': 's',
155
+ },
156
+ de: {
157
+ 'common.continue': 'Fortfahren',
158
+ 'common.cancel': 'Abbrechen',
159
+ 'common.close': 'Schliessen',
160
+ 'common.done': 'Fertig',
161
+ 'common.loading': 'Laden...',
162
+ 'common.processing': 'Verarbeitung...',
163
+ 'common.error': 'Fehler',
164
+ 'common.success': 'Erfolg',
165
+ 'common.tryAgain': 'Erneut versuchen',
166
+ 'paywall.restore': 'Kaufe wiederherstellen',
167
+ 'paywall.restoring': 'Wiederherstellen...',
168
+ 'paywall.purchasing': 'Kaufen...',
169
+ 'paywall.startTrial': '%d-tagige Testversion starten',
170
+ 'paywall.then': 'Dann %@',
171
+ 'paywall.perMonth': '/Monat',
172
+ 'paywall.perYear': '/Jahr',
173
+ 'paywall.perWeek': '/Woche',
174
+ 'paywall.bestValue': 'Bester Wert',
175
+ 'paywall.mostPopular': 'Am beliebtesten',
176
+ 'paywall.save': '%d%% sparen',
177
+ 'paywall.freeTrialIncluded': 'Kostenlose Testversion enthalten',
178
+ 'paywall.termsAndPrivacy': 'Nutzungsbedingungen und Datenschutz',
179
+ 'paywall.legalDisclaimer': 'Die Zahlung wird bei Kaufbestatigung von Ihrem Konto abgebucht. Das Abonnement verlangert sich automatisch, sofern es nicht mindestens 24 Stunden vor Ende des aktuellen Zeitraums gekundigt wird.',
180
+ 'paywall.unlockPremium': 'Premium freischalten',
181
+ 'paywall.noProductsAvailable': 'Keine Produkte verfugbar',
182
+ 'error.unableToLoad': 'Laden nicht moglich',
183
+ 'error.purchaseFailed': 'Kauf fehlgeschlagen',
184
+ 'error.restoreFailed': 'Wiederherstellung fehlgeschlagen',
185
+ 'error.networkError': 'Netzwerkfehler',
186
+ 'error.somethingWentWrong': 'Etwas ist schief gelaufen',
187
+ 'error.dismiss': 'Schliessen',
188
+ 'error.failedToLoadOfferings': 'Angebote konnten nicht geladen werden',
189
+ 'faq.title': 'Haufig gestellte Fragen',
190
+ 'socialProof.rating': 'Bewertung',
191
+ 'socialProof.reviews': 'Bewertungen',
192
+ 'socialProof.downloads': 'Downloads',
193
+ 'countdown.days': 'T',
194
+ 'countdown.hours': 'Std',
195
+ 'countdown.minutes': 'Min',
196
+ 'countdown.seconds': 'Sek',
197
+ },
198
+ ja: {
199
+ 'common.continue': '続ける',
200
+ 'common.cancel': 'キャンセル',
201
+ 'common.close': '閉じる',
202
+ 'common.done': '完了',
203
+ 'common.loading': '読み込み中...',
204
+ 'common.processing': '処理中...',
205
+ 'common.error': 'エラー',
206
+ 'common.success': '成功',
207
+ 'common.tryAgain': '再試行',
208
+ 'paywall.restore': '購入を復元',
209
+ 'paywall.restoring': '復元中...',
210
+ 'paywall.purchasing': '購入中...',
211
+ 'paywall.startTrial': '%d日間の無料トライアルを開始',
212
+ 'paywall.then': 'その後 %@',
213
+ 'paywall.perMonth': '/月',
214
+ 'paywall.perYear': '/年',
215
+ 'paywall.perWeek': '/週',
216
+ 'paywall.bestValue': 'ベストバリュー',
217
+ 'paywall.mostPopular': '最も人気',
218
+ 'paywall.save': '%d%%オフ',
219
+ 'paywall.freeTrialIncluded': '無料トライアル付き',
220
+ 'paywall.termsAndPrivacy': '利用規約とプライバシーポリシー',
221
+ 'paywall.legalDisclaimer': '購入確認時にアカウントに請求されます。現在の期間終了の24時間前までにキャンセルしない限り、サブスクリプションは自動更新されます。',
222
+ 'paywall.unlockPremium': 'プレミアムを解除',
223
+ 'paywall.noProductsAvailable': '利用可能な製品がありません',
224
+ 'error.unableToLoad': '読み込めません',
225
+ 'error.purchaseFailed': '購入に失敗しました',
226
+ 'error.restoreFailed': '復元に失敗しました',
227
+ 'error.networkError': 'ネットワークエラー',
228
+ 'error.somethingWentWrong': '問題が発生しました',
229
+ 'error.dismiss': '閉じる',
230
+ 'error.failedToLoadOfferings': 'オファーの読み込みに失敗しました',
231
+ 'faq.title': 'よくある質問',
232
+ 'socialProof.rating': '評価',
233
+ 'socialProof.reviews': 'レビュー',
234
+ 'socialProof.downloads': 'ダウンロード',
235
+ 'countdown.days': '日',
236
+ 'countdown.hours': '時',
237
+ 'countdown.minutes': '分',
238
+ 'countdown.seconds': '秒',
239
+ },
240
+ zh: {
241
+ 'common.continue': '继续',
242
+ 'common.cancel': '取消',
243
+ 'common.close': '关闭',
244
+ 'common.done': '完成',
245
+ 'common.loading': '加载中...',
246
+ 'common.processing': '处理中...',
247
+ 'common.error': '错误',
248
+ 'common.success': '成功',
249
+ 'common.tryAgain': '重试',
250
+ 'paywall.restore': '恢复购买',
251
+ 'paywall.restoring': '恢复中...',
252
+ 'paywall.purchasing': '购买中...',
253
+ 'paywall.startTrial': '开始%d天免费试用',
254
+ 'paywall.then': '然后 %@',
255
+ 'paywall.perMonth': '/月',
256
+ 'paywall.perYear': '/年',
257
+ 'paywall.perWeek': '/周',
258
+ 'paywall.bestValue': '最佳价值',
259
+ 'paywall.mostPopular': '最受欢迎',
260
+ 'paywall.save': '节省%d%%',
261
+ 'paywall.freeTrialIncluded': '含免费试用',
262
+ 'paywall.termsAndPrivacy': '服务条款和隐私政策',
263
+ 'paywall.legalDisclaimer': '确认购买后将从您的账户扣款。除非在当前周期结束前至少24小时取消,否则订阅将自动续订。',
264
+ 'paywall.unlockPremium': '解锁高级版',
265
+ 'paywall.noProductsAvailable': '没有可用的产品',
266
+ 'error.unableToLoad': '无法加载',
267
+ 'error.purchaseFailed': '购买失败',
268
+ 'error.restoreFailed': '恢复失败',
269
+ 'error.networkError': '网络错误',
270
+ 'error.somethingWentWrong': '出了点问题',
271
+ 'error.dismiss': '关闭',
272
+ 'error.failedToLoadOfferings': '加载产品失败',
273
+ 'faq.title': '常见问题',
274
+ 'socialProof.rating': '评分',
275
+ 'socialProof.reviews': '评论',
276
+ 'socialProof.downloads': '下载',
277
+ 'countdown.days': '天',
278
+ 'countdown.hours': '时',
279
+ 'countdown.minutes': '分',
280
+ 'countdown.seconds': '秒',
281
+ },
282
+ pt: {
283
+ 'common.continue': 'Continuar',
284
+ 'common.cancel': 'Cancelar',
285
+ 'common.close': 'Fechar',
286
+ 'common.done': 'Concluido',
287
+ 'common.loading': 'Carregando...',
288
+ 'common.processing': 'Processando...',
289
+ 'common.error': 'Erro',
290
+ 'common.success': 'Sucesso',
291
+ 'common.tryAgain': 'Tentar novamente',
292
+ 'paywall.restore': 'Restaurar compras',
293
+ 'paywall.restoring': 'Restaurando...',
294
+ 'paywall.purchasing': 'Comprando...',
295
+ 'paywall.startTrial': 'Iniciar teste de %d dias',
296
+ 'paywall.then': 'Depois %@',
297
+ 'paywall.perMonth': '/mes',
298
+ 'paywall.perYear': '/ano',
299
+ 'paywall.perWeek': '/semana',
300
+ 'paywall.bestValue': 'Melhor valor',
301
+ 'paywall.mostPopular': 'Mais popular',
302
+ 'paywall.save': 'Economize %d%%',
303
+ 'paywall.freeTrialIncluded': 'Teste gratuito incluso',
304
+ 'paywall.termsAndPrivacy': 'Termos de servico e politica de privacidade',
305
+ 'paywall.legalDisclaimer': 'O pagamento sera cobrado em sua conta na confirmacao da compra. A assinatura e renovada automaticamente, a menos que seja cancelada pelo menos 24 horas antes do final do periodo atual.',
306
+ 'paywall.unlockPremium': 'Desbloquear Premium',
307
+ 'paywall.noProductsAvailable': 'Nenhum produto disponivel',
308
+ 'error.unableToLoad': 'Nao foi possivel carregar',
309
+ 'error.purchaseFailed': 'Falha na compra',
310
+ 'error.restoreFailed': 'Falha na restauracao',
311
+ 'error.networkError': 'Erro de rede',
312
+ 'error.somethingWentWrong': 'Algo deu errado',
313
+ 'error.dismiss': 'Fechar',
314
+ 'error.failedToLoadOfferings': 'Falha ao carregar ofertas',
315
+ 'faq.title': 'Perguntas frequentes',
316
+ 'socialProof.rating': 'Avaliacao',
317
+ 'socialProof.reviews': 'avaliacoes',
318
+ 'socialProof.downloads': 'downloads',
319
+ 'countdown.days': 'd',
320
+ 'countdown.hours': 'h',
321
+ 'countdown.minutes': 'm',
322
+ 'countdown.seconds': 's',
323
+ },
324
+ it: {
325
+ 'common.continue': 'Continua',
326
+ 'common.cancel': 'Annulla',
327
+ 'common.close': 'Chiudi',
328
+ 'common.done': 'Fatto',
329
+ 'common.loading': 'Caricamento...',
330
+ 'common.processing': 'Elaborazione...',
331
+ 'common.error': 'Errore',
332
+ 'common.success': 'Successo',
333
+ 'common.tryAgain': 'Riprova',
334
+ 'paywall.restore': 'Ripristina acquisti',
335
+ 'paywall.restoring': 'Ripristino...',
336
+ 'paywall.purchasing': 'Acquisto...',
337
+ 'paywall.startTrial': 'Inizia prova gratuita di %d giorni',
338
+ 'paywall.then': 'Poi %@',
339
+ 'paywall.perMonth': '/mese',
340
+ 'paywall.perYear': '/anno',
341
+ 'paywall.perWeek': '/settimana',
342
+ 'paywall.bestValue': 'Miglior valore',
343
+ 'paywall.mostPopular': 'Piu popolare',
344
+ 'paywall.save': 'Risparmia %d%%',
345
+ 'paywall.freeTrialIncluded': 'Prova gratuita inclusa',
346
+ 'paywall.termsAndPrivacy': 'Termini di servizio e privacy',
347
+ 'paywall.legalDisclaimer': "Il pagamento verra addebitato sul tuo account alla conferma dell'acquisto. L'abbonamento si rinnova automaticamente a meno che non venga annullato almeno 24 ore prima della fine del periodo corrente.",
348
+ 'paywall.unlockPremium': 'Sblocca Premium',
349
+ 'paywall.noProductsAvailable': 'Nessun prodotto disponibile',
350
+ 'error.unableToLoad': 'Impossibile caricare',
351
+ 'error.purchaseFailed': 'Acquisto fallito',
352
+ 'error.restoreFailed': 'Ripristino fallito',
353
+ 'error.networkError': 'Errore di rete',
354
+ 'error.somethingWentWrong': 'Qualcosa e andato storto',
355
+ 'error.dismiss': 'Chiudi',
356
+ 'error.failedToLoadOfferings': 'Impossibile caricare le offerte',
357
+ 'faq.title': 'Domande frequenti',
358
+ 'socialProof.rating': 'Valutazione',
359
+ 'socialProof.reviews': 'recensioni',
360
+ 'socialProof.downloads': 'download',
361
+ 'countdown.days': 'g',
362
+ 'countdown.hours': 'h',
363
+ 'countdown.minutes': 'm',
364
+ 'countdown.seconds': 's',
365
+ },
366
+ };
367
+ /**
368
+ * Get the current locale from navigator
369
+ */
370
+ function getCurrentLocale() {
371
+ if (typeof navigator !== 'undefined' && navigator.language) {
372
+ const lang = navigator.language.split('-')[0];
373
+ if (lang in translations) {
374
+ return lang;
375
+ }
376
+ }
377
+ return 'en';
378
+ }
379
+ /**
380
+ * Capivv L10n helper
381
+ */
382
+ class CapivvL10n {
383
+ locale;
384
+ constructor(locale) {
385
+ this.locale = locale || getCurrentLocale();
386
+ }
387
+ /**
388
+ * Get a localized string by key
389
+ */
390
+ get(key) {
391
+ return translations[this.locale][key] || translations.en[key] || key;
392
+ }
393
+ /**
394
+ * Get a formatted string with placeholder replacement
395
+ */
396
+ format(key, ...args) {
397
+ let str = this.get(key);
398
+ args.forEach((arg, index) => {
399
+ str = str.replace(`%${index === 0 ? 'd' : '@'}`, String(arg));
400
+ });
401
+ return str;
402
+ }
403
+ /**
404
+ * Set the locale
405
+ */
406
+ setLocale(locale) {
407
+ this.locale = locale;
408
+ }
409
+ /**
410
+ * Get the current locale
411
+ */
412
+ getLocale() {
413
+ return this.locale;
414
+ }
415
+ }
416
+ // Export singleton instance
417
+ const l10n = new CapivvL10n();
418
+
419
+ const Capivv = core.registerPlugin('Capivv', {
420
+ web: () => Promise.resolve().then(function () { return web; }).then((m) => new m.CapivvWeb()),
421
+ });
422
+
423
+ /**
424
+ * Web implementation of the Capivv plugin.
425
+ * Uses the Capivv REST API directly for web platforms.
426
+ * Stripe integration can be added for web purchases.
427
+ */
428
+ class CapivvWeb extends core.WebPlugin {
429
+ capivvConfig = null;
430
+ userId = null;
431
+ apiUrl = 'https://api.capivv.com';
432
+ async configure(config) {
433
+ this.capivvConfig = config;
434
+ if (config.apiUrl) {
435
+ this.apiUrl = config.apiUrl;
436
+ }
437
+ if (config.debug) {
438
+ console.log('[Capivv] Configured with API URL:', this.apiUrl);
439
+ }
440
+ }
441
+ async identify(options) {
442
+ this.ensureConfigured();
443
+ this.userId = options.userId;
444
+ const response = await this.apiRequest('POST', `/v1/users/${options.userId}/login`, {
445
+ attributes: options.attributes,
446
+ });
447
+ const data = response;
448
+ return {
449
+ userId: options.userId,
450
+ entitlements: data.entitlements || [],
451
+ originalPurchaseDate: data.original_purchase_date,
452
+ latestPurchaseDate: data.latest_purchase_date,
453
+ };
454
+ }
455
+ async logout() {
456
+ this.userId = null;
457
+ }
458
+ async getUserInfo() {
459
+ this.ensureConfigured();
460
+ this.ensureIdentified();
461
+ const response = await this.apiRequest('GET', `/v1/users/${this.userId}/entitlements`);
462
+ const data = response;
463
+ return {
464
+ userId: this.userId,
465
+ entitlements: data.entitlements || [],
466
+ };
467
+ }
468
+ async isBillingSupported() {
469
+ // Web platform always supports billing via Stripe
470
+ return { isSupported: true };
471
+ }
472
+ async getOfferings() {
473
+ this.ensureConfigured();
474
+ const response = await this.apiRequest('GET', '/v1/offerings');
475
+ const data = response;
476
+ return {
477
+ offerings: (data.offerings || []).map(this.mapOffering),
478
+ };
479
+ }
480
+ async getProduct(options) {
481
+ this.ensureConfigured();
482
+ const offerings = await this.getOfferings();
483
+ for (const offering of offerings.offerings) {
484
+ const product = offering.products.find((p) => p.identifier === options.productIdentifier);
485
+ if (product) {
486
+ return { product };
487
+ }
488
+ }
489
+ throw new Error(`Product not found: ${options.productIdentifier}`);
490
+ }
491
+ async getProducts(options) {
492
+ this.ensureConfigured();
493
+ const offerings = await this.getOfferings();
494
+ const products = [];
495
+ for (const offering of offerings.offerings) {
496
+ for (const product of offering.products) {
497
+ if (options.productIdentifiers.includes(product.identifier)) {
498
+ products.push(product);
499
+ }
500
+ }
501
+ }
502
+ return { products };
503
+ }
504
+ async purchase(options) {
505
+ this.ensureConfigured();
506
+ this.ensureIdentified();
507
+ // For web, we would integrate with Stripe Checkout here
508
+ // This is a placeholder that returns an error suggesting native platforms
509
+ console.warn('[Capivv] Web purchases require Stripe integration. Configure Stripe in your Capivv dashboard.');
510
+ // TODO: Implement Stripe Checkout integration
511
+ // 1. Create checkout session via Capivv API
512
+ // 2. Redirect to Stripe Checkout
513
+ // 3. Handle success/cancel callbacks
514
+ return {
515
+ success: false,
516
+ error: 'Web purchases not yet implemented. Use iOS or Android for native purchases.',
517
+ };
518
+ }
519
+ async restorePurchases() {
520
+ this.ensureConfigured();
521
+ this.ensureIdentified();
522
+ // Web doesn't have local purchases to restore
523
+ // Just fetch current entitlements from server
524
+ const response = await this.apiRequest('GET', `/v1/users/${this.userId}/entitlements`);
525
+ const restoreData = response;
526
+ return {
527
+ entitlements: restoreData.entitlements || [],
528
+ };
529
+ }
530
+ async checkEntitlement(options) {
531
+ this.ensureConfigured();
532
+ this.ensureIdentified();
533
+ const response = await this.apiRequest('GET', `/v1/users/${this.userId}/entitlements`);
534
+ const checkData = response;
535
+ const entitlements = checkData.entitlements || [];
536
+ const entitlement = entitlements.find((e) => e.identifier === options.entitlementIdentifier);
537
+ return {
538
+ hasAccess: entitlement?.isActive ?? false,
539
+ entitlement,
540
+ };
541
+ }
542
+ async getEntitlements() {
543
+ this.ensureConfigured();
544
+ this.ensureIdentified();
545
+ const response = await this.apiRequest('GET', `/v1/users/${this.userId}/entitlements`);
546
+ const entData = response;
547
+ return {
548
+ entitlements: entData.entitlements || [],
549
+ };
550
+ }
551
+ async syncPurchases() {
552
+ // Web doesn't have local purchases to sync
553
+ return this.getEntitlements();
554
+ }
555
+ async manageSubscriptions() {
556
+ // For web, we could redirect to a customer portal
557
+ // For now, log a warning
558
+ console.warn('[Capivv] Subscription management on web requires Stripe Customer Portal integration.');
559
+ }
560
+ /**
561
+ * Get a paywall template by identifier for OTA updates.
562
+ */
563
+ async getPaywallTemplate(identifier) {
564
+ this.ensureConfigured();
565
+ try {
566
+ const response = await this.apiRequest('GET', `/v1/paywalls/by-identifier/${identifier}/template`);
567
+ const data = response;
568
+ return {
569
+ template: data.template,
570
+ version: data.version || '1.0.0',
571
+ updatedAt: data.updated_at || new Date().toISOString(),
572
+ cacheTtlSeconds: data.cache_ttl_seconds,
573
+ };
574
+ }
575
+ catch (e) {
576
+ if (this.capivvConfig?.debug) {
577
+ console.log(`[Capivv] Template not available for ${identifier}:`, e);
578
+ }
579
+ // Return empty result for graceful fallback
580
+ return {
581
+ template: null,
582
+ version: '0.0.0',
583
+ updatedAt: new Date().toISOString(),
584
+ };
585
+ }
586
+ }
587
+ /**
588
+ * Get offerings and template in parallel for a paywall.
589
+ */
590
+ async getPaywallWithTemplate(identifier) {
591
+ this.ensureConfigured();
592
+ const [offeringsResult, templateResult] = await Promise.all([
593
+ this.getOfferings(),
594
+ this.getPaywallTemplate(identifier),
595
+ ]);
596
+ return {
597
+ offerings: offeringsResult.offerings,
598
+ template: templateResult.template,
599
+ };
600
+ }
601
+ // Helper methods
602
+ ensureConfigured() {
603
+ if (!this.capivvConfig) {
604
+ throw new Error('Capivv not configured. Call configure() first.');
605
+ }
606
+ }
607
+ ensureIdentified() {
608
+ if (!this.userId) {
609
+ throw new Error('User not identified. Call identify() first.');
610
+ }
611
+ }
612
+ async apiRequest(method, path, body) {
613
+ const url = `${this.apiUrl}${path}`;
614
+ const headers = {
615
+ 'Content-Type': 'application/json',
616
+ 'X-Capivv-Api-Key': this.capivvConfig.apiKey,
617
+ };
618
+ const options = {
619
+ method,
620
+ headers,
621
+ };
622
+ if (body && method !== 'GET') {
623
+ options.body = JSON.stringify(body);
624
+ }
625
+ const response = await fetch(url, options);
626
+ if (!response.ok) {
627
+ const error = await response.text();
628
+ throw new Error(`API error (${response.status}): ${error}`);
629
+ }
630
+ return response.json();
631
+ }
632
+ mapOffering(offering) {
633
+ return {
634
+ identifier: offering.identifier,
635
+ description: offering.description,
636
+ products: (offering.products || []).map((p) => ({
637
+ identifier: p.identifier,
638
+ title: p.title,
639
+ description: p.description,
640
+ priceString: p.price_string,
641
+ priceAmountMicros: p.price_amount_micros,
642
+ currencyCode: p.currency_code,
643
+ productType: p.product_type,
644
+ subscriptionPeriod: p.subscription_period,
645
+ trialPeriod: p.trial_period,
646
+ })),
647
+ metadata: offering.metadata,
648
+ };
649
+ }
650
+ }
651
+
652
+ var web = /*#__PURE__*/Object.freeze({
653
+ __proto__: null,
654
+ CapivvWeb: CapivvWeb
655
+ });
656
+
657
+ exports.Capivv = Capivv;
658
+ exports.CapivvL10n = CapivvL10n;
659
+ exports.l10n = l10n;
660
+
661
+ return exports;
662
+
663
+ })({}, capacitorExports);
664
+ //# sourceMappingURL=plugin.js.map