@marvalt/digivalt-core 0.2.21 → 0.2.24

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.
@@ -2430,8 +2430,335 @@ async function generateMauticData(options) {
2430
2430
  return true;
2431
2431
  }
2432
2432
  catch (e) {
2433
- console.error('❌ Mautic generation failed:', e.message);
2434
- return false;
2433
+ console.warn(`⚠️ Mautic generation failed (build continues): ${e.message}`);
2434
+ return true;
2435
+ }
2436
+ }
2437
+
2438
+ /** Normalize PHPList base URL to REST API v2 root. */
2439
+ function getApiBaseUrl(phplistUrl) {
2440
+ const trimmed = phplistUrl.replace(/\/$/, '');
2441
+ if (trimmed.endsWith('/api/v2'))
2442
+ return trimmed;
2443
+ if (trimmed.endsWith('/lists'))
2444
+ return `${trimmed}/api/v2`;
2445
+ return `${trimmed}/lists/api/v2`;
2446
+ }
2447
+ function buildViewProxyPath(messageId, uid) {
2448
+ const params = new URLSearchParams({ endpoint: 'view', mid: String(messageId) });
2449
+ return `/api/phplist-proxy?${params.toString()}`;
2450
+ }
2451
+
2452
+ let cachedSession = null;
2453
+ function buildAccessHeaders(options) {
2454
+ const headers = {};
2455
+ if (options.cfAccessClientId && options.cfAccessClientSecret) {
2456
+ headers['CF-Access-Client-Id'] = options.cfAccessClientId;
2457
+ headers['CF-Access-Client-Secret'] = options.cfAccessClientSecret;
2458
+ }
2459
+ return headers;
2460
+ }
2461
+ async function createPhplistSession(options) {
2462
+ if (cachedSession && cachedSession.expiresAt > Date.now() + 300000) {
2463
+ return cachedSession.key;
2464
+ }
2465
+ const apiBase = getApiBaseUrl(options.apiUrl);
2466
+ const headers = {
2467
+ 'Content-Type': 'application/json',
2468
+ ...buildAccessHeaders(options),
2469
+ };
2470
+ const response = await fetch(`${apiBase}/sessions`, {
2471
+ method: 'POST',
2472
+ headers,
2473
+ body: JSON.stringify({
2474
+ login_name: options.apiUser,
2475
+ password: options.apiPassword,
2476
+ }),
2477
+ });
2478
+ if (!response.ok) {
2479
+ const errText = await response.text();
2480
+ throw new Error(`PHPList session failed: ${response.status} ${errText}`);
2481
+ }
2482
+ const data = (await response.json());
2483
+ const expiryMs = data.expiry ? Date.parse(data.expiry) : Date.now() + 3600000;
2484
+ cachedSession = { key: data.key, expiresAt: expiryMs };
2485
+ return data.key;
2486
+ }
2487
+ async function phplistApiFetch(options, path, init = {}) {
2488
+ const sessionKey = await createPhplistSession(options);
2489
+ const apiBase = getApiBaseUrl(options.apiUrl);
2490
+ const url = path.startsWith('http') ? path : `${apiBase}${path.startsWith('/') ? path : `/${path}`}`;
2491
+ const headers = {
2492
+ 'Content-Type': 'application/json',
2493
+ 'php-auth-pw': sessionKey,
2494
+ ...init.headers,
2495
+ ...buildAccessHeaders(options),
2496
+ };
2497
+ const response = await fetch(url, { ...init, headers });
2498
+ if (!response.ok) {
2499
+ const errText = await response.text();
2500
+ throw new Error(`PHPList API ${path} failed: ${response.status} ${errText}`);
2501
+ }
2502
+ if (response.status === 204) {
2503
+ return undefined;
2504
+ }
2505
+ const text = await response.text();
2506
+ if (!text)
2507
+ return undefined;
2508
+ return JSON.parse(text);
2509
+ }
2510
+
2511
+ /** URL-safe slug from subject line. */
2512
+ function slugifySubject(subject) {
2513
+ return subject
2514
+ .toLowerCase()
2515
+ .normalize('NFKD')
2516
+ .replace(/[\u0300-\u036f]/g, '')
2517
+ .replace(/[^a-z0-9]+/g, '-')
2518
+ .replace(/^-+|-+$/g, '')
2519
+ .slice(0, 80) || 'newsletter';
2520
+ }
2521
+ function slugifyListName(name) {
2522
+ return slugifySubject(name);
2523
+ }
2524
+ function buildNewsletterSlug(listSlug, messageId, subject) {
2525
+ return `${listSlug}/${messageId}-${slugifySubject(subject)}`;
2526
+ }
2527
+ function stripHtmlExcerpt(html, maxLength = 200) {
2528
+ const text = html
2529
+ .replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '')
2530
+ .replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '')
2531
+ .replace(/<[^>]+>/g, ' ')
2532
+ .replace(/\s+/g, ' ')
2533
+ .trim();
2534
+ if (text.length <= maxLength)
2535
+ return text;
2536
+ return `${text.slice(0, maxLength).trim()}…`;
2537
+ }
2538
+
2539
+ async function generatePhplistData$1(config) {
2540
+ console.log('🔄 Generating PHPList newsletter JSON data...');
2541
+ try {
2542
+ const authOptions = {
2543
+ apiUrl: config.apiUrl,
2544
+ apiUser: config.apiUser,
2545
+ apiPassword: config.apiPassword,
2546
+ cfAccessClientId: config.cfAccessClientId,
2547
+ cfAccessClientSecret: config.cfAccessClientSecret,
2548
+ };
2549
+ const list = await phplistApiFetch(authOptions, `/lists/${config.listId}`);
2550
+ const listSlug = slugifyListName(list.name);
2551
+ const existing = readExistingData(config.outputPath);
2552
+ const knownIds = new Set(existing?.newsletters.map((n) => n.id) ?? []);
2553
+ const lastSentAt = existing?.newsletters.reduce((max, n) => {
2554
+ const t = Date.parse(n.sent_at);
2555
+ return Number.isNaN(t) ? max : Math.max(max, t);
2556
+ }, 0) ?? 0;
2557
+ const listMessageIds = await fetchListMessageIds(authOptions, config.listId);
2558
+ const listMessageIdSet = new Set(listMessageIds);
2559
+ const newItems = [];
2560
+ let afterId = 0;
2561
+ let hasMore = true;
2562
+ while (hasMore) {
2563
+ const page = await phplistApiFetch(authOptions, `/campaigns?limit=100&after_id=${afterId || 1}`);
2564
+ const items = page.items ?? [];
2565
+ if (items.length === 0)
2566
+ break;
2567
+ for (const summary of items) {
2568
+ const id = summary.id;
2569
+ if (!id || !listMessageIdSet.has(id) || knownIds.has(id))
2570
+ continue;
2571
+ if (summary.message_metadata?.status !== 'sent')
2572
+ continue;
2573
+ const sentAt = summary.message_metadata?.sent;
2574
+ if (sentAt && lastSentAt > 0 && Date.parse(sentAt) <= lastSentAt) {
2575
+ continue;
2576
+ }
2577
+ const detail = await phplistApiFetch(authOptions, `/campaigns/${id}`);
2578
+ const item = messageToNewsletter(detail, listSlug, config.newsletterRouteBase);
2579
+ if (item) {
2580
+ newItems.push(item);
2581
+ knownIds.add(id);
2582
+ }
2583
+ }
2584
+ const lastId = items[items.length - 1]?.id;
2585
+ if (!lastId || items.length < 100) {
2586
+ hasMore = false;
2587
+ }
2588
+ else {
2589
+ afterId = lastId;
2590
+ const oldestSent = items
2591
+ .map((m) => m.message_metadata?.sent)
2592
+ .filter(Boolean)
2593
+ .map((s) => Date.parse(s))
2594
+ .filter((t) => !Number.isNaN(t));
2595
+ if (lastSentAt > 0 && oldestSent.length && Math.min(...oldestSent) <= lastSentAt) {
2596
+ hasMore = false;
2597
+ }
2598
+ }
2599
+ }
2600
+ const mergedNewsletters = [
2601
+ ...(existing?.newsletters ?? []),
2602
+ ...newItems,
2603
+ ].sort((a, b) => Date.parse(b.sent_at) - Date.parse(a.sent_at));
2604
+ const subscribePages = await fetchSubscribePages(authOptions, config.subscribePageIds);
2605
+ const data = {
2606
+ generated_at: new Date().toISOString(),
2607
+ list: {
2608
+ id: list.id,
2609
+ name: list.name,
2610
+ slug: listSlug,
2611
+ description: list.description,
2612
+ },
2613
+ subscribe_pages: subscribePages,
2614
+ newsletters: mergedNewsletters,
2615
+ };
2616
+ writeStaticData(config.outputPath, data);
2617
+ console.log(`✅ PHPList: ${mergedNewsletters.length} newsletters (${newItems.length} new)`);
2618
+ return { success: true, data };
2619
+ }
2620
+ catch (error) {
2621
+ const message = error instanceof Error ? error.message : String(error);
2622
+ console.warn(`⚠️ PHPList generation failed: ${message}`);
2623
+ return { success: false, error: message };
2624
+ }
2625
+ }
2626
+ async function fetchListMessageIds(authOptions, listId) {
2627
+ const response = await phplistApiFetch(authOptions, `/list-messages/list/${listId}/messages`);
2628
+ return (response.items ?? []).map((row) => row.message_id).filter(Boolean);
2629
+ }
2630
+ async function fetchSubscribePages(authOptions, pageIds) {
2631
+ const pages = [];
2632
+ for (const pageId of pageIds) {
2633
+ try {
2634
+ const publicPage = await phplistApiFetch(authOptions, `/public/subscribe-pages/${pageId}`);
2635
+ pages.push({
2636
+ id: pageId,
2637
+ title: publicPage.title,
2638
+ intro: publicPage.intro,
2639
+ attributes: publicPage.attributes ?? [],
2640
+ list_ids: publicPage.list_ids,
2641
+ });
2642
+ }
2643
+ catch (e) {
2644
+ console.warn(`⚠️ Could not load subscribe page ${pageId}:`, e.message);
2645
+ }
2646
+ }
2647
+ return pages;
2648
+ }
2649
+ function messageToNewsletter(message, listSlug, _routeBase) {
2650
+ const subject = message.message_content?.subject?.trim();
2651
+ const html = message.message_content?.text ?? '';
2652
+ const sentAt = message.message_metadata?.sent;
2653
+ if (!subject || !sentAt || message.message_metadata?.status !== 'sent') {
2654
+ return null;
2655
+ }
2656
+ const slug = buildNewsletterSlug(listSlug, message.id, subject);
2657
+ return {
2658
+ id: message.id,
2659
+ unique_id: message.unique_id,
2660
+ slug,
2661
+ subject,
2662
+ sent_at: sentAt,
2663
+ excerpt: stripHtmlExcerpt(html),
2664
+ html,
2665
+ plain_text: message.message_content?.text_message,
2666
+ view_url: buildViewProxyPath(message.id),
2667
+ };
2668
+ }
2669
+ function readExistingData(outputPath) {
2670
+ try {
2671
+ if (!fs.existsSync(outputPath))
2672
+ return null;
2673
+ return JSON.parse(fs.readFileSync(outputPath, 'utf8'));
2674
+ }
2675
+ catch {
2676
+ return null;
2677
+ }
2678
+ }
2679
+ function writeStaticData(outputPath, data) {
2680
+ const dir = path.dirname(outputPath);
2681
+ if (!fs.existsSync(dir)) {
2682
+ fs.mkdirSync(dir, { recursive: true });
2683
+ }
2684
+ fs.writeFileSync(outputPath, JSON.stringify(data, null, 2), 'utf8');
2685
+ }
2686
+
2687
+ function parseSubscribePageIds(raw) {
2688
+ if (!raw?.trim())
2689
+ return [];
2690
+ return raw
2691
+ .split(',')
2692
+ .map((s) => parseInt(s.trim(), 10))
2693
+ .filter((n) => !Number.isNaN(n));
2694
+ }
2695
+ async function generatePhplistData(options) {
2696
+ const outputPath = options?.outputPath || './public/phplist-data.json';
2697
+ const phplistUrl = process.env.PHPLIST_URL || process.env.VITE_PHPLIST_URL;
2698
+ const listIdRaw = process.env.PHPLIST_LIST_ID || process.env.VITE_PHPLIST_LIST_ID;
2699
+ const apiUser = process.env.PHPLIST_API_USER || process.env.VITE_PHPLIST_API_USER;
2700
+ const apiPassword = process.env.PHPLIST_API_PASSWORD || process.env.VITE_PHPLIST_API_PASSWORD;
2701
+ const proxyUrl = process.env.PHPLIST_PROXY_URL || process.env.VITE_PHPLIST_PROXY_URL;
2702
+ const subscribePageIds = parseSubscribePageIds(process.env.PHPLIST_SUBSCRIBE_PAGE_IDS || process.env.VITE_PHPLIST_SUBSCRIBE_PAGE_IDS);
2703
+ const newsletterRouteBase = process.env.VITE_PHPLIST_NEWSLETTER_ROUTE_BASE || '/newsletters';
2704
+ const cfAccessClientId = process.env.CF_ACCESS_CLIENT_ID || process.env.VITE_CF_ACCESS_CLIENT_ID;
2705
+ const cfAccessClientSecret = process.env.CF_ACCESS_CLIENT_SECRET || process.env.VITE_CF_ACCESS_CLIENT_SECRET;
2706
+ const restApiEndpoint = process.env.PHPLIST_API_ENDPOINT || process.env.VITE_PHPLIST_API_ENDPOINT;
2707
+ const publicBaseUrl = process.env.PHPLIST_PUBLIC_BASE_URL || process.env.VITE_PHPLIST_PUBLIC_BASE_URL;
2708
+ const apiSecret = process.env.PHPLIST_API_SECRET || process.env.VITE_PHPLIST_API_SECRET;
2709
+ const subscribeStrategy = process.env.PHPLIST_SUBSCRIBE_STRATEGY || process.env.VITE_PHPLIST_SUBSCRIBE_STRATEGY;
2710
+ const subscribePageId = process.env.PHPLIST_SUBSCRIBE_PAGE_ID || process.env.VITE_PHPLIST_SUBSCRIBE_PAGE_ID;
2711
+ const apiModeRaw = process.env.PHPLIST_API_MODE || process.env.VITE_PHPLIST_API_MODE;
2712
+ const apiMode = apiModeRaw === 'rest_v2' || apiModeRaw === 'v2'
2713
+ ? 'rest_v2'
2714
+ : apiModeRaw === 'restapi' || apiModeRaw === 'plugin' || restApiEndpoint
2715
+ ? 'restapi'
2716
+ : undefined;
2717
+ if (!phplistUrl) {
2718
+ console.log('⚠️ PHPList URL not configured. Skipping PHPList data generation.');
2719
+ return true;
2720
+ }
2721
+ const listId = parseInt(listIdRaw || '0', 10);
2722
+ if (!listId || Number.isNaN(listId)) {
2723
+ console.warn('⚠️ PHPList list ID not configured. Skipping PHPList data generation.');
2724
+ return true;
2725
+ }
2726
+ if (!apiUser || !apiPassword) {
2727
+ console.warn('⚠️ PHPList API credentials missing. Skipping PHPList data generation.');
2728
+ return true;
2729
+ }
2730
+ try {
2731
+ const authMode = proxyUrl ? 'cloudflare_proxy' : 'direct';
2732
+ const result = await generatePhplistData$1({
2733
+ authMode,
2734
+ apiUrl: phplistUrl,
2735
+ cloudflareWorkerUrl: authMode === 'cloudflare_proxy' ? proxyUrl : undefined,
2736
+ apiUser,
2737
+ apiPassword,
2738
+ listId,
2739
+ subscribePageIds,
2740
+ outputPath,
2741
+ newsletterRouteBase,
2742
+ cfAccessClientId,
2743
+ cfAccessClientSecret,
2744
+ apiMode,
2745
+ restApiEndpoint,
2746
+ publicBaseUrl,
2747
+ apiSecret,
2748
+ subscribeStrategy: subscribeStrategy === 'direct' ? 'direct' : subscribeStrategy === 'confirm-email' ? 'confirm-email' : undefined,
2749
+ subscribePageId,
2750
+ });
2751
+ if (result.success) {
2752
+ console.log(`📁 PHPList data written to: ${path.join(process.cwd(), outputPath)}`);
2753
+ }
2754
+ else {
2755
+ console.warn(`⚠️ PHPList generation completed with warnings: ${result.error ?? 'unknown'}`);
2756
+ }
2757
+ return true;
2758
+ }
2759
+ catch (e) {
2760
+ console.warn(`⚠️ PHPList generation failed: ${e.message}`);
2761
+ return true;
2435
2762
  }
2436
2763
  }
2437
2764
 
@@ -2465,8 +2792,8 @@ async function generateSuiteCRMData(options) {
2465
2792
  return true;
2466
2793
  }
2467
2794
  catch (e) {
2468
- console.error('❌ SuiteCRM generation failed:', e.message);
2469
- return false;
2795
+ console.warn(`⚠️ SuiteCRM generation failed (build continues): ${e.message}`);
2796
+ return true;
2470
2797
  }
2471
2798
  }
2472
2799
 
@@ -2781,11 +3108,13 @@ async function generateAllData() {
2781
3108
  }
2782
3109
  const wpSuccess = await generateWordPressData();
2783
3110
  const gfSuccess = await generateGravityFormsData();
2784
- const mauticSuccess = await generateMauticData();
2785
- const suitecrmSuccess = await generateSuiteCRMData();
2786
- const googleReviewsSuccess = await generateGoogleReviewsData();
2787
- if (!wpSuccess || !gfSuccess || !mauticSuccess || !suitecrmSuccess || !googleReviewsSuccess) {
2788
- console.error('❌ Some generation tasks failed. See above for details.');
3111
+ // Optional integrations — warn-only (same as PHPList); do not block deploy
3112
+ await generateMauticData();
3113
+ await generatePhplistData();
3114
+ await generateSuiteCRMData();
3115
+ await generateGoogleReviewsData();
3116
+ if (!wpSuccess || !gfSuccess) {
3117
+ console.error('❌ Required generation failed (WordPress or Gravity Forms). See above for details.');
2789
3118
  process.exit(1);
2790
3119
  }
2791
3120
  await generateSitemapPathsSafe();
@@ -2797,6 +3126,7 @@ exports.generateAllData = generateAllData;
2797
3126
  exports.generateGoogleReviewsData = generateGoogleReviewsData;
2798
3127
  exports.generateGravityFormsData = generateGravityFormsData;
2799
3128
  exports.generateMauticData = generateMauticData;
3129
+ exports.generatePhplistData = generatePhplistData;
2800
3130
  exports.generateSitemapPaths = generateSitemapPaths;
2801
3131
  exports.generateSitemapPathsSafe = generateSitemapPathsSafe;
2802
3132
  exports.generateSuiteCRMData = generateSuiteCRMData;