@nextblock-cms/ecom 0.15.8 → 0.15.9

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.
@@ -2,10 +2,10 @@ import { createClient as H } from "@supabase/supabase-js";
2
2
  import Q from "crypto";
3
3
  import { Freemius as te } from "@freemius/sdk";
4
4
  import { hydrateFreemiusEnvFromDb as ne } from "../payment-config.es.js";
5
- import { normalizeOrderCustomerDetails as ie } from "../customer.es.js";
6
- import { getCouponQuote as se, recordCouponRedemption as oe } from "../coupon-server.es.js";
7
- import { upsertDefaultUserAddresses as ae, fillMissingUserProfileCheckoutDetails as ce } from "../customer-addresses.es.js";
8
- import { getDefaultCurrency as ue, resolveEffectivePriceForCurrency as le, isSaleWindowActive as z } from "../currency.es.js";
5
+ import { normalizeOrderCustomerDetails as se } from "../customer.es.js";
6
+ import { getCouponQuote as ie, recordCouponRedemption as oe } from "../coupon-server.es.js";
7
+ import { upsertDefaultUserAddresses as ce, fillMissingUserProfileCheckoutDetails as ae } from "../customer-addresses.es.js";
8
+ import { getDefaultCurrency as le, resolveEffectivePriceForCurrency as ue, isSaleWindowActive as z } from "../currency.es.js";
9
9
  function o(e) {
10
10
  const r = process.env[e];
11
11
  if (!r)
@@ -20,10 +20,10 @@ function de(e) {
20
20
  firstName: null,
21
21
  lastName: null
22
22
  };
23
- const [t, ...i] = r.split(/\s+/);
23
+ const [t, ...s] = r.split(/\s+/);
24
24
  return {
25
25
  firstName: t || null,
26
- lastName: i.length > 0 ? i.join(" ") : null
26
+ lastName: s.length > 0 ? s.join(" ") : null
27
27
  };
28
28
  }
29
29
  function G(e) {
@@ -41,13 +41,13 @@ function _e(e, r) {
41
41
  }
42
42
  function X(e, r) {
43
43
  for (const t of r) {
44
- const i = _e(e, t);
45
- if (i.length > 0)
46
- return i;
44
+ const s = _e(e, t);
45
+ if (s.length > 0)
46
+ return s;
47
47
  }
48
48
  return Array.isArray(e) ? e : [];
49
49
  }
50
- function D(e) {
50
+ function k(e) {
51
51
  if (e == null || e === "")
52
52
  return null;
53
53
  const r = Number(e);
@@ -77,22 +77,22 @@ function Ee() {
77
77
  }
78
78
  }
79
79
  function ge(e) {
80
- const r = Ee(), t = String(e), i = r?.[t], a = o("FREEMIUS_PRODUCT_ID"), d = o(
80
+ const r = Ee(), t = String(e), s = r?.[t], c = o("FREEMIUS_PRODUCT_ID"), d = o(
81
81
  "FREEMIUS_ECOMMERCE_SANDBOX_PUBLIC_KEY"
82
82
  ), f = o(
83
83
  "FREEMIUS_ECOMMERCE_SANDBOX_SECRET_KEY"
84
84
  );
85
- return i?.publicKey ? {
86
- publicKey: i.publicKey,
87
- secretKey: i.secretKey ?? null,
88
- apiKey: i.apiKey ?? null,
85
+ return s?.publicKey ? {
86
+ publicKey: s.publicKey,
87
+ secretKey: s.secretKey ?? null,
88
+ apiKey: s.apiKey ?? null,
89
89
  source: "product-map"
90
- } : process.env.FREEMIUS_SANDBOX_ENABLED === "true" && a && a === t && d ? {
90
+ } : process.env.FREEMIUS_SANDBOX_ENABLED === "true" && c && c === t && d ? {
91
91
  publicKey: d,
92
92
  secretKey: f,
93
93
  apiKey: o("FREEMIUS_API_KEY"),
94
94
  source: "single-product-sandbox-env"
95
- } : a && a === t && o("FREEMIUS_PUBLIC_KEY") ? {
95
+ } : c && c === t && o("FREEMIUS_PUBLIC_KEY") ? {
96
96
  publicKey: o("FREEMIUS_PUBLIC_KEY"),
97
97
  secretKey: o("FREEMIUS_SECRET_KEY"),
98
98
  apiKey: o("FREEMIUS_API_KEY"),
@@ -104,7 +104,7 @@ function ge(e) {
104
104
  source: "legacy-env"
105
105
  };
106
106
  }
107
- async function Se(e) {
107
+ async function ye(e) {
108
108
  if (!e.apiKey)
109
109
  throw new Error("Missing Freemius API key for SDK sandbox generation.");
110
110
  return new te({
@@ -114,84 +114,84 @@ async function Se(e) {
114
114
  publicKey: e.publicKey
115
115
  }).checkout.getSandboxParams();
116
116
  }
117
- class we {
117
+ class Ue {
118
118
  getProviderName() {
119
119
  return "Freemius";
120
120
  }
121
121
  async createCheckoutSession({
122
122
  items: r,
123
123
  customerEmail: t,
124
- customerPhone: i,
125
- userId: a,
124
+ customerPhone: s,
125
+ userId: c,
126
126
  billingAddress: d,
127
127
  shippingAddress: f,
128
128
  currencyCode: m,
129
- couponCode: K,
129
+ couponCode: b,
130
130
  couponContextItems: E
131
131
  }) {
132
- const c = process.env.NEXT_PUBLIC_SUPABASE_URL || process.env.SUPABASE_URL, u = process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.SUPABASE_SECRET_KEY;
133
- if (!c || !u)
132
+ const a = process.env.NEXT_PUBLIC_SUPABASE_URL || process.env.SUPABASE_URL, l = process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.SUPABASE_SECRET_KEY;
133
+ if (!a || !l)
134
134
  return { error: "Missing Supabase credentials for checkout (Service Key required).", url: null };
135
- const p = H(c, u);
135
+ const p = H(a, l);
136
136
  if (!r || r.length === 0)
137
137
  return { error: "Cart is empty", url: null };
138
138
  if (r.length !== 1)
139
139
  return { error: "Freemius items must be checked out one at a time.", url: null };
140
- const { data: g, error: U } = await p.from("currencies").select(
140
+ const { data: g, error: K } = await p.from("currencies").select(
141
141
  "code, symbol, exchange_rate, is_default, is_active, auto_sync_product_prices, auto_update_exchange_rate, exchange_rate_source, exchange_rate_updated_at, rounding_mode, rounding_increment, rounding_charm_amount"
142
142
  ).eq("is_active", !0).order("code", { ascending: !0 }), v = g ?? [];
143
- if (U || v.length === 0)
143
+ if (K || v.length === 0)
144
144
  return { error: "Failed to resolve store currencies", url: null };
145
- const j = ue(v), b = v.find((l) => l.code === (m || "").toUpperCase()) ?? j, S = r[0], { data: s, error: I } = await p.from("products").select("id, title, price, prices, sale_price, sale_prices, sale_start_at, sale_end_at, scheduled_price, scheduled_prices, scheduled_price_at, freemius_plan_id, freemius_product_id, trial_period_days, trial_requires_payment_method").eq("id", S.product_id).single();
146
- if (I || !s)
145
+ const j = le(v), w = v.find((u) => u.code === (m || "").toUpperCase()) ?? j, y = r[0], { data: i, error: I } = await p.from("products").select("id, title, price, prices, sale_price, sale_prices, sale_start_at, sale_end_at, scheduled_price, scheduled_prices, scheduled_price_at, freemius_plan_id, freemius_product_id, trial_period_days, trial_requires_payment_method").eq("id", y.product_id).single();
146
+ if (I || !i)
147
147
  return { error: "Product not found", url: null };
148
- const R = s.freemius_plan_id, P = s.freemius_product_id;
148
+ const R = i.freemius_plan_id, P = i.freemius_product_id;
149
149
  if (!R || !P)
150
150
  return { error: "Product is not configured for Freemius checkout (missing Plan ID or Product ID)", url: null };
151
- const k = le({
152
- prices: s.prices || {},
153
- salePrices: s.sale_prices || {},
154
- fallbackPrice: s.price,
155
- fallbackSalePrice: s.sale_price,
156
- saleStartAt: s.sale_start_at,
157
- saleEndAt: s.sale_end_at,
158
- scheduledPrice: s.scheduled_price,
159
- scheduledPrices: s.scheduled_prices || {},
160
- scheduledPriceAt: s.scheduled_price_at,
161
- currencyCode: b.code,
151
+ const D = ue({
152
+ prices: i.prices || {},
153
+ salePrices: i.sale_prices || {},
154
+ fallbackPrice: i.price,
155
+ fallbackSalePrice: i.sale_price,
156
+ saleStartAt: i.sale_start_at,
157
+ saleEndAt: i.sale_end_at,
158
+ scheduledPrice: i.scheduled_price,
159
+ scheduledPrices: i.scheduled_prices || {},
160
+ scheduledPriceAt: i.scheduled_price_at,
161
+ currencyCode: w.code,
162
162
  currencies: v
163
- }), N = k.sale_price ?? k.price, x = z({
164
- saleStartAt: s.sale_start_at,
165
- saleEndAt: s.sale_end_at
166
- }), y = N * S.quantity;
163
+ }), N = D.sale_price ?? D.price, x = z({
164
+ saleStartAt: i.sale_start_at,
165
+ saleEndAt: i.sale_end_at
166
+ }), S = N * y.quantity;
167
167
  let n = null, _ = 0;
168
- if (K) {
169
- const l = await se({
168
+ if (b) {
169
+ const u = await ie({
170
170
  client: p,
171
- code: K,
171
+ code: b,
172
172
  items: E && E.length > 0 ? E : r,
173
- currencyCode: b.code
173
+ currencyCode: w.code
174
174
  });
175
- if (!l.success)
175
+ if (!u.success)
176
176
  return {
177
- error: l.error,
178
- errorKey: l.errorKey,
177
+ error: u.error,
178
+ errorKey: u.errorKey,
179
179
  errorStatus: 400,
180
180
  url: null
181
181
  };
182
- n = l.quote, _ = Math.min(
183
- y,
184
- n.lineDiscounts.filter(($) => $.product_id === s.id).reduce(($, T) => $ + T.discount, 0)
182
+ n = u.quote, _ = Math.min(
183
+ S,
184
+ n.lineDiscounts.filter(($) => $.product_id === i.id).reduce(($, q) => $ + q.discount, 0)
185
185
  );
186
186
  }
187
- const F = G(s.trial_period_days), w = F > 0 ? S.trial_preference ? S.trial_preference : s.trial_requires_payment_method ? "paid" : "free" : null, B = "pending", h = de(
187
+ const F = G(i.trial_period_days), U = F > 0 ? y.trial_preference ? y.trial_preference : i.trial_requires_payment_method ? "paid" : "free" : null, B = "pending", h = de(
188
188
  d?.recipient_name ?? null
189
189
  ), { data: Y, error: V } = await p.from("orders").insert({
190
190
  status: B,
191
- total: Math.max(0, y - _),
192
- currency: b.code,
193
- exchange_rate_at_purchase: b.exchange_rate,
194
- subtotal: y,
191
+ total: Math.max(0, S - _),
192
+ currency: w.code,
193
+ exchange_rate_at_purchase: w.exchange_rate,
194
+ subtotal: S,
195
195
  discount_total: _,
196
196
  coupon_id: n?.couponId ?? null,
197
197
  coupon_code: n?.code ?? null,
@@ -207,10 +207,10 @@ class we {
207
207
  provider: "freemius",
208
208
  freemius_product_id: String(P),
209
209
  freemius_plan_id: String(R),
210
- user_id: a || null,
211
- customer_details: ie({
210
+ user_id: c || null,
211
+ customer_details: se({
212
212
  email: t,
213
- phone: i,
213
+ phone: s,
214
214
  name: d?.recipient_name,
215
215
  billing: d,
216
216
  shipping: f
@@ -220,27 +220,27 @@ class we {
220
220
  return console.error("Failed to create pending order:", V), { error: "Failed to initiate order", url: null };
221
221
  const { error: J } = await p.from("order_items").insert([{
222
222
  order_id: Y.id,
223
- product_id: s.id,
224
- quantity: S.quantity,
223
+ product_id: i.id,
224
+ quantity: y.quantity,
225
225
  price_at_purchase: N
226
226
  }]);
227
- if (J && console.error("Failed to insert order items:", J), a)
227
+ if (J && console.error("Failed to insert order items:", J), c)
228
228
  try {
229
- await ae({
230
- userId: a,
229
+ await ce({
230
+ userId: c,
231
231
  billingAddress: d,
232
232
  shippingAddress: f,
233
233
  client: p
234
- }), await ce({
235
- userId: a,
234
+ }), await ae({
235
+ userId: c,
236
236
  fullName: d?.recipient_name ?? f?.recipient_name ?? null,
237
- phone: i,
237
+ phone: s,
238
238
  client: p
239
239
  });
240
- } catch (l) {
240
+ } catch (u) {
241
241
  console.error(
242
242
  "Failed to sync checkout profile defaults before checkout:",
243
- l
243
+ u
244
244
  );
245
245
  }
246
246
  n && await oe({
@@ -249,63 +249,70 @@ class we {
249
249
  orderId: Y.id,
250
250
  provider: "freemius",
251
251
  discountTotal: _,
252
- userId: a,
252
+ userId: c,
253
253
  customerEmail: t,
254
254
  metadata: {
255
- currency: b.code,
256
- subtotal: y,
255
+ currency: w.code,
256
+ subtotal: S,
257
257
  final_amount_owned_by: "freemius"
258
258
  }
259
259
  }), await ne();
260
260
  const O = process.env.FREEMIUS_SANDBOX_ENABLED === "true", M = ge(P), A = M.publicKey, L = M.secretKey, W = M.apiKey;
261
261
  if (!A || O && !L)
262
- return { error: "Missing FREEMIUS credentials (PUBLIC_KEY or SECRET_KEY) in environment variables.", url: null };
262
+ return console.error(
263
+ "Freemius checkout blocked: missing credentials (PUBLIC_KEY or SECRET_KEY) in CMS → Payments or environment."
264
+ ), {
265
+ error: "This store is not able to take payments right now. Please contact the seller to complete your purchase.",
266
+ errorKey: "ecommerce.checkout_payments_unavailable",
267
+ errorStatus: 503,
268
+ url: null
269
+ };
263
270
  if (O && M.source === "legacy-env") {
264
- const l = o("FREEMIUS_PRODUCT_ID"), $ = !!o("FREEMIUS_ECOMMERCE_SANDBOX_PUBLIC_KEY"), T = !!o("FREEMIUS_ECOMMERCE_SANDBOX_SECRET_KEY");
271
+ const u = o("FREEMIUS_PRODUCT_ID"), $ = !!o("FREEMIUS_ECOMMERCE_SANDBOX_PUBLIC_KEY"), q = !!o("FREEMIUS_ECOMMERCE_SANDBOX_SECRET_KEY");
265
272
  console.warn(
266
273
  `[Freemius Checkout] Sandbox is enabled for product ${P}, but no product-scoped checkout credentials were selected. Falling back to legacy FREEMIUS_PUBLIC_KEY/FREEMIUS_SECRET_KEY may open live checkout instead of sandbox.`,
267
274
  {
268
- configuredProductId: l,
269
- productIdsMatch: l === String(P),
275
+ configuredProductId: u,
276
+ productIdsMatch: u === String(P),
270
277
  hasSandboxOverridePublicKey: $,
271
- hasSandboxOverrideSecretKey: T,
278
+ hasSandboxOverrideSecretKey: q,
272
279
  hasCheckoutProductsJson: !!o("FREEMIUS_CHECKOUT_PRODUCTS_JSON")
273
280
  }
274
281
  );
275
282
  }
276
- let q = !1;
283
+ let T = !1;
277
284
  if (O && L && A)
278
285
  try {
279
- q = await Se({
286
+ T = await ye({
280
287
  productId: P,
281
288
  publicKey: A,
282
289
  secretKey: L,
283
290
  apiKey: W
284
291
  });
285
- } catch (l) {
292
+ } catch (u) {
286
293
  console.warn(
287
294
  "Freemius Checkout - SDK sandbox generation failed. Falling back to manual token generation.",
288
- l,
295
+ u,
289
296
  {
290
297
  credentialSource: M.source,
291
298
  hasApiKey: !!W
292
299
  }
293
300
  );
294
- const $ = Math.floor(Date.now() / 1e3).toString(), T = `${$}${P}${L}${A}checkout`, re = Q.createHash("md5").update(T).digest("hex");
295
- q = {
301
+ const $ = Math.floor(Date.now() / 1e3).toString(), q = `${$}${P}${L}${A}checkout`, re = Q.createHash("md5").update(q).digest("hex");
302
+ T = {
296
303
  ctx: $,
297
304
  token: re
298
305
  };
299
306
  }
300
307
  const C = new URL(`https://checkout.freemius.com/app/${P}/plan/${R}/`);
301
- if (O && L && A ? (C.searchParams.append("sandbox", q.token), C.searchParams.append("s_ctx_ts", q.ctx)) : O && C.searchParams.append("sandbox", "true"), t && C.searchParams.append("user_email", t), h.firstName && C.searchParams.append("user_firstname", h.firstName), h.lastName && C.searchParams.append("user_lastname", h.lastName), C.searchParams.append("currency", b.code.toLowerCase()), S.billing_cycle && C.searchParams.append("billing_cycle", S.billing_cycle), w && C.searchParams.append("trial", w), n)
308
+ if (O && L && A ? (C.searchParams.append("sandbox", T.token), C.searchParams.append("s_ctx_ts", T.ctx)) : O && C.searchParams.append("sandbox", "true"), t && C.searchParams.append("user_email", t), h.firstName && C.searchParams.append("user_firstname", h.firstName), h.lastName && C.searchParams.append("user_lastname", h.lastName), C.searchParams.append("currency", w.code.toLowerCase()), y.billing_cycle && C.searchParams.append("billing_cycle", y.billing_cycle), U && C.searchParams.append("trial", U), n)
302
309
  C.searchParams.append("coupon", n.code);
303
310
  else if (x) {
304
- const { data: l } = await p.from("product_freemius_sale_coupons").select("freemius_coupon_code, is_active, starts_at, ends_at, sync_status").eq("product_id", s.id).maybeSingle();
305
- l?.is_active && l.sync_status === "synced" && l.freemius_coupon_code && z({
306
- saleStartAt: l.starts_at,
307
- saleEndAt: l.ends_at
308
- }) && C.searchParams.append("coupon", l.freemius_coupon_code);
311
+ const { data: u } = await p.from("product_freemius_sale_coupons").select("freemius_coupon_code, is_active, starts_at, ends_at, sync_status").eq("product_id", i.id).maybeSingle();
312
+ u?.is_active && u.sync_status === "synced" && u.freemius_coupon_code && z({
313
+ saleStartAt: u.starts_at,
314
+ saleEndAt: u.ends_at
315
+ }) && C.searchParams.append("coupon", u.freemius_coupon_code);
309
316
  }
310
317
  return {
311
318
  url: C.toString(),
@@ -318,11 +325,11 @@ class we {
318
325
  user_firstname: h.firstName,
319
326
  user_lastname: h.lastName,
320
327
  credential_source: M.source,
321
- sandbox: q,
322
- billing_cycle: S.billing_cycle,
323
- trial: w,
328
+ sandbox: T,
329
+ billing_cycle: y.billing_cycle,
330
+ trial: U,
324
331
  trial_period_days: F,
325
- trial_requires_payment_method: s.trial_requires_payment_method,
332
+ trial_requires_payment_method: i.trial_requires_payment_method,
326
333
  initial_order_status: B,
327
334
  coupon: n?.code ?? null,
328
335
  order_id: Y.id
@@ -330,54 +337,54 @@ class we {
330
337
  };
331
338
  }
332
339
  }
333
- async function Z(e, r, t, i) {
340
+ async function Z(e, r, t, s) {
334
341
  const d = (/* @__PURE__ */ new Date()).toUTCString().replace("GMT", "+0000"), f = `GET
335
342
 
336
343
 
337
344
  ${d}
338
- ${e}`, m = Q.createHmac("sha256", i).update(f).digest("hex"), K = Buffer.from(m).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""), E = `FS ${r}:${t}:${K}`, c = await fetch(`https://api.freemius.com${e}`, {
345
+ ${e}`, m = Q.createHmac("sha256", s).update(f).digest("hex"), b = Buffer.from(m).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""), E = `FS ${r}:${t}:${b}`, a = await fetch(`https://api.freemius.com${e}`, {
339
346
  headers: {
340
347
  Authorization: E,
341
348
  Date: d,
342
349
  Accept: "application/json"
343
350
  }
344
351
  });
345
- if (!c.ok) {
346
- const u = await c.text();
347
- throw console.error(`[Freemius API] [ERROR] ${e} returned ${c.status}: ${u}`), new Error(`Freemius API failed on ${e}: ${c.status} - ${u}`);
352
+ if (!a.ok) {
353
+ const l = await a.text();
354
+ throw console.error(`[Freemius API] [ERROR] ${e} returned ${a.status}: ${l}`), new Error(`Freemius API failed on ${e}: ${a.status} - ${l}`);
348
355
  }
349
- return c.json();
356
+ return a.json();
350
357
  }
351
358
  async function Re() {
352
- const e = o("FREEMIUS_DEVELOPER_ID"), r = o("FREEMIUS_PUBLIC_KEY"), t = o("FREEMIUS_SECRET_KEY"), i = process.env.NEXT_PUBLIC_SUPABASE_URL || process.env.SUPABASE_URL, a = process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.SUPABASE_SECRET_KEY;
353
- if (!e || !r || !t || !i || !a)
359
+ const e = o("FREEMIUS_DEVELOPER_ID"), r = o("FREEMIUS_PUBLIC_KEY"), t = o("FREEMIUS_SECRET_KEY"), s = process.env.NEXT_PUBLIC_SUPABASE_URL || process.env.SUPABASE_URL, c = process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.SUPABASE_SECRET_KEY;
360
+ if (!e || !r || !t || !s || !c)
354
361
  throw new Error("Missing necessary environment variables for Freemius Sync.");
355
- const d = H(i, a, {
362
+ const d = H(s, c, {
356
363
  auth: { autoRefreshToken: !1, persistSession: !1 }
357
364
  }), f = (m) => Z(m, e, r, t);
358
365
  try {
359
366
  console.log(`[Freemius Sync] Fetching all plugins for developer ${e}...`);
360
- const m = await f(`/v1/developers/${e}/plugins.json`), K = X(m, ["plugins", "plugin"]);
361
- console.log(`[Freemius Sync] Found ${K.length} plugins. Syncing plans...`);
367
+ const m = await f(`/v1/developers/${e}/plugins.json`), b = X(m, ["plugins", "plugin"]);
368
+ console.log(`[Freemius Sync] Found ${b.length} plugins. Syncing plans...`);
362
369
  let E = 0;
363
- const { data: c } = await d.from("languages").select("id").eq("code", "en").single(), u = c?.id;
364
- if (!u)
370
+ const { data: a } = await d.from("languages").select("id").eq("code", "en").single(), l = a?.id;
371
+ if (!l)
365
372
  throw new Error("English language not found in database. Cannot sync products.");
366
- for (const p of K) {
373
+ for (const p of b) {
367
374
  const g = p.id?.toString();
368
375
  if (!g) {
369
376
  console.warn("[Freemius Sync] Skipping plugin without an id:", p);
370
377
  continue;
371
378
  }
372
- const U = await ee(
379
+ const K = await ee(
373
380
  d,
374
381
  e,
375
382
  g,
376
383
  p.title || p.name || `Freemius Product ${g}`,
377
384
  f,
378
- u
385
+ l
379
386
  );
380
- E += U;
387
+ E += K;
381
388
  }
382
389
  return { success: !0, count: E };
383
390
  } catch (m) {
@@ -385,123 +392,123 @@ async function Re() {
385
392
  }
386
393
  }
387
394
  async function $e(e) {
388
- const r = o("FREEMIUS_DEVELOPER_ID"), t = o("FREEMIUS_PUBLIC_KEY"), i = o("FREEMIUS_SECRET_KEY"), a = process.env.NEXT_PUBLIC_SUPABASE_URL || process.env.SUPABASE_URL, d = process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.SUPABASE_SECRET_KEY;
389
- if (!r || !t || !i || !a || !d)
395
+ const r = o("FREEMIUS_DEVELOPER_ID"), t = o("FREEMIUS_PUBLIC_KEY"), s = o("FREEMIUS_SECRET_KEY"), c = process.env.NEXT_PUBLIC_SUPABASE_URL || process.env.SUPABASE_URL, d = process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.SUPABASE_SECRET_KEY;
396
+ if (!r || !t || !s || !c || !d)
390
397
  throw new Error("Missing environment variables for Freemius Sync.");
391
- const f = H(a, d), m = (g) => Z(g, r, t, i), { data: K } = await f.from("languages").select("id").eq("code", "en").single(), E = K?.id;
398
+ const f = H(c, d), m = (g) => Z(g, r, t, s), { data: b } = await f.from("languages").select("id").eq("code", "en").single(), E = b?.id;
392
399
  if (!E)
393
400
  throw new Error("English language not found in database. Cannot sync products.");
394
- const c = await m(`/v1/developers/${r}/plugins/${e}.json`), u = c.plugin ?? c;
401
+ const a = await m(`/v1/developers/${r}/plugins/${e}.json`), l = a.plugin ?? a;
395
402
  return { success: !0, count: await ee(
396
403
  f,
397
404
  r,
398
405
  e,
399
- u.title || u.name || `Freemius Product ${e}`,
406
+ l.title || l.name || `Freemius Product ${e}`,
400
407
  m,
401
408
  E
402
409
  ) };
403
410
  }
404
- async function ee(e, r, t, i, a, d) {
405
- console.log(`[Freemius Sync] Fetching plans for plugin: ${i} (${t})...`);
411
+ async function ee(e, r, t, s, c, d) {
412
+ console.log(`[Freemius Sync] Fetching plans for plugin: ${s} (${t})...`);
406
413
  let f = 0;
407
414
  try {
408
- const m = `/v1/developers/${r}/plugins/${t}/plans.json`, K = await a(m), E = X(K, ["plans", "plan"]);
415
+ const m = `/v1/developers/${r}/plugins/${t}/plans.json`, b = await c(m), E = X(b, ["plans", "plan"]);
409
416
  console.log(`[Freemius Sync] Received ${E.length} plans for plugin ${t}.`);
410
- for (const c of E) {
411
- const u = c.id?.toString();
412
- if (!u) {
413
- console.warn("[Freemius Sync] Skipping plan without an id:", c);
417
+ for (const a of E) {
418
+ const l = a.id?.toString();
419
+ if (!l) {
420
+ console.warn("[Freemius Sync] Skipping plan without an id:", a);
414
421
  continue;
415
422
  }
416
- const p = c.name || c.title || u, g = c.title || p;
417
- console.log(`[Freemius Sync] Processing plan: ${g} (${u})...`);
418
- let U = c;
419
- if (U.trial_period === void 0 || U.is_require_subscription === void 0)
423
+ const p = a.name || a.title || l, g = a.title || p;
424
+ console.log(`[Freemius Sync] Processing plan: ${g} (${l})...`);
425
+ let K = a;
426
+ if (K.trial_period === void 0 || K.is_require_subscription === void 0)
420
427
  try {
421
- const n = `/v1/developers/${r}/plugins/${t}/plans/${u}.json`, _ = await a(n), F = _.plan ?? _;
422
- U = {
423
- ...U,
428
+ const n = `/v1/developers/${r}/plugins/${t}/plans/${l}.json`, _ = await c(n), F = _.plan ?? _;
429
+ K = {
430
+ ...K,
424
431
  ...F
425
432
  };
426
433
  } catch (n) {
427
434
  console.warn(
428
- `[Freemius Sync] Could not fetch trial details for plan ${u}:`,
435
+ `[Freemius Sync] Could not fetch trial details for plan ${l}:`,
429
436
  n instanceof Error ? n.message : n
430
437
  );
431
438
  }
432
- const v = G(U.trial_period), j = v > 0 && pe(U.is_require_subscription);
433
- let b = 0, S = [];
439
+ const v = G(K.trial_period), j = v > 0 && pe(K.is_require_subscription);
440
+ let w = 0, y = [];
434
441
  try {
435
- const n = `/v1/developers/${r}/plugins/${t}/plans/${u}/pricing.json`, _ = await a(n);
436
- if (S = X(_, [
442
+ const n = `/v1/developers/${r}/plugins/${t}/plans/${l}/pricing.json`, _ = await c(n);
443
+ if (y = X(_, [
437
444
  "pricing",
438
445
  "prices",
439
446
  "pricings"
440
- ]), S.length > 0) {
441
- const F = S[0], w = D(F.annual_price) ?? D(F.monthly_price) ?? D(F.lifetime_price);
442
- b = me(w);
447
+ ]), y.length > 0) {
448
+ const F = y[0], U = k(F.annual_price) ?? k(F.monthly_price) ?? k(F.lifetime_price);
449
+ w = me(U);
443
450
  }
444
- console.log(`[Freemius Sync] Plan: ${g} -> Resolved Price (cents): ${b}`);
451
+ console.log(`[Freemius Sync] Plan: ${g} -> Resolved Price (cents): ${w}`);
445
452
  } catch (n) {
446
- console.warn(`[Freemius Sync] Could not fetch pricing for plan ${u}:`, n instanceof Error ? n.message : n);
453
+ console.warn(`[Freemius Sync] Could not fetch pricing for plan ${l}:`, n instanceof Error ? n.message : n);
447
454
  }
448
- const s = `${i}-${g}`.toLowerCase().replace(/[^\w\s-]/g, "").replace(/[\s_]+/g, "-").replace(/^-+|-+$/g, ""), I = {
449
- title: `${i} - ${g}`,
450
- slug: s,
451
- short_description: c.description || "",
452
- price: b,
455
+ const i = `${s}-${g}`.toLowerCase().replace(/[^\w\s-]/g, "").replace(/[\s_]+/g, "-").replace(/^-+|-+$/g, ""), I = {
456
+ title: `${s} - ${g}`,
457
+ slug: i,
458
+ short_description: a.description || "",
459
+ price: w,
453
460
  product_type: "digital",
454
461
  payment_provider: "freemius",
455
- freemius_plan_id: u,
462
+ freemius_plan_id: l,
456
463
  freemius_product_id: t,
457
464
  trial_period_days: v,
458
465
  trial_requires_payment_method: j,
459
466
  status: "active",
460
467
  stock: 999,
461
- sku: `FM-${t}-${u}`,
468
+ sku: `FM-${t}-${l}`,
462
469
  language_id: d
463
470
  }, { data: R, error: P } = await e.from("products").upsert(I, { onConflict: "language_id, sku" }).select();
464
471
  if (P || !R || R.length === 0) {
465
472
  console.error(`[Freemius Sync] Error upserting product ${I.sku}:`, P);
466
473
  continue;
467
474
  }
468
- const k = R[0].id, { data: N, error: x } = await e.from("freemius_plans").select("id").eq("product_id", k).eq("name", p).maybeSingle();
475
+ const D = R[0].id, { data: N, error: x } = await e.from("freemius_plans").select("id").eq("product_id", D).eq("name", p).maybeSingle();
469
476
  x && console.warn(
470
477
  `[Freemius Sync] Could not check existing local plan for ${I.sku}:`,
471
478
  x.message || x
472
479
  );
473
- let y = "";
480
+ let S = "";
474
481
  if (N) {
475
- y = N.id;
476
- const { error: n } = await e.from("freemius_plans").update({ title: g, updated_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("id", y);
482
+ S = N.id;
483
+ const { error: n } = await e.from("freemius_plans").update({ title: g, updated_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("id", S);
477
484
  n && console.warn(
478
- `[Freemius Sync] Could not update local plan ${y}:`,
485
+ `[Freemius Sync] Could not update local plan ${S}:`,
479
486
  n.message || n
480
487
  );
481
488
  } else {
482
489
  const { data: n, error: _ } = await e.from("freemius_plans").insert({
483
- product_id: k,
490
+ product_id: D,
484
491
  name: p,
485
492
  title: g
486
493
  }).select("id").single();
487
494
  _ && console.warn(
488
495
  `[Freemius Sync] Could not insert local plan for ${I.sku}:`,
489
496
  _.message || _
490
- ), n && (y = n.id);
497
+ ), n && (S = n.id);
491
498
  }
492
- if (y && S.length > 0)
493
- for (const n of S) {
499
+ if (S && y.length > 0)
500
+ for (const n of y) {
494
501
  const _ = fe(
495
502
  n.licenses ?? n.license_quota ?? n.quota
496
- ), { data: F, error: w } = await e.from("freemius_pricing").select("id").eq("plan_id", y).eq("license_quota", _).maybeSingle();
497
- w && console.warn(
498
- `[Freemius Sync] Could not check pricing for plan ${y}, quota ${_}:`,
499
- w.message || w
503
+ ), { data: F, error: U } = await e.from("freemius_pricing").select("id").eq("plan_id", S).eq("license_quota", _).maybeSingle();
504
+ U && console.warn(
505
+ `[Freemius Sync] Could not check pricing for plan ${S}, quota ${_}:`,
506
+ U.message || U
500
507
  );
501
508
  const B = {
502
- api_monthly_price: D(n.monthly_price),
503
- api_annual_price: D(n.annual_price),
504
- api_lifetime_price: D(n.lifetime_price),
509
+ api_monthly_price: k(n.monthly_price),
510
+ api_annual_price: k(n.annual_price),
511
+ api_lifetime_price: k(n.lifetime_price),
505
512
  updated_at: (/* @__PURE__ */ new Date()).toISOString()
506
513
  };
507
514
  if (F) {
@@ -512,12 +519,12 @@ async function ee(e, r, t, i, a, d) {
512
519
  );
513
520
  } else {
514
521
  const { error: h } = await e.from("freemius_pricing").insert({
515
- plan_id: y,
522
+ plan_id: S,
516
523
  license_quota: _,
517
524
  ...B
518
525
  });
519
526
  h && console.warn(
520
- `[Freemius Sync] Could not insert pricing for plan ${y}, quota ${_}:`,
527
+ `[Freemius Sync] Could not insert pricing for plan ${S}, quota ${_}:`,
521
528
  h.message || h
522
529
  );
523
530
  }
@@ -530,7 +537,7 @@ async function ee(e, r, t, i, a, d) {
530
537
  return f;
531
538
  }
532
539
  export {
533
- we as FreemiusProvider,
540
+ Ue as FreemiusProvider,
534
541
  Ee as parseFreemiusCheckoutCredentialsMap,
535
542
  o as readFreemiusEnvValue,
536
543
  ge as resolveFreemiusCheckoutCredentials,