@digilogiclabs/platform-core 1.20.1 → 1.21.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.
Files changed (42) hide show
  1. package/dist/{ConsoleEmail-CO0OM4UT.d.ts → ConsoleEmail-BbdpINKx.d.ts} +4 -46
  2. package/dist/{ConsoleEmail-DDB28vyS.d.mts → ConsoleEmail-DpxhsG9C.d.mts} +4 -46
  3. package/dist/{IAI-D8wA_i8N.d.mts → IAI-CWd11dzL.d.mts} +1 -105
  4. package/dist/{IAI-D8wA_i8N.d.ts → IAI-CWd11dzL.d.ts} +1 -105
  5. package/dist/IEmail-CsOcaQcb.d.mts +45 -0
  6. package/dist/IEmail-CsOcaQcb.d.ts +45 -0
  7. package/dist/ILogger-DLDBZaH4.d.mts +105 -0
  8. package/dist/ILogger-DLDBZaH4.d.ts +105 -0
  9. package/dist/{agents-Cc65YUoW.d.ts → agents-C42rGwRl.d.ts} +2 -1
  10. package/dist/{agents-DGciJI27.d.mts → agents-CES-Aq1K.d.mts} +2 -1
  11. package/dist/agents.d.mts +3 -2
  12. package/dist/agents.d.ts +3 -2
  13. package/dist/auth.d.mts +238 -1
  14. package/dist/auth.d.ts +238 -1
  15. package/dist/auth.js +198 -0
  16. package/dist/auth.js.map +1 -1
  17. package/dist/auth.mjs +183 -0
  18. package/dist/auth.mjs.map +1 -1
  19. package/dist/circuit-breaker-CP6kw0P5.d.ts +351 -0
  20. package/dist/circuit-breaker-CsQivd57.d.mts +351 -0
  21. package/dist/email-templates.d.mts +106 -1
  22. package/dist/email-templates.d.ts +106 -1
  23. package/dist/email-templates.js +608 -0
  24. package/dist/email-templates.js.map +1 -1
  25. package/dist/email-templates.mjs +596 -0
  26. package/dist/email-templates.mjs.map +1 -1
  27. package/dist/index.d.mts +12 -355
  28. package/dist/index.d.ts +12 -355
  29. package/dist/index.js +10 -7
  30. package/dist/index.js.map +1 -1
  31. package/dist/index.mjs +10 -7
  32. package/dist/index.mjs.map +1 -1
  33. package/dist/migrate.js +0 -0
  34. package/dist/pdf-exports/index.d.mts +63 -3
  35. package/dist/pdf-exports/index.d.ts +63 -3
  36. package/dist/pdf-exports/index.js +21 -4
  37. package/dist/pdf-exports/index.js.map +1 -1
  38. package/dist/pdf-exports/index.mjs +20 -4
  39. package/dist/pdf-exports/index.mjs.map +1 -1
  40. package/dist/testing.d.mts +5 -3
  41. package/dist/testing.d.ts +5 -3
  42. package/package.json +11 -11
@@ -285,8 +285,604 @@ function securityEmail(branding, data) {
285
285
  cta: data.actionUrl ? { text: data.actionText ?? "Take Action", url: data.actionUrl } : void 0
286
286
  });
287
287
  }
288
+
289
+ // src/auth/tokens.ts
290
+ import crypto2 from "crypto";
291
+ var HMAC_HEX_CHARS = 16;
292
+ function validateSecret(secret) {
293
+ if (typeof secret !== "string" || secret.length < 16) {
294
+ throw new Error(
295
+ "signToken/verifyToken require a secret of at least 16 characters"
296
+ );
297
+ }
298
+ }
299
+ function computeHmac(secret, signedPart) {
300
+ return crypto2.createHmac("sha256", secret).update(signedPart).digest("hex").slice(0, HMAC_HEX_CHARS);
301
+ }
302
+ function signToken(opts) {
303
+ validateSecret(opts.secret);
304
+ if (typeof opts.payload !== "string" || opts.payload.length === 0) {
305
+ throw new Error("signToken requires a non-empty payload string");
306
+ }
307
+ const signedPart = opts.ttlSeconds !== void 0 ? `${opts.payload}.${Math.floor(Date.now() / 1e3)}` : opts.payload;
308
+ const encoded = Buffer.from(signedPart, "utf-8").toString("base64url");
309
+ const hmac = computeHmac(opts.secret, signedPart);
310
+ return `${encoded}.${hmac}`;
311
+ }
312
+ function verifyToken(token, opts) {
313
+ validateSecret(opts.secret);
314
+ if (typeof token !== "string" || token.length === 0) {
315
+ return { valid: false, reason: "malformed" };
316
+ }
317
+ const lastDot = token.lastIndexOf(".");
318
+ if (lastDot <= 0 || lastDot === token.length - 1) {
319
+ return { valid: false, reason: "malformed" };
320
+ }
321
+ const encoded = token.slice(0, lastDot);
322
+ const providedHmac = token.slice(lastDot + 1);
323
+ let signedPart;
324
+ try {
325
+ signedPart = Buffer.from(encoded, "base64url").toString("utf-8");
326
+ } catch {
327
+ return { valid: false, reason: "malformed" };
328
+ }
329
+ if (signedPart.length === 0) {
330
+ return { valid: false, reason: "malformed" };
331
+ }
332
+ const expectedHmac = computeHmac(opts.secret, signedPart);
333
+ if (providedHmac.length !== expectedHmac.length || !crypto2.timingSafeEqual(
334
+ Buffer.from(providedHmac, "utf-8"),
335
+ Buffer.from(expectedHmac, "utf-8")
336
+ )) {
337
+ return { valid: false, reason: "bad_signature" };
338
+ }
339
+ const tsDot = signedPart.lastIndexOf(".");
340
+ let payload = signedPart;
341
+ let issuedAt;
342
+ if (tsDot > 0) {
343
+ const tsCandidate = signedPart.slice(tsDot + 1);
344
+ const tsNum = Number(tsCandidate);
345
+ if (Number.isFinite(tsNum) && /^\d+$/.test(tsCandidate)) {
346
+ payload = signedPart.slice(0, tsDot);
347
+ issuedAt = tsNum;
348
+ }
349
+ }
350
+ if (opts.maxAgeSeconds !== void 0 && issuedAt !== void 0) {
351
+ const ageSeconds = Math.floor(Date.now() / 1e3) - issuedAt;
352
+ if (ageSeconds > opts.maxAgeSeconds) {
353
+ return { valid: false, reason: "expired" };
354
+ }
355
+ }
356
+ return issuedAt !== void 0 ? { valid: true, payload, issuedAt } : { valid: true, payload };
357
+ }
358
+
359
+ // src/email-templates/unsubscribe.ts
360
+ function normalizeEmail(email) {
361
+ return email.toLowerCase().trim();
362
+ }
363
+ function createUnsubscribe(cfg) {
364
+ if (!cfg.secret || cfg.secret.length < 16) {
365
+ throw new Error(
366
+ "createUnsubscribe requires `secret` of at least 16 characters"
367
+ );
368
+ }
369
+ if (!cfg.baseUrl) {
370
+ throw new Error("createUnsubscribe requires `baseUrl`");
371
+ }
372
+ const baseUrl = cfg.baseUrl.replace(/\/+$/, "");
373
+ const path = (cfg.path ?? "/unsubscribe").replace(/^\/?/, "/");
374
+ return {
375
+ generateToken(email) {
376
+ return signToken({ payload: normalizeEmail(email), secret: cfg.secret });
377
+ },
378
+ verifyToken(token) {
379
+ const result = verifyToken(token, { secret: cfg.secret });
380
+ return result.valid ? result.payload : null;
381
+ },
382
+ generateUrl(email) {
383
+ const token = signToken({
384
+ payload: normalizeEmail(email),
385
+ secret: cfg.secret
386
+ });
387
+ return `${baseUrl}${path}?token=${encodeURIComponent(token)}`;
388
+ },
389
+ generateListUnsubscribeHeader(email) {
390
+ const token = signToken({
391
+ payload: normalizeEmail(email),
392
+ secret: cfg.secret
393
+ });
394
+ const url = `${baseUrl}${path}?token=${encodeURIComponent(token)}`;
395
+ if (cfg.mailtoUnsubscribe) {
396
+ return `<${url}>, <mailto:${cfg.mailtoUnsubscribe}?subject=unsubscribe>`;
397
+ }
398
+ return `<${url}>`;
399
+ },
400
+ generateListUnsubscribePostHeader() {
401
+ return "List-Unsubscribe=One-Click";
402
+ }
403
+ };
404
+ }
405
+
406
+ // src/interfaces/ILogger.ts
407
+ var NoopLogger = class {
408
+ debug() {
409
+ }
410
+ info() {
411
+ }
412
+ warn() {
413
+ }
414
+ error() {
415
+ }
416
+ child() {
417
+ return this;
418
+ }
419
+ };
420
+
421
+ // src/resilience/retry.ts
422
+ var DEFAULT_RETRY_OPTIONS = {
423
+ maxAttempts: 3,
424
+ baseDelay: 100,
425
+ maxDelay: 1e4,
426
+ backoffMultiplier: 2,
427
+ jitter: true,
428
+ maxJitter: 100
429
+ };
430
+ function sleep(ms) {
431
+ return new Promise((resolve) => setTimeout(resolve, ms));
432
+ }
433
+ function calculateDelay(attempt, options) {
434
+ let delay = options.baseDelay * Math.pow(options.backoffMultiplier, attempt - 1);
435
+ delay = Math.min(delay, options.maxDelay);
436
+ if (options.jitter) {
437
+ const jitter = Math.random() * options.maxJitter;
438
+ delay += jitter;
439
+ }
440
+ return Math.floor(delay);
441
+ }
442
+ async function withRetry(fn, options = {}) {
443
+ const opts = { ...DEFAULT_RETRY_OPTIONS, ...options };
444
+ const logger = opts.logger ?? new NoopLogger();
445
+ let lastError;
446
+ let delay = opts.baseDelay;
447
+ for (let attempt = 1; attempt <= opts.maxAttempts; attempt++) {
448
+ try {
449
+ return await fn();
450
+ } catch (error) {
451
+ lastError = error instanceof Error ? error : new Error(String(error));
452
+ if (opts.abortIf?.(lastError)) {
453
+ logger.debug("Retry aborted - non-retryable error", {
454
+ attempt,
455
+ error: lastError
456
+ });
457
+ throw lastError;
458
+ }
459
+ if (opts.retryIf && !opts.retryIf(lastError)) {
460
+ logger.debug("Retry aborted - error not retryable", {
461
+ attempt,
462
+ error: lastError
463
+ });
464
+ throw lastError;
465
+ }
466
+ if (attempt >= opts.maxAttempts) {
467
+ logger.warn("All retry attempts exhausted", {
468
+ attempts: attempt,
469
+ error: lastError
470
+ });
471
+ throw lastError;
472
+ }
473
+ delay = calculateDelay(attempt, opts);
474
+ logger.debug("Retrying operation", {
475
+ attempt,
476
+ maxAttempts: opts.maxAttempts,
477
+ delay,
478
+ error: lastError
479
+ });
480
+ opts.onRetry?.(lastError, attempt, delay);
481
+ await sleep(delay);
482
+ }
483
+ }
484
+ throw lastError ?? new Error("Retry failed with no error");
485
+ }
486
+ var RetryPredicates = {
487
+ /**
488
+ * Retry on network errors
489
+ */
490
+ networkErrors: (error) => {
491
+ const networkErrorCodes = [
492
+ "ECONNRESET",
493
+ "ECONNREFUSED",
494
+ "ETIMEDOUT",
495
+ "ENOTFOUND",
496
+ "EAI_AGAIN",
497
+ "EHOSTUNREACH",
498
+ "ENETUNREACH"
499
+ ];
500
+ const errorCode = error.code;
501
+ if (errorCode && networkErrorCodes.includes(errorCode)) {
502
+ return true;
503
+ }
504
+ const message = error.message.toLowerCase();
505
+ return message.includes("network") || message.includes("timeout") || message.includes("connection") || message.includes("socket");
506
+ },
507
+ /**
508
+ * Retry on HTTP 5xx errors
509
+ */
510
+ serverErrors: (error) => {
511
+ const statusCode = error.statusCode;
512
+ return statusCode !== void 0 && statusCode >= 500 && statusCode < 600;
513
+ },
514
+ /**
515
+ * Retry on HTTP 429 (rate limit) errors
516
+ */
517
+ rateLimitErrors: (error) => {
518
+ const statusCode = error.statusCode;
519
+ return statusCode === 429;
520
+ },
521
+ /**
522
+ * Retry on database deadlock errors
523
+ */
524
+ deadlockErrors: (error) => {
525
+ const message = error.message.toLowerCase();
526
+ return message.includes("deadlock") || message.includes("lock wait timeout");
527
+ },
528
+ /**
529
+ * Never retry on authentication errors
530
+ */
531
+ authenticationErrors: (error) => {
532
+ const statusCode = error.statusCode;
533
+ return statusCode === 401 || statusCode === 403;
534
+ },
535
+ /**
536
+ * Never retry on validation errors
537
+ */
538
+ validationErrors: (error) => {
539
+ const statusCode = error.statusCode;
540
+ return statusCode === 400 || statusCode === 422;
541
+ }
542
+ };
543
+ var RetryConfigs = {
544
+ /**
545
+ * Fast retry for quick failures
546
+ */
547
+ fast: {
548
+ maxAttempts: 3,
549
+ baseDelay: 50,
550
+ maxDelay: 500,
551
+ backoffMultiplier: 2
552
+ },
553
+ /**
554
+ * Standard retry configuration
555
+ */
556
+ standard: {
557
+ maxAttempts: 3,
558
+ baseDelay: 100,
559
+ maxDelay: 5e3,
560
+ backoffMultiplier: 2
561
+ },
562
+ /**
563
+ * Aggressive retry for critical operations
564
+ */
565
+ aggressive: {
566
+ maxAttempts: 5,
567
+ baseDelay: 200,
568
+ maxDelay: 3e4,
569
+ backoffMultiplier: 2
570
+ },
571
+ /**
572
+ * Conservative retry for rate-limited APIs
573
+ */
574
+ rateLimited: {
575
+ maxAttempts: 3,
576
+ baseDelay: 1e3,
577
+ maxDelay: 6e4,
578
+ backoffMultiplier: 3,
579
+ jitter: true,
580
+ maxJitter: 500
581
+ },
582
+ /**
583
+ * Database retry configuration
584
+ */
585
+ database: {
586
+ maxAttempts: 3,
587
+ baseDelay: 100,
588
+ maxDelay: 5e3,
589
+ backoffMultiplier: 2,
590
+ retryIf: (error) => RetryPredicates.networkErrors(error) || RetryPredicates.deadlockErrors(error),
591
+ abortIf: RetryPredicates.validationErrors
592
+ }
593
+ };
594
+
595
+ // src/resilience/circuit-breaker.ts
596
+ var DEFAULT_CIRCUIT_BREAKER_OPTIONS = {
597
+ failureThreshold: 5,
598
+ resetTimeout: 3e4,
599
+ successThreshold: 3,
600
+ failureWindow: 6e4
601
+ };
602
+ var CircuitOpenError = class extends Error {
603
+ name = "CircuitOpenError";
604
+ circuitName;
605
+ state;
606
+ nextAttemptAt;
607
+ constructor(circuitName, state, resetTimeout) {
608
+ super(
609
+ `Circuit "${circuitName}" is ${state}. Retry after ${resetTimeout}ms.`
610
+ );
611
+ this.circuitName = circuitName;
612
+ this.state = state;
613
+ this.nextAttemptAt = new Date(Date.now() + resetTimeout);
614
+ }
615
+ };
616
+ var CircuitBreaker = class {
617
+ state = "closed";
618
+ failures = 0;
619
+ successes = 0;
620
+ failureTimestamps = [];
621
+ lastFailure;
622
+ lastSuccess;
623
+ lastStateChange;
624
+ lastOpenedAt;
625
+ totalRequests = 0;
626
+ rejectedRequests = 0;
627
+ lastError;
628
+ options;
629
+ logger;
630
+ constructor(options) {
631
+ this.options = {
632
+ ...DEFAULT_CIRCUIT_BREAKER_OPTIONS,
633
+ ...options
634
+ };
635
+ this.logger = options.logger ?? new NoopLogger();
636
+ }
637
+ /**
638
+ * Execute a function with circuit breaker protection
639
+ */
640
+ async execute(fn) {
641
+ this.totalRequests++;
642
+ if (!this.canExecute()) {
643
+ this.rejectedRequests++;
644
+ this.options.onReject?.(this.state);
645
+ throw new CircuitOpenError(
646
+ this.options.name,
647
+ this.state,
648
+ this.getRemainingTimeout()
649
+ );
650
+ }
651
+ try {
652
+ const result = await fn();
653
+ this.onSuccess();
654
+ return result;
655
+ } catch (error) {
656
+ this.onFailure(error instanceof Error ? error : new Error(String(error)));
657
+ throw error;
658
+ }
659
+ }
660
+ /**
661
+ * Check if circuit allows execution
662
+ */
663
+ canExecute() {
664
+ switch (this.state) {
665
+ case "closed":
666
+ return true;
667
+ case "open":
668
+ if (this.shouldAttemptReset()) {
669
+ this.transitionTo("half-open");
670
+ return true;
671
+ }
672
+ return false;
673
+ case "half-open":
674
+ return true;
675
+ default:
676
+ return false;
677
+ }
678
+ }
679
+ /**
680
+ * Record a successful execution
681
+ */
682
+ onSuccess() {
683
+ this.lastSuccess = /* @__PURE__ */ new Date();
684
+ this.successes++;
685
+ switch (this.state) {
686
+ case "half-open":
687
+ if (this.successes >= this.options.successThreshold) {
688
+ this.transitionTo("closed");
689
+ }
690
+ break;
691
+ case "closed":
692
+ this.failures = 0;
693
+ this.failureTimestamps = [];
694
+ break;
695
+ }
696
+ }
697
+ /**
698
+ * Record a failed execution
699
+ */
700
+ onFailure(error) {
701
+ if (this.options.shouldTrip && !this.options.shouldTrip(error)) {
702
+ return;
703
+ }
704
+ this.lastError = error;
705
+ this.lastFailure = /* @__PURE__ */ new Date();
706
+ this.failures++;
707
+ const now = Date.now();
708
+ this.failureTimestamps.push(now);
709
+ const windowStart = now - this.options.failureWindow;
710
+ this.failureTimestamps = this.failureTimestamps.filter(
711
+ (ts) => ts > windowStart
712
+ );
713
+ switch (this.state) {
714
+ case "closed":
715
+ if (this.failureTimestamps.length >= this.options.failureThreshold) {
716
+ this.transitionTo("open");
717
+ this.options.onOpen?.(this.failures, error);
718
+ }
719
+ break;
720
+ case "half-open":
721
+ this.transitionTo("open");
722
+ this.options.onOpen?.(this.failures, error);
723
+ break;
724
+ }
725
+ }
726
+ /**
727
+ * Transition to a new state
728
+ */
729
+ transitionTo(newState) {
730
+ const oldState = this.state;
731
+ if (oldState === newState) return;
732
+ this.state = newState;
733
+ this.lastStateChange = /* @__PURE__ */ new Date();
734
+ this.logger.info(`Circuit "${this.options.name}" state change`, {
735
+ from: oldState,
736
+ to: newState,
737
+ failures: this.failures,
738
+ successes: this.successes
739
+ });
740
+ this.options.onStateChange?.(oldState, newState);
741
+ switch (newState) {
742
+ case "open":
743
+ this.lastOpenedAt = /* @__PURE__ */ new Date();
744
+ this.successes = 0;
745
+ break;
746
+ case "half-open":
747
+ this.successes = 0;
748
+ break;
749
+ case "closed":
750
+ this.failures = 0;
751
+ this.failureTimestamps = [];
752
+ this.successes = 0;
753
+ this.options.onClose?.();
754
+ break;
755
+ }
756
+ }
757
+ /**
758
+ * Check if reset timeout has passed
759
+ */
760
+ shouldAttemptReset() {
761
+ if (!this.lastOpenedAt) return true;
762
+ const elapsed = Date.now() - this.lastOpenedAt.getTime();
763
+ return elapsed >= this.options.resetTimeout;
764
+ }
765
+ /**
766
+ * Get remaining time until reset attempt
767
+ */
768
+ getRemainingTimeout() {
769
+ if (!this.lastOpenedAt) return 0;
770
+ const elapsed = Date.now() - this.lastOpenedAt.getTime();
771
+ return Math.max(0, this.options.resetTimeout - elapsed);
772
+ }
773
+ /**
774
+ * Get current circuit state
775
+ */
776
+ getState() {
777
+ return this.state;
778
+ }
779
+ /**
780
+ * Get circuit breaker statistics
781
+ */
782
+ getStats() {
783
+ return {
784
+ state: this.state,
785
+ failures: this.failures,
786
+ successes: this.successes,
787
+ lastFailure: this.lastFailure,
788
+ lastSuccess: this.lastSuccess,
789
+ lastStateChange: this.lastStateChange,
790
+ totalRequests: this.totalRequests,
791
+ rejectedRequests: this.rejectedRequests
792
+ };
793
+ }
794
+ /**
795
+ * Manually reset the circuit to closed state
796
+ */
797
+ reset() {
798
+ this.transitionTo("closed");
799
+ }
800
+ /**
801
+ * Manually trip the circuit to open state
802
+ */
803
+ trip() {
804
+ this.transitionTo("open");
805
+ }
806
+ /**
807
+ * Check if circuit is open
808
+ */
809
+ isOpen() {
810
+ return this.state === "open";
811
+ }
812
+ /**
813
+ * Check if circuit is closed
814
+ */
815
+ isClosed() {
816
+ return this.state === "closed";
817
+ }
818
+ /**
819
+ * Check if circuit is half-open
820
+ */
821
+ isHalfOpen() {
822
+ return this.state === "half-open";
823
+ }
824
+ };
825
+
826
+ // src/email-templates/transport.ts
827
+ var DEFAULT_RETRY = {
828
+ maxAttempts: 3
829
+ };
830
+ function withTimeout(promise, ms) {
831
+ return new Promise((resolve, reject) => {
832
+ const timer = setTimeout(
833
+ () => reject(new Error(`email send timed out after ${ms}ms`)),
834
+ ms
835
+ );
836
+ promise.then(
837
+ (v) => {
838
+ clearTimeout(timer);
839
+ resolve(v);
840
+ },
841
+ (e) => {
842
+ clearTimeout(timer);
843
+ reject(e);
844
+ }
845
+ );
846
+ });
847
+ }
848
+ function createResilientEmail(inner, options = {}) {
849
+ const retryOpts = options.retry === false ? null : { ...DEFAULT_RETRY, ...options.retry ?? {} };
850
+ const breaker = options.circuitBreaker ? new CircuitBreaker(options.circuitBreaker) : null;
851
+ const timeoutMs = options.timeoutMs;
852
+ const wrapAttempt = async (fn) => {
853
+ if (timeoutMs !== void 0) {
854
+ return withTimeout(fn(), timeoutMs);
855
+ }
856
+ return fn();
857
+ };
858
+ const withResilience = async (fn) => {
859
+ const exec = async () => {
860
+ if (retryOpts) {
861
+ return withRetry(() => wrapAttempt(fn), retryOpts);
862
+ }
863
+ return wrapAttempt(fn);
864
+ };
865
+ if (breaker) {
866
+ return breaker.execute(exec);
867
+ }
868
+ return exec();
869
+ };
870
+ return {
871
+ async send(message) {
872
+ return withResilience(() => inner.send(message));
873
+ },
874
+ async sendBatch(messages) {
875
+ return withResilience(() => inner.sendBatch(messages));
876
+ },
877
+ async healthCheck() {
878
+ return inner.healthCheck();
879
+ }
880
+ };
881
+ }
288
882
  export {
289
883
  calloutBlock,
884
+ createResilientEmail,
885
+ createUnsubscribe,
290
886
  dataTable,
291
887
  digestEmail,
292
888
  divider,