@infuro/cms-core 1.0.34 → 1.0.36

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 (152) hide show
  1. package/README.md +13 -0
  2. package/dist/OrderTrackPage-W3J6WIG2.js +426 -0
  3. package/dist/OrderTrackPage-Z6FCJQYY.cjs +428 -0
  4. package/dist/admin.cjs +35254 -21613
  5. package/dist/admin.d.cts +192 -9
  6. package/dist/admin.d.ts +192 -9
  7. package/dist/admin.js +34301 -20755
  8. package/dist/api.cjs +137 -17531
  9. package/dist/api.d.cts +633 -3
  10. package/dist/api.d.ts +633 -3
  11. package/dist/api.js +15 -17528
  12. package/dist/auth.cjs +192 -1034
  13. package/dist/auth.d.cts +197 -54
  14. package/dist/auth.d.ts +197 -54
  15. package/dist/auth.js +4 -966
  16. package/dist/chunk-2AEVFOQP.cjs +30436 -0
  17. package/dist/chunk-3DZRIZOD.cjs +52 -0
  18. package/dist/chunk-5ELSW2UP.js +150 -0
  19. package/dist/chunk-7NMT3GBR.cjs +29 -0
  20. package/dist/chunk-COBORIJH.cjs +2373 -0
  21. package/dist/chunk-CRFV5WJK.js +16 -0
  22. package/dist/chunk-D5FBNKQM.cjs +104 -0
  23. package/dist/chunk-FG6I64HP.js +604 -0
  24. package/dist/chunk-GO7PPYNU.js +76 -0
  25. package/dist/chunk-HCIRL37O.js +21 -0
  26. package/dist/chunk-HF3L2GIT.cjs +194 -0
  27. package/dist/chunk-HT5DI3XW.cjs +82 -0
  28. package/dist/chunk-JC6DLWTE.js +21 -0
  29. package/dist/chunk-JS2W7XZ4.js +30312 -0
  30. package/dist/chunk-JXF23MPG.js +25 -0
  31. package/dist/chunk-KFFB6EMZ.js +123 -0
  32. package/dist/chunk-KPKFNLQQ.cjs +648 -0
  33. package/dist/chunk-LI2IXVAY.js +171 -0
  34. package/dist/chunk-MQBT33IV.js +48 -0
  35. package/dist/chunk-OOTLNH63.cjs +18 -0
  36. package/dist/chunk-PNOKNSG2.cjs +222 -0
  37. package/dist/chunk-SHUYVCID.js +4 -0
  38. package/dist/chunk-SPQFNIYJ.cjs +132 -0
  39. package/dist/chunk-SYBOCAWB.js +97 -0
  40. package/dist/chunk-TDV6EJHV.js +192 -0
  41. package/dist/chunk-UCKN4BBY.cjs +24 -0
  42. package/dist/chunk-UF3BYUXY.js +616 -0
  43. package/dist/chunk-UPLVMVRX.cjs +23 -0
  44. package/dist/chunk-USNT2KNT.cjs +6 -0
  45. package/dist/chunk-VMY2S32H.js +2342 -0
  46. package/dist/chunk-WEMDMVHQ.js +216 -0
  47. package/dist/chunk-WO2DW4AU.cjs +182 -0
  48. package/dist/chunk-X47PBV4I.js +79 -0
  49. package/dist/chunk-X6H5VBQ2.cjs +620 -0
  50. package/dist/chunk-XQ3QUHWR.cjs +83 -0
  51. package/dist/chunk-XW5ATPRW.cjs +155 -0
  52. package/dist/cli.cjs +107 -86
  53. package/dist/cli.js +66 -29
  54. package/dist/email-queue-CGZBVVAS.js +2 -0
  55. package/dist/email-queue-TPZWLTIV.cjs +23 -0
  56. package/dist/emit-order-notification-trigger-D2N3KFHL.cjs +16 -0
  57. package/dist/emit-order-notification-trigger-IVLWKKJL.js +3 -0
  58. package/dist/erp-config-enabled-CUMQ6N2V.cjs +11 -0
  59. package/dist/erp-config-enabled-T37X7T34.js +2 -0
  60. package/dist/erp-order-invoice-3YISSOWW.js +3 -0
  61. package/dist/erp-order-invoice-ZR5F2KTA.cjs +12 -0
  62. package/dist/event-order-defaults-EMWBIGL3.cjs +39 -0
  63. package/dist/event-order-defaults-SDRNAZHC.js +2 -0
  64. package/dist/hooks.cjs +259 -132
  65. package/dist/hooks.d.cts +42 -1
  66. package/dist/hooks.d.ts +42 -1
  67. package/dist/hooks.js +234 -91
  68. package/dist/index.cjs +3679 -22356
  69. package/dist/index.d.cts +2173 -643
  70. package/dist/index.d.ts +2173 -643
  71. package/dist/index.js +2587 -22119
  72. package/dist/interpolate-WAKPN56R.cjs +11 -0
  73. package/dist/interpolate-WDUWDF3I.js +2 -0
  74. package/dist/migrations/1779400000000-ConvertStatusToEnum.ts +142 -0
  75. package/dist/migrations/1779400000000-SeedDefaultCurrencies.ts +33 -0
  76. package/dist/migrations/1779500000000-VendorRolesAndPermissions.ts +102 -0
  77. package/dist/migrations/1779600000000-VendorRegistrationProfile.ts +52 -0
  78. package/dist/migrations/1779700000000-CollectionIsCatalog.ts +22 -0
  79. package/dist/migrations/1779710000000-CollectionPlatformCatalog.ts +60 -0
  80. package/dist/migrations/1779720000000-ProductCategoryPlatformCatalog.ts +157 -0
  81. package/dist/migrations/1779800000000-EventsAndEventProducts.ts +173 -0
  82. package/dist/migrations/1779810000000-BackfillVendorRoleEventsPermissions.ts +38 -0
  83. package/dist/migrations/1779820000000-FixProductsCategoryForeignKey.ts +70 -0
  84. package/dist/migrations/1779830000000-ProductTitleColumn.ts +32 -0
  85. package/dist/migrations/1779840000000-EventAboutAndVisibilityFields.ts +34 -0
  86. package/dist/migrations/1779850000000-EventCityCountrySplit.ts +43 -0
  87. package/dist/migrations/1779860000000-CreateCombos.ts +140 -0
  88. package/dist/migrations/1780100000000-OrderAttendeesEventId.ts +55 -0
  89. package/dist/migrations/1780110000000-EventContactFormId.ts +49 -0
  90. package/dist/migrations/1780130000000-ProductVariants.ts +54 -0
  91. package/dist/migrations/1780140000000-EventManagementEnhancements.ts +44 -0
  92. package/dist/migrations/1780160000000-EventRegistrationGstProductContactForm.ts +79 -0
  93. package/dist/migrations/1780170000000-ComboCurrencyPrices.ts +20 -0
  94. package/dist/migrations/1781110000000-VendorOwnerCombosPermission.ts +38 -0
  95. package/dist/migrations/1781120000000-RefundPoliciesAndRequests.ts +225 -0
  96. package/dist/migrations/1781130000000-CreateAttendees.ts +44 -0
  97. package/dist/migrations/1781140000000-EventOrderNotifications.ts +29 -0
  98. package/dist/migrations/1781150000000-EventNamedLists.ts +28 -0
  99. package/dist/migrations/1781160000000-RefundPolicyEventTiers.ts +27 -0
  100. package/dist/migrations/1781170000000-EventRefundPolicy.ts +42 -0
  101. package/dist/migrations/1781180000000-RemoveCartItemsUniqueConstraint.ts +15 -0
  102. package/dist/migrations/1781190000000-RenameProductTaxesToProductConfig.ts +84 -0
  103. package/dist/migrations/1781200000000-VendorOwnerProductConfigPermissions.ts +51 -0
  104. package/dist/migrations/1781210000000-VendorRoleProductConfigPermissions.ts +46 -0
  105. package/dist/migrations/1781220000000-AddWhatsappTriggerBindings.ts +23 -0
  106. package/dist/migrations/1781230000000-AddOrderNotificationTriggers.ts +46 -0
  107. package/dist/migrations/1781240000000-DropEventOrderNotificationColumns.ts +29 -0
  108. package/dist/migrations/1781250000000-RemoveOrderRefundedTrigger.ts +36 -0
  109. package/dist/migrations/helpers/vendor-role-seed.ts +243 -0
  110. package/dist/paid-order-erp-3USEG6WL.js +3 -0
  111. package/dist/paid-order-erp-FSQ3GSXE.cjs +12 -0
  112. package/dist/pg-boss-service-4XF2TQ2E.js +2 -0
  113. package/dist/pg-boss-service-L6MTF4EQ.cjs +15 -0
  114. package/dist/razorpay-KLO2KNCB.js +49 -0
  115. package/dist/razorpay-U23LGY72.cjs +56 -0
  116. package/dist/rbac-debug-db-HWP65A4O.cjs +35 -0
  117. package/dist/rbac-debug-db-QJH3AD34.js +33 -0
  118. package/dist/sms-defaults-2NL24H57.js +2 -0
  119. package/dist/sms-defaults-KCOPKQBA.cjs +19 -0
  120. package/dist/stripe-4FD27QVJ.js +51 -0
  121. package/dist/stripe-VU6OEG2D.cjs +57 -0
  122. package/dist/theme.cjs +31 -59
  123. package/dist/theme.d.cts +78 -3
  124. package/dist/theme.d.ts +78 -3
  125. package/dist/theme.js +23 -20
  126. package/dist/vendor-invite-status-77O7ZQ3U.cjs +19 -0
  127. package/dist/vendor-invite-status-PWJ3DE76.js +2 -0
  128. package/dist/whatsapp-trigger-dispatcher-ONHXI7UY.cjs +19 -0
  129. package/dist/whatsapp-trigger-dispatcher-PWFI4FKP.js +6 -0
  130. package/package.json +147 -142
  131. package/dist/admin.cjs.map +0 -1
  132. package/dist/admin.js.map +0 -1
  133. package/dist/api.cjs.map +0 -1
  134. package/dist/api.js.map +0 -1
  135. package/dist/auth.cjs.map +0 -1
  136. package/dist/auth.js.map +0 -1
  137. package/dist/cli.cjs.map +0 -1
  138. package/dist/cli.js.map +0 -1
  139. package/dist/config-DJ5CmQvS.d.cts +0 -8
  140. package/dist/config-DJ5CmQvS.d.ts +0 -8
  141. package/dist/hooks.cjs.map +0 -1
  142. package/dist/hooks.js.map +0 -1
  143. package/dist/index-Bf5GO8fu.d.cts +0 -583
  144. package/dist/index-DOiJuMQA.d.ts +0 -583
  145. package/dist/index.cjs.map +0 -1
  146. package/dist/index.js.map +0 -1
  147. package/dist/theme.cjs.map +0 -1
  148. package/dist/theme.js.map +0 -1
  149. package/dist/types-DCVaXlPV.d.cts +0 -78
  150. package/dist/types-DCVaXlPV.d.ts +0 -78
  151. package/dist/vendor-scope-DTYhJk_I.d.cts +0 -129
  152. package/dist/vendor-scope-DTYhJk_I.d.ts +0 -129
package/dist/index.d.ts CHANGED
@@ -1,18 +1,11 @@
1
- import { e as CompanyDetails, T as TemplateContext, h as EmailTemplateResult, g as EmailTemplateName, O as OrderPlacedLineItem, o as StorageService, i as EntityMap$2 } from './index-DOiJuMQA.js';
2
- export { A as AnalyticsHandlerConfig, a as AuthHandlersConfig, B as BlogBySlugConfig, C as ChangePasswordConfig, b as ChatPublicConfig, c as CmsApiHandlerConfig, d as CmsGetter, f as CrudHandlerOptions, D as DashboardStatsConfig, E as EcommerceAnalyticsConfig, F as ForgotPasswordConfig, j as FormBySlugConfig, G as GetPublicSettingsGroupConfig, k as GetPublicSettingsGroupDataSource, I as InviteAcceptConfig, J as JobScheduleApiConfig, L as LlmAgentKnowledgeApiConfig, l as LlmAgentValidationRulesJson, P as ParsedLlmAgentValidation, S as SetPasswordConfig, m as SettingsApiConfig, n as SocialLinkItem, p as StorefrontApiConfig, q as StorefrontOtpFlags, U as UploadHandlerConfig, r as UserAuthApiConfig, s as UserAvatarConfig, t as UserProfileConfig, u as UsersApiConfig, V as VendorOnboardHandlersConfig, v as VendorOwnerActivation, w as createAnalyticsHandlers, x as createBlogBySlugHandler, y as createChangePasswordHandler, z as createCmsApiHandler, H as createCrudByIdHandler, K as createCrudHandler, M as createDashboardStatsHandler, N as createEcommerceAnalyticsHandler, Q as createForgotPasswordHandler, R as createFormBySlugHandler, W as createInviteAcceptHandler, X as createJobScheduleHandlers, Y as createLlmAgentKnowledgeHandlers, Z as createMediaZipExtractHandler, _ as createSetPasswordHandler, $ as createSettingsApiHandlers, a0 as createStorefrontApiHandler, a1 as createUploadHandler, a2 as createUserAuthApiRouter, a3 as createUserAvatarHandler, a4 as createUserProfileHandler, a5 as createUsersApiHandlers, a6 as createVendorOnboardHandlers, a7 as getCompanyDetailsFromSettings, a8 as getPublicSettingsGroup, a9 as mergeEmailLayoutCompanyDetails, aa as mergeGuardrailsIntoSystemPrompt, ab as parseLlmAgentValidationRules, ac as simpleDecrypt, ad as simpleEncrypt, ae as validateUserMessageAgainstAgentRules, af as validateUserMessageAgainstStructuredRules } from './index-DOiJuMQA.js';
3
1
  import PgBoss from 'pg-boss';
4
2
  import * as typeorm from 'typeorm';
5
- import { DataSource, EntityTarget, ObjectLiteral, SelectQueryBuilder } from 'typeorm';
3
+ import { DataSource, EntityTarget, ObjectLiteral, EntityManager, SelectQueryBuilder } from 'typeorm';
6
4
  import { ClassValue } from 'clsx';
7
5
  import { Metadata } from 'next';
8
- import { NextAuthUser } from './auth.js';
9
- export { AuthorizeOtpInput, CmsMiddlewareConfig, CmsMiddlewareRequest, NextAuthOptionsConfig, SUPER_ADMIN_GROUP_ID, VENDOR_ADMIN_GROUP_ID, createCmsMiddleware, defaultPublicApiMethods, explainSessionEntityAccess, getNextAuthOptions, getStorefrontNextAuthOptions, isAuthDebugClientEnabled, isAuthDebugEnabled, isRbacDebugEnabled, isSuperAdmin, isVendorAdmin, logAuth, logAuthClient, logEntityAccessDecision, logRbac, nextAuthCookieDebugInfo, seedAdministratorPermissions, summarizeEntityPerms, summarizeSessionUserForLog } from './auth.js';
10
- import { E as EntityCrudAction, S as SessionUser, e as VendorScope } from './vendor-scope-DTYhJk_I.js';
11
- export { A as ADMIN_GROUP_NAME, a as AuthHelpers, b as EntityPermissionFlags, G as GetSession, O as OPEN_ENDPOINTS, P as PERMISSION_REQUIRED_ENDPOINTS, R as RBAC_ADMIN_ONLY_ENTITIES, V as VENDOR_OWNER_GROUP_NAME, c as VENDOR_SCOPED_STORE_ENTITIES, d as VENDOR_STORE_RBAC_ENTITIES, f as canManageRoles, g as canManageVendorRoles, h as canManageVendorTeam, i as canOnboardVendors, j as createAuthHelpers, k as createCmsAuthBundle, l as getPermissionableEntityKeys, m as getRequiredPermission, n as hasEntityPermission, o as isOpenEndpoint, p as isPlatformAdministrator, q as isPublicMethod, r as isSuperAdminGroupName, s as isVendorGroupName, t as isVendorOwner, u as isVendorPortalUser, v as isVendorStaff, w as permissionRowsToRecord, x as resolveVendorScopeFromSessionUser, y as sessionHasEntityAccess, z as vendorPortalFlagsFromUser } from './vendor-scope-DTYhJk_I.js';
12
- import { a as NavbarConfig, F as FooterConfig } from './types-DCVaXlPV.js';
13
- export { A as AdminNavItem, D as DEFAULT_ADMIN_NAV } from './config-DJ5CmQvS.js';
14
- import 'next-auth/jwt';
15
- import 'next-auth';
6
+ import { EventEmitter } from 'events';
7
+ import { NextAuthOptions } from 'next-auth';
8
+ import { getToken } from 'next-auth/jwt';
16
9
 
17
10
  interface PluginContext {
18
11
  dataSource: unknown;
@@ -42,6 +35,8 @@ interface CmsApp {
42
35
  dataSource: unknown;
43
36
  getPlugin<T = unknown>(name: string): T | undefined;
44
37
  }
38
+ /** Merge extra plugin instances on top of an existing CMS app (overlay wins). */
39
+ declare function overlayCmsPlugins(base: CmsApp, plugins: Record<string, unknown>): CmsApp;
45
40
  declare function createCmsApp(options: CreateCmsAppOptions): Promise<CmsApp>;
46
41
 
47
42
  interface ContactFormData {
@@ -126,7 +121,7 @@ declare class ERPSubmissionService {
126
121
  }[]): ContactFormData | null;
127
122
  }
128
123
 
129
- interface CmsAppLike$3 {
124
+ interface CmsAppLike$4 {
130
125
  getPlugin(name: string): unknown;
131
126
  }
132
127
  type ErpJobPayload = {
@@ -145,8 +140,8 @@ type ErpJobPayload = {
145
140
  kind: 'productUpsert';
146
141
  product: Record<string, unknown>;
147
142
  };
148
- declare function queueErp(cms: CmsAppLike$3, payload: ErpJobPayload): Promise<void>;
149
- declare function registerErpQueueProcessor(cms: CmsAppLike$3): void;
143
+ declare function queueErp(cms: CmsAppLike$4, payload: ErpJobPayload): Promise<void>;
144
+ declare function registerErpQueueProcessor(cms: CmsAppLike$4): void;
150
145
 
151
146
  /**
152
147
  * Duck-typed DataSource so host apps (e.g. Next) can pass their own TypeORM instance
@@ -167,7 +162,7 @@ type ErpPaidOrderEntityMap = Record<string, unknown>;
167
162
  * Enqueues ERP `order.created` only when the order has at least one **completed** payment.
168
163
  * Include `payments` in the payload.
169
164
  */
170
- declare function queueErpPaidOrderForOrderId(cms: CmsAppLike$3, dataSource: ErpPaidOrderDataSource, entityMap: ErpPaidOrderEntityMap, orderId: number): Promise<void>;
165
+ declare function queueErpPaidOrderForOrderId(cms: CmsAppLike$4, dataSource: ErpPaidOrderDataSource, entityMap: ErpPaidOrderEntityMap, orderId: number): Promise<void>;
171
166
 
172
167
  interface ErpContactSyncInput {
173
168
  name: string;
@@ -183,7 +178,7 @@ interface ErpContactSyncInput {
183
178
  * When ERP is enabled and plugin loaded, enqueue `create-contact` (non-fatal on failure).
184
179
  * Used for admin CRUD and storefront contact paths — not form submissions (those use lead/opportunity).
185
180
  */
186
- declare function queueErpCreateContactIfEnabled(cms: CmsAppLike$3, dataSource: ErpPaidOrderDataSource, entityMap: ErpPaidOrderEntityMap, input: ErpContactSyncInput): Promise<void>;
181
+ declare function queueErpCreateContactIfEnabled(cms: CmsAppLike$4, dataSource: ErpPaidOrderDataSource, entityMap: ErpPaidOrderEntityMap, input: ErpContactSyncInput): Promise<void>;
187
182
 
188
183
  interface ERPPluginConfig {
189
184
  webhookUrl: string;
@@ -195,6 +190,47 @@ interface ERPPluginInstance {
195
190
  }
196
191
  declare function erpPlugin(config: ERPPluginConfig): CmsPlugin<ERPPluginInstance>;
197
192
 
193
+ /** Social entry: use `iconUrl` for an image, or `icon` (emoji/text) as fallback when no image. */
194
+ interface SocialLinkItem {
195
+ url: string;
196
+ iconUrl?: string;
197
+ icon?: string;
198
+ }
199
+ interface CompanyDetails {
200
+ logoUrl?: string;
201
+ companyName?: string;
202
+ supportEmail?: string;
203
+ supportPhone?: string;
204
+ socialLinks?: SocialLinkItem[];
205
+ /** Shown below footer rows; from email plugin settings */
206
+ footerDisclaimer?: string;
207
+ /** Heading above social icons (default "Follow Us") */
208
+ followUsTitle?: string;
209
+ }
210
+ /** One row in order-placed transactional emails */
211
+ interface OrderPlacedLineItem {
212
+ productName: string;
213
+ quantity: number;
214
+ unitPrice: number | string;
215
+ lineTotal: number | string;
216
+ sku?: string | null;
217
+ tax?: number | string | null;
218
+ hsn?: string | null;
219
+ }
220
+ /** Merge branding + email plugin settings for layout (email overrides when set). */
221
+ declare function mergeEmailLayoutCompanyDetails(branding: Record<string, string>, emailSettings: Record<string, string>): CompanyDetails;
222
+ interface EmailTemplateResult {
223
+ subject: string;
224
+ bodyHtml: string;
225
+ text?: string;
226
+ }
227
+ type TemplateContext<T = unknown> = T & {
228
+ companyDetails: CompanyDetails;
229
+ };
230
+ declare const EMAIL_TEMPLATE_NAMES: readonly ["signup", "passwordReset", "passwordChange", "orderPlaced", "returnInitiated", "shippingUpdate", "invite", "formSubmission", "otp", "chatLead", "vendorOnboarded"];
231
+ type EmailTemplateName = (typeof EMAIL_TEMPLATE_NAMES)[number];
232
+ declare function getCompanyDetailsFromSettings(settingsGroup: Record<string, string>): CompanyDetails;
233
+
198
234
  interface RenderEmailOptions {
199
235
  renderLayout?: (opts: {
200
236
  bodyHtml: string;
@@ -288,7 +324,7 @@ declare function renderLayout(options: {
288
324
  companyDetails: CompanyDetails;
289
325
  }): string;
290
326
 
291
- interface CmsAppLike$2 {
327
+ interface CmsAppLike$3 {
292
328
  getPlugin(name: string): unknown;
293
329
  }
294
330
  /** Context for template rendering: at least companyDetails; template-specific fields (formName, etc.) are allowed. */
@@ -302,8 +338,8 @@ interface EmailJobPayload {
302
338
  html?: string;
303
339
  text?: string;
304
340
  }
305
- declare function registerEmailQueueProcessor(cms: CmsAppLike$2): void;
306
- declare function queueEmail(cms: CmsAppLike$2, payload: EmailJobPayload): Promise<void>;
341
+ declare function registerEmailQueueProcessor(cms: CmsAppLike$3): void;
342
+ declare function queueEmail(cms: CmsAppLike$3, payload: EmailJobPayload): Promise<void>;
307
343
  interface OrderPlacedEmailPayload {
308
344
  orderNumber: string;
309
345
  total?: string | number;
@@ -321,7 +357,7 @@ interface OrderPlacedEmailPayload {
321
357
  shippingAddress?: Record<string, string>;
322
358
  }
323
359
  /** Queues one `orderPlaced` email per recipient (customer + each unique sales address; skips sales if same as customer). */
324
- declare function queueOrderPlacedEmails(cms: CmsAppLike$2, payload: OrderPlacedEmailPayload): Promise<void>;
360
+ declare function queueOrderPlacedEmails(cms: CmsAppLike$3, payload: OrderPlacedEmailPayload): Promise<void>;
325
361
  interface VendorOnboardEmailPayload {
326
362
  vendorName: string;
327
363
  vendorSlug?: string;
@@ -336,7 +372,7 @@ interface VendorOnboardEmailPayload {
336
372
  sendToOwner?: boolean;
337
373
  }
338
374
  /** Queues `vendorOnboarded` email to owner and each unique notify address (sales team settings). */
339
- declare function queueVendorOnboardEmails(cms: CmsAppLike$2, payload: VendorOnboardEmailPayload): Promise<void>;
375
+ declare function queueVendorOnboardEmails(cms: CmsAppLike$3, payload: VendorOnboardEmailPayload): Promise<void>;
340
376
 
341
377
  interface EmailPluginConfig {
342
378
  type: 'AWS' | 'SMTP' | 'GMAIL' | 'SENDGRID';
@@ -404,7 +440,7 @@ interface AnalyticsPluginConfig {
404
440
  }
405
441
  declare function analyticsPlugin(config?: AnalyticsPluginConfig): CmsPlugin<AnalyticsService>;
406
442
 
407
- type MessageTemplateRowLoader = (channel: string, templateKey: string) => Promise<{
443
+ type MessageTemplateRowLoader$1 = (channel: string, templateKey: string) => Promise<{
408
444
  body: string;
409
445
  externalTemplateRef: string | null;
410
446
  providerMeta: Record<string, unknown> | null;
@@ -444,7 +480,7 @@ interface SmsServiceConfig {
444
480
  webhookSecret?: string;
445
481
  }
446
482
 
447
- interface CmsAppLike$1 {
483
+ interface CmsAppLike$2 {
448
484
  getPlugin(name: string): unknown;
449
485
  }
450
486
  interface SmsJobPayload {
@@ -455,14 +491,14 @@ interface SmsJobPayload {
455
491
  variables?: Record<string, string>;
456
492
  otpCode?: string;
457
493
  }
458
- declare function registerSmsQueueProcessor(cms: CmsAppLike$1): void;
459
- declare function queueSms(cms: CmsAppLike$1, payload: SmsJobPayload): Promise<void>;
494
+ declare function registerSmsQueueProcessor(cms: CmsAppLike$2): void;
495
+ declare function queueSms(cms: CmsAppLike$2, payload: SmsJobPayload): Promise<void>;
460
496
 
461
497
  interface SmsPluginConfig extends Partial<SmsServiceConfig> {
462
498
  /** Load admin settings group `sms` (enabled, smsProvider). Secrets typically stay in env. */
463
499
  getSmsSettings?: () => Promise<Record<string, string>>;
464
500
  /** Resolve `message_templates` rows for SMS (required for `templateKey` sends). */
465
- getMessageTemplateRow?: MessageTemplateRowLoader;
501
+ getMessageTemplateRow?: MessageTemplateRowLoader$1;
466
502
  }
467
503
  interface SmsServiceInterface {
468
504
  send(opts: {
@@ -475,6 +511,48 @@ interface SmsServiceInterface {
475
511
  }
476
512
  declare function smsPlugin(config?: SmsPluginConfig): CmsPlugin<SmsServiceInterface | null>;
477
513
 
514
+ type MessageTemplateRowLoader = (channel: string, templateKey: string) => Promise<{
515
+ body: string;
516
+ externalTemplateRef: string | null;
517
+ enabled: boolean;
518
+ } | null>;
519
+ interface WhatsAppServiceConfig {
520
+ accessToken?: string;
521
+ phoneNumberId?: string;
522
+ apiVersion?: string;
523
+ }
524
+
525
+ interface CmsAppLike$1 {
526
+ getPlugin(name: string): unknown;
527
+ }
528
+ interface WhatsAppJobPayload {
529
+ to: string;
530
+ body?: string;
531
+ templateKey?: string;
532
+ externalTemplateRef?: string;
533
+ templateLanguage?: string;
534
+ variables?: Record<string, string>;
535
+ templateParamOrder?: readonly string[];
536
+ }
537
+ declare function registerWhatsAppQueueProcessor(cms: CmsAppLike$1): void;
538
+ declare function queueWhatsApp(cms: CmsAppLike$1, payload: WhatsAppJobPayload): Promise<boolean>;
539
+
540
+ interface WhatsAppPluginConfig extends Partial<WhatsAppServiceConfig> {
541
+ getWhatsAppSettings?: () => Promise<Record<string, string>>;
542
+ getMessageTemplateRow?: MessageTemplateRowLoader;
543
+ }
544
+ interface WhatsAppServiceInterface {
545
+ send(opts: {
546
+ to: string;
547
+ body?: string;
548
+ templateKey?: string;
549
+ externalTemplateRef?: string;
550
+ variables?: Record<string, string>;
551
+ templateParamOrder?: readonly string[];
552
+ }): Promise<boolean>;
553
+ }
554
+ declare function whatsappPlugin(config?: WhatsAppPluginConfig): CmsPlugin<WhatsAppServiceInterface | null>;
555
+
478
556
  interface PaymentIntent {
479
557
  id: string;
480
558
  clientSecret: string;
@@ -501,6 +579,13 @@ interface RazorpayConfig {
501
579
  type PaymentPluginConfig = StripeConfig | RazorpayConfig;
502
580
  declare function paymentPlugin(config: PaymentPluginConfig): CmsPlugin<PaymentServiceInterface | undefined>;
503
581
 
582
+ /**
583
+ * Storage plugin contract: upload a file and return its public URL.
584
+ */
585
+ interface StorageService {
586
+ upload(buffer: Buffer, key: string, contentType: string): Promise<string>;
587
+ }
588
+
504
589
  interface S3StoragePluginConfig {
505
590
  region: string;
506
591
  accessKeyId: string;
@@ -636,6 +721,173 @@ declare class LlmService implements LlmServiceInterface {
636
721
  streamChat(messages: LlmMessage[], options?: LlmChatOptions): AsyncIterable<string>;
637
722
  }
638
723
 
724
+ /** Canonical name for new installs / migrations */
725
+ declare const ADMIN_GROUP_NAME = "Administrator";
726
+ /** System administrator group (roles UI + users / user_groups / permissions bypass). */
727
+ declare function isSuperAdminGroupName(name: string | null | undefined): boolean;
728
+ type EntityCrudAction = 'create' | 'read' | 'update' | 'delete';
729
+ type EntityPermissionFlags = {
730
+ c: boolean;
731
+ r: boolean;
732
+ u: boolean;
733
+ d: boolean;
734
+ };
735
+ declare function getPermissionableEntityKeys(entityMap: Record<string, unknown>): string[];
736
+ declare function permissionRowsToRecord(rows: Array<{
737
+ entity: string;
738
+ canCreate: boolean;
739
+ canRead: boolean;
740
+ canUpdate: boolean;
741
+ canDelete: boolean;
742
+ }> | undefined): Record<string, EntityPermissionFlags>;
743
+ declare function hasEntityPermission(record: Record<string, EntityPermissionFlags> | undefined, entity: string, action: EntityCrudAction): boolean;
744
+
745
+ /**
746
+ * @deprecated Administrator bypass is now full entity access via `isRBACAdmin` in `sessionHasEntityAccess`.
747
+ * Kept for backwards-compatible imports.
748
+ */
749
+ declare const RBAC_ADMIN_ONLY_ENTITIES: Set<string>;
750
+ interface SessionUser {
751
+ id?: string;
752
+ email?: string | null;
753
+ name?: string | null;
754
+ groupId?: number;
755
+ /** User group display name (from login). */
756
+ groupName?: string | null;
757
+ /** @deprecated use entityPerms / isRBACAdmin */
758
+ permissions?: string[];
759
+ /** Administrator group: bypasses entity-level RBAC on all resources */
760
+ isRBACAdmin?: boolean;
761
+ entityPerms?: Record<string, EntityPermissionFlags>;
762
+ /** When false and not isRBACAdmin, admin API/UI is denied. */
763
+ adminAccess?: boolean;
764
+ /** Vendor stores this user can access (from vendor_users). */
765
+ vendorIds?: number[];
766
+ /** Active vendor for scoped CRUD (vendor staff). */
767
+ activeVendorId?: number | null;
768
+ /** Role for the active vendor link (`vendor_users.role`). */
769
+ vendorRole?: 'owner' | 'staff' | null;
770
+ /** Active vendor-scoped role id (`vendor_users.vendorRoleId`). */
771
+ vendorRoleId?: number | null;
772
+ vendorRoleName?: string | null;
773
+ /** True when active vendor role has `isOwnerRole`. */
774
+ isVendorRoleOwner?: boolean;
775
+ /** Permissions from active vendor role (`vendor_role_permissions`). */
776
+ vendorEntityPerms?: Record<string, EntityPermissionFlags>;
777
+ /** Set at login: vendor store portal (not platform admin). */
778
+ isVendorPortal?: boolean;
779
+ /** Set at login: vendor store owner (team + permissions). */
780
+ isVendorOwner?: boolean;
781
+ }
782
+ declare function sessionHasEntityAccess(user: SessionUser | null | undefined, entity: string, action: EntityCrudAction): boolean;
783
+ declare function canManageRoles(user: SessionUser | null | undefined): boolean;
784
+ type GetSession = () => Promise<{
785
+ user?: SessionUser;
786
+ } | null>;
787
+ declare const OPEN_ENDPOINTS: Array<Record<string, string[]>>;
788
+ declare const PERMISSION_REQUIRED_ENDPOINTS: Record<string, string[]>;
789
+ declare function isOpenEndpoint(pathname: string): boolean;
790
+ declare function getRequiredPermission(pathname: string): string[] | null;
791
+ declare function isPublicMethod(pathname: string, method: string): boolean;
792
+ interface AuthHelpers {
793
+ requireAuth(req: Request): Promise<Response | null>;
794
+ requirePermission(req: Request, permission: string): Promise<Response | null>;
795
+ requireEntityPermission(req: Request, entity: string, action: EntityCrudAction): Promise<Response | null>;
796
+ requireAdminAccess(req: Request): Promise<Response | null>;
797
+ getAuthenticatedUser(): Promise<SessionUser | null>;
798
+ }
799
+ declare function createAuthHelpers(getSession: GetSession, NextResponse: {
800
+ json: (body: unknown, init?: {
801
+ status?: number;
802
+ }) => Response;
803
+ }): AuthHelpers;
804
+ /** Pass return value into `createCmsApiHandler` (includes `getSessionUser` for vendor store APIs). */
805
+ declare function createCmsAuthBundle(getSession: GetSession, NextResponse: {
806
+ json: (body: unknown, init?: {
807
+ status?: number;
808
+ }) => Response;
809
+ }): {
810
+ requireAuth: (req: Request) => Promise<Response | null>;
811
+ requireAdminAccess: (req: Request) => Promise<Response | null>;
812
+ requireEntityPermission: (req: Request, entity: string, action: EntityCrudAction) => Promise<Response | null>;
813
+ getSessionUser: () => Promise<SessionUser | null>;
814
+ getAuthenticatedUser: () => Promise<SessionUser | null>;
815
+ };
816
+
817
+ /** Entities with a `vendorId` column (store data). */
818
+ declare const VENDOR_SCOPED_STORE_ENTITIES: Set<string>;
819
+ /**
820
+ * Store admin RBAC for vendor portal users (read/create/update/delete fallbacks in rbac-debug).
821
+ * Includes entities without `vendorId` that are still part of the store admin UI.
822
+ */
823
+ declare const VENDOR_STORE_RBAC_ENTITIES: Set<string>;
824
+ type VendorScope = {
825
+ type: 'all';
826
+ } | {
827
+ type: 'vendor';
828
+ vendorId: number;
829
+ vendorIds: number[];
830
+ } | {
831
+ type: 'deny';
832
+ };
833
+ declare const VENDOR_OWNER_GROUP_NAME = "Vendor Owner";
834
+ /** User groups treated as vendor store staff (sidebar + scoped admin). */
835
+ declare function isVendorGroupName(name: string | null | undefined): boolean;
836
+ declare function isPlatformAdministrator(user: SessionUser | null | undefined): boolean;
837
+ /** Vendor portal UI (store + store admin), not platform admin. */
838
+ declare function isVendorPortalUser(user: SessionUser | null | undefined): boolean;
839
+ declare function isVendorStaff(user: SessionUser | null | undefined): boolean;
840
+ /** Vendor store owner (manages team + role permissions for their store). */
841
+ declare function isVendorOwner(user: SessionUser | null | undefined): boolean;
842
+ declare function canManageVendorTeam(user: SessionUser | null | undefined): boolean;
843
+ declare function canManageVendorRoles(user: SessionUser | null | undefined): boolean;
844
+ /** Platform admins (Administrator group) can onboard vendors. */
845
+ declare function canOnboardVendors(user: SessionUser | null | undefined): boolean;
846
+ declare function resolveVendorScopeFromSessionUser(user: SessionUser | null | undefined): VendorScope;
847
+ /** Compute portal flags at login (persist on JWT). */
848
+ declare function vendorPortalFlagsFromUser(input: {
849
+ email: string;
850
+ isRBACAdmin: boolean;
851
+ groupName?: string | null;
852
+ vendorIds?: number[];
853
+ vendorRole?: 'owner' | 'staff' | null;
854
+ isVendorRoleOwner?: boolean;
855
+ }): {
856
+ isVendorPortal: boolean;
857
+ isVendorOwner: boolean;
858
+ };
859
+
860
+ type EntityMap$2 = Record<string, typeorm.EntityTarget<typeorm.ObjectLiteral>>;
861
+ interface CrudHandlerOptions {
862
+ requireAuth: (req: Request) => Promise<Response | null>;
863
+ json: (body: unknown, init?: {
864
+ status?: number;
865
+ }) => Response;
866
+ requireEntityPermission?: (req: Request, entity: string, action: EntityCrudAction) => Promise<Response | null>;
867
+ /** When set, contact create/update enqueues ERP `create-contact` (non-fatal). */
868
+ getCms?: () => Promise<{
869
+ getPlugin: (name: string) => unknown;
870
+ }>;
871
+ /** When set, soft-delete sets `deletedBy` from the current admin user. */
872
+ getDeletedByUserId?: (req: Request) => Promise<number | null>;
873
+ /** When set, store rows are filtered by session vendor (platform admin bypasses). */
874
+ getVendorScope?: () => Promise<VendorScope>;
875
+ /** Hydrated session (group + vendor context) for vendorId resolution on create. */
876
+ getHydratedSessionUser?: () => Promise<SessionUser | null>;
877
+ }
878
+ declare function createCrudHandler(dataSource: DataSource, entityMap: EntityMap$2, options: CrudHandlerOptions): {
879
+ GET(req: Request, resource: string): Promise<Response>;
880
+ POST(req: Request, resource: string): Promise<Response>;
881
+ GET_METADATA(req: Request, resource: string): Promise<Response>;
882
+ BULK_POST(req: Request, resource: string): Promise<Response>;
883
+ GET_EXPORT(req: Request, resource: string): Promise<Response>;
884
+ };
885
+ declare function createCrudByIdHandler(dataSource: DataSource, entityMap: EntityMap$2, options: CrudHandlerOptions): {
886
+ GET(req: Request, resource: string, id: string): Promise<Response>;
887
+ PUT(req: Request, resource: string, id: string): Promise<Response>;
888
+ DELETE(req: Request, resource: string, id: string): Promise<Response>;
889
+ };
890
+
639
891
  declare class LlmAgent {
640
892
  id: number;
641
893
  name: string;
@@ -797,337 +1049,461 @@ declare function pgBossScheduleNameForId(scheduleId: string): string;
797
1049
  declare function buildCronFromSchedule(schedule: Pick<JobSchedule, 'scheduleMode' | 'intervalMinutes' | 'runAtTime' | 'runOnDays' | 'cronExpression'>): string;
798
1050
  declare function validateScheduleInput(schedule: Pick<JobSchedule, 'scheduleMode' | 'intervalMinutes' | 'runAtTime' | 'cronExpression'>): string | null;
799
1051
 
800
- type CaptchaProviderId = 'turnstile' | 'recaptcha_v3';
801
- interface CaptchaPublicConfig {
802
- enabled: boolean;
803
- activeProvider: CaptchaProviderId | null;
804
- siteKey: string | null;
805
- availableProviders: Array<{
806
- id: CaptchaProviderId;
807
- siteKey: string;
808
- }>;
809
- multipleProviders: boolean;
810
- }
811
- type CaptchaVerifyResult = {
812
- ok: true;
813
- } | {
814
- ok: false;
815
- status: number;
816
- message: string;
817
- };
818
- declare function buildCaptchaPublicConfig(config: Record<string, string>): CaptchaPublicConfig;
819
- declare class CaptchaService {
820
- private readonly env;
821
- constructor(env: Record<string, string>);
822
- isEnforced(): boolean;
823
- getPublicConfig(): CaptchaPublicConfig;
824
- verify(body: Record<string, unknown>, req: Request): Promise<CaptchaVerifyResult>;
825
- }
826
-
827
- declare function captchaPlugin(): CmsPlugin<CaptchaService | void>;
828
-
829
- type JsonResponse = (body: unknown, init?: {
830
- status?: number;
831
- headers?: HeadersInit;
832
- }) => Response;
833
- declare function assertCaptchaOk(getCms: (() => Promise<{
834
- getPlugin: (name: string) => unknown;
835
- }>) | undefined, body: Record<string, unknown>, req: Request, json: JsonResponse): Promise<Response | null>;
1052
+ /**
1053
+ * Auth API handler factories. Inject dataSource + entityMap, sendEmail, hash/compare; optional hooks to customize.
1054
+ */
836
1055
 
837
- interface LatestArticleFromFeed {
838
- title?: string;
839
- link?: string;
840
- /** Short excerpt */
841
- summary?: string;
842
- /** Full content if available */
843
- content?: string;
844
- date: Date;
845
- creator?: string;
846
- categories?: string[];
1056
+ interface AuthHandlersConfig {
1057
+ json: (body: unknown, init?: {
1058
+ status?: number;
1059
+ }) => Response;
1060
+ baseUrl: string;
1061
+ hashPassword: (plain: string) => Promise<string>;
1062
+ comparePassword: (plain: string, hash: string) => Promise<boolean>;
847
1063
  }
848
- type RssItem = {
849
- title?: string;
850
- link?: string;
851
- pubDate?: string;
852
- isoDate?: string;
853
- contentSnippet?: string;
854
- summary?: string;
855
- description?: string;
856
- content?: string;
857
- creator?: string;
858
- 'dc:creator'?: string;
859
- 'content:encoded'?: string;
860
- categories?: string[];
861
- guid?: string | {
862
- _: string;
863
- };
864
- };
865
- declare function getRssArticleSummaryFromItem(item: RssItem): {
866
- summary: string;
867
- fullContent: string;
868
- };
869
- type BlogGeneratorDraftParseMode = 'json' | 'plaintext';
870
- interface BlogGeneratorSeoDraft {
871
- title: string | null;
872
- description: string | null;
873
- keywords: string | null;
874
- ogTitle: string | null;
875
- ogDescription: string | null;
1064
+ interface ForgotPasswordConfig extends AuthHandlersConfig {
1065
+ dataSource: DataSource;
1066
+ entityMap: EntityMap$2;
1067
+ sendEmail?: (opts: {
1068
+ to: string;
1069
+ subject: string;
1070
+ html: string;
1071
+ text?: string;
1072
+ /** Plain reset URL for templated emails (preferred over parsing html). */
1073
+ resetLink?: string;
1074
+ }) => Promise<void>;
1075
+ resetExpiryHours?: number;
1076
+ afterCreateToken?: (email: string, resetLink: string) => Promise<void>;
1077
+ }
1078
+ declare function createForgotPasswordHandler(config: ForgotPasswordConfig): (request: Request) => Promise<Response>;
1079
+ interface SetPasswordConfig extends AuthHandlersConfig {
1080
+ dataSource: DataSource;
1081
+ entityMap: EntityMap$2;
1082
+ minPasswordLength?: number;
1083
+ beforeUpdate?: (email: string, userId: number) => Promise<void>;
876
1084
  }
877
- interface BlogGeneratorBlogDraft {
878
- title: string;
879
- slug?: string;
880
- markdown: string;
881
- /** Short plain-text copy for social (e.g. LinkedIn); optional until social LLM step runs. */
882
- socialMediaContent?: string | null;
883
- categoryName: string | null;
884
- seo: BlogGeneratorSeoDraft;
885
- /** Suggested tag labels (may not exist in CMS yet). */
886
- tags: string[];
887
- parseMode: BlogGeneratorDraftParseMode;
1085
+ declare function createSetPasswordHandler(config: SetPasswordConfig): (request: Request) => Promise<Response>;
1086
+ interface InviteAcceptConfig extends AuthHandlersConfig {
1087
+ dataSource: DataSource;
1088
+ entityMap: EntityMap$2;
1089
+ beforeActivate?: (email: string, userId: number) => Promise<void>;
1090
+ }
1091
+ /** Decode invite token (base64 email) and set password + unblock user */
1092
+ declare function createInviteAcceptHandler(config: InviteAcceptConfig): (request: Request) => Promise<Response>;
1093
+ interface ChangePasswordConfig extends AuthHandlersConfig {
1094
+ dataSource: DataSource;
1095
+ entityMap: EntityMap$2;
1096
+ getSession: () => Promise<{
1097
+ user?: {
1098
+ email?: string | null;
1099
+ };
1100
+ } | null>;
1101
+ minPasswordLength?: number;
1102
+ beforeUpdate?: (email: string) => Promise<void>;
1103
+ }
1104
+ declare function createChangePasswordHandler(config: ChangePasswordConfig): (request: Request) => Promise<Response>;
1105
+ interface UserAuthApiConfig extends ForgotPasswordConfig, Omit<SetPasswordConfig, 'dataSource' | 'entityMap' | 'json' | 'baseUrl' | 'hashPassword' | 'comparePassword'>, Omit<InviteAcceptConfig, 'dataSource' | 'entityMap' | 'json' | 'baseUrl' | 'hashPassword' | 'comparePassword'>, Omit<ChangePasswordConfig, 'dataSource' | 'entityMap' | 'json' | 'baseUrl' | 'hashPassword' | 'comparePassword' | 'beforeUpdate' | 'getSession'> {
1106
+ getSession?: () => Promise<{
1107
+ user?: {
1108
+ email?: string | null;
1109
+ };
1110
+ } | null>;
1111
+ beforeChangePasswordUpdate?: (email: string) => Promise<void>;
888
1112
  }
889
1113
  /**
890
- * Parses the LLM reply: prefers a single JSON object with blogTitle, blogHtml/blogMarkdown/content, categoryName, seo, …
891
- * Falls back to treating the entire string as HTML (or legacy markdown) if JSON parsing fails.
1114
+ * Single router for all user-auth APIs. Mount in the app once.
1115
+ * Use when you have no users/[id] route (else Next.js gives [id] precedence and "forgot-password" would match as id).
1116
+ * Path is the segment after the mount (e.g. "forgot-password"). Returns 404 for unknown paths.
892
1117
  */
893
- declare function parseBlogGeneratorAgentContent(raw: string): BlogGeneratorBlogDraft;
894
- declare function resolveBlogCategoryIdByName(needle: string | null | undefined, rows: readonly {
895
- id: number;
896
- name: string;
897
- }[]): {
898
- categoryId: number | null;
899
- matched: boolean;
1118
+ declare function createUserAuthApiRouter(config: UserAuthApiConfig): {
1119
+ POST(req: Request, pathname: string): Promise<Response>;
900
1120
  };
1121
+
901
1122
  /**
902
- * Minimal user payload: latest item per feed only (system prompt carries writing rules).
1123
+ * CMS API handlers: dashboard, analytics, upload, blog/form by slug, users (list/create/get/update/delete/regenerate-invite/avatar/profile).
1124
+ * All accept injectable deps; upload supports S3 or local.
903
1125
  */
904
- declare function buildRssUserPromptFromFeeds(feeds: ReadonlyArray<{
905
- rssUrl: string;
906
- article: LatestArticleFromFeed;
907
- }>): string;
1126
+
1127
+ type RequireEntityPermissionFn = (req: Request, entity: string, action: EntityCrudAction) => Promise<Response | null>;
908
1128
  /**
909
- * User message for the metadata-only LLM step (one blog at a time).
1129
+ * Optional JSON in `LlmAgent.validationRules`. Used for programmatic checks before the LLM call.
1130
+ * For natural-language output rules, use `guardrails` / `outputRules` / `outputInstructions` (merged into system prompt).
910
1131
  */
911
- declare function buildBlogMetadataUserPrompt(opts: {
912
- title: string;
913
- markdown: string;
914
- categoryNames: readonly string[];
915
- tagNames: readonly string[];
916
- }): string;
917
- /** Parses JSON from the metadata-enrichment LLM (category, slug, seo, tags). */
918
- declare function parseBlogMetadataEnrichmentJson(raw: string): {
919
- categoryName: string | null;
920
- blogSlug: string | null;
921
- seo: BlogGeneratorSeoDraft;
922
- tags: string[];
1132
+ type LlmAgentValidationRulesJson = {
1133
+ maxUserChars?: number;
1134
+ maxMessageLength?: number;
1135
+ minUserChars?: number;
1136
+ minMessageLength?: number;
1137
+ blockedSubstrings?: string[];
1138
+ /** Shown to the model as output guardrails (first non-empty of guardrails | outputRules | outputInstructions wins). */
1139
+ guardrails?: string;
1140
+ outputRules?: string;
1141
+ outputInstructions?: string;
1142
+ };
1143
+ type ParsedLlmAgentValidation = {
1144
+ /** Subset used for length / substring checks only. */
1145
+ structured: Pick<LlmAgentValidationRulesJson, 'maxUserChars' | 'maxMessageLength' | 'minUserChars' | 'minMessageLength' | 'blockedSubstrings'>;
1146
+ /** Appended to system prompt so the model follows output guardrails. */
1147
+ guardrailsForPrompt: string | null;
923
1148
  };
924
1149
  /**
925
- * Parses LLM output: prefers HTML + {@link BLOG_GENERATOR_MARKDOWN_ARTICLE_SEPARATOR} for multiple articles.
926
- * If the model still returns legacy JSON with `blogHtml` / `blogMarkdown`, returns a single draft from that object.
1150
+ * - Valid JSON object: structural keys validation; `guardrails` / `outputRules` / `outputInstructions` → prompt suffix.
1151
+ * - Not JSON: entire string is treated as prose guardrails for the prompt (no programmatic rules unless you use JSON).
927
1152
  */
928
- declare function parseBlogGeneratorModelOutput(raw: string): BlogGeneratorBlogDraft[];
929
- declare class BlogGeneratorService {
930
- readonly version: "1.0.0";
931
- getLatestArticleFromFeed(rssUrl: string): Promise<LatestArticleFromFeed | null>;
932
- /** Defaults for the Blog Generator Agent (admin can override per request). */
933
- getAgentDefaults(): {
934
- agentName: string;
935
- systemInstruction: string;
936
- validationRules: string;
937
- };
938
- /**
939
- * Second LLM call: one draft at a time — category, URL slug, SEO fields, tags (JSON).
940
- */
941
- private enrichBlogDraftWithLlmMetadata;
942
- /**
943
- * Third LLM call: one draft at a time short social copy (JSON `{ socialMediaContent }`).
944
- */
945
- private enrichBlogDraftWithLlmSocial;
946
- /**
947
- * Fetches the latest item for each RSS URL, then calls {@link LlmServiceInterface.chatAgent}.
948
- * `userPrompt` is only per-feed source material; rules live in the system prompt.
949
- * Expects HTML article fragment(s), optionally separated by {@link BLOG_GENERATOR_MARKDOWN_ARTICLE_SEPARATOR}.
950
- */
951
- generateBlogMarkdownFromRss(params: {
952
- llm: LlmServiceInterface;
953
- /** Single feed (legacy). */
954
- rssUrl?: string;
955
- /** One or more feeds; latest item per URL is sent together. Prefer this when multiple URLs. */
956
- rssUrls?: readonly string[];
957
- systemInstruction?: string;
958
- validationRules?: string;
959
- /** Reserved for future structured output; writer does not inject categories into the user prompt. */
960
- categoryNamesHint?: readonly string[];
961
- /** Names of non-deleted tags in CMS (hint for reuse). */
962
- tagNamesHint?: readonly string[];
963
- /** From optional `llm_agents` row (slug `blog-generator`): model / sampling for the writer step. */
964
- llmAgentChatOptions?: Pick<LlmAgentOptions, 'model' | 'temperature' | 'max_tokens'>;
965
- /** Optional overrides for the metadata step; defaults live in `blog-generator-metadata-defaults.ts`. */
966
- metadataSystemInstruction?: string;
967
- metadataValidationRules?: string;
968
- /** From optional `llm_agents` row (slug `blog-generator-metadata`): model / sampling for metadata only. */
969
- metadataLlmAgentChatOptions?: Pick<LlmAgentOptions, 'model' | 'temperature' | 'max_tokens'>;
970
- /** Optional overrides for the social-summary step; defaults in `blog-generator-social-defaults.ts`. */
971
- socialSystemInstruction?: string;
972
- socialValidationRules?: string;
973
- /** From optional `llm_agents` row (slug `blog-generator-social`): model / sampling for social copy only. */
974
- socialLlmAgentChatOptions?: Pick<LlmAgentOptions, 'model' | 'temperature' | 'max_tokens'>;
975
- }): Promise<{
976
- agentName: string;
977
- feedArticles: Array<{
978
- rssUrl: string;
979
- article: LatestArticleFromFeed;
980
- }>;
981
- /** First feed's article (backward compatibility). */
982
- article: LatestArticleFromFeed;
983
- /** Raw model reply (HTML body per defaults; legacy markdown or JSON still parsed when present). */
984
- blogMarkdown: string;
985
- blogDrafts: BlogGeneratorBlogDraft[];
986
- /** Same as first draft; backward compatibility. */
987
- blogDraft: BlogGeneratorBlogDraft;
988
- }>;
1153
+ declare function parseLlmAgentValidationRules(validationRulesText: string | null | undefined): ParsedLlmAgentValidation;
1154
+ declare function validateUserMessageAgainstStructuredRules(message: string, structured: ParsedLlmAgentValidation['structured']): {
1155
+ ok: true;
1156
+ } | {
1157
+ ok: false;
1158
+ error: string;
1159
+ };
1160
+ /** Parses `validationRules` then runs programmatic checks only. */
1161
+ declare function validateUserMessageAgainstAgentRules(message: string, validationRulesText: string | null | undefined): {
1162
+ ok: true;
1163
+ } | {
1164
+ ok: false;
1165
+ error: string;
1166
+ };
1167
+ /** Merges guardrails prose into the system instruction sent to the model. */
1168
+ declare function mergeGuardrailsIntoSystemPrompt(baseSystem: string | undefined, guardrailsForPrompt: string | null): string;
1169
+ interface CmsHandlersBase {
1170
+ json: (body: unknown, init?: {
1171
+ status?: number;
1172
+ }) => Response;
1173
+ requireAuth: (req: Request) => Promise<Response | null>;
1174
+ requireEntityPermission?: RequireEntityPermissionFn;
1175
+ }
1176
+ interface DashboardStatsConfig extends CmsHandlersBase {
1177
+ dataSource: DataSource;
1178
+ entityMap: EntityMap$2;
1179
+ requirePermission?: (req: Request, permission: string) => Promise<Response | null>;
1180
+ }
1181
+ declare function createDashboardStatsHandler(config: DashboardStatsConfig): (req: Request) => Promise<Response>;
1182
+ interface EcommerceAnalyticsConfig extends CmsHandlersBase {
1183
+ dataSource: DataSource;
1184
+ entityMap: EntityMap$2;
1185
+ }
1186
+ declare function createEcommerceAnalyticsHandler(config: EcommerceAnalyticsConfig): (req: Request) => Promise<Response>;
1187
+ interface VendorDashboardConfig extends CmsHandlersBase {
1188
+ dataSource: DataSource;
1189
+ entityMap: EntityMap$2;
1190
+ getSessionUser: () => Promise<SessionUser | null>;
1191
+ }
1192
+ declare function createVendorDashboardHandler(config: VendorDashboardConfig): (req: Request) => Promise<Response>;
1193
+ interface AnalyticsHandlerConfig extends CmsHandlersBase {
1194
+ getAnalyticsData?: (days: number) => Promise<unknown>;
1195
+ getPropertyId?: () => ({
1196
+ currentViewId?: string;
1197
+ [k: string]: unknown;
1198
+ });
1199
+ getPermissions?: () => ({
1200
+ serviceAccountEmail?: string;
1201
+ currentViewId?: string;
1202
+ [k: string]: unknown;
1203
+ });
989
1204
  }
1205
+ declare function createAnalyticsHandlers(config: AnalyticsHandlerConfig): {
1206
+ GET(req: Request): Promise<Response>;
1207
+ propertyId: () => Promise<Response>;
1208
+ permissions: () => Promise<Response>;
1209
+ };
990
1210
 
991
- /** Stable display name; not persisted as DB agent row in v1. */
992
- declare const BLOG_GENERATOR_AGENT_NAME = "Blog Generator Agent";
1211
+ interface UploadHandlerConfig extends CmsHandlersBase {
1212
+ /** Storage plugin instance or getter (e.g. () => getCms().then(c => c.getPlugin('storage'))). If not set, uses local fallback. */
1213
+ storage?: StorageService | (() => StorageService | undefined) | (() => Promise<StorageService | undefined>);
1214
+ /** Fallback when storage not set: dir relative to cwd (e.g. "public/uploads") */
1215
+ localUploadDir?: string;
1216
+ allowedTypes?: string[];
1217
+ maxSizeBytes?: number;
1218
+ /** Resolve folder chain for `parentId` (merged from createCmsApiHandler when omitted). */
1219
+ dataSource?: DataSource;
1220
+ entityMap?: EntityMap$2;
1221
+ }
1222
+ declare function createUploadHandler(config: UploadHandlerConfig): (req: Request) => Promise<Response>;
1223
+ /** POST /api/media/extract/:id — expand a zip media row into folders/files under the zip’s parent folder. */
1224
+ declare function createMediaZipExtractHandler(config: UploadHandlerConfig): (_req: Request, zipMediaId: string) => Promise<Response>;
1225
+ interface BlogBySlugConfig extends CmsHandlersBase {
1226
+ dataSource: DataSource;
1227
+ entityMap: EntityMap$2;
1228
+ }
1229
+ declare function createBlogBySlugHandler(config: BlogBySlugConfig): (_req: Request, slug: string) => Promise<Response>;
1230
+ interface FormBySlugConfig extends CmsHandlersBase {
1231
+ dataSource: DataSource;
1232
+ entityMap: EntityMap$2;
1233
+ }
1234
+ declare function createFormBySlugHandler(config: FormBySlugConfig): (_req: Request, slug: string) => Promise<Response>;
1235
+ interface FormSaveHandlersConfig extends CmsHandlersBase {
1236
+ dataSource: DataSource;
1237
+ entityMap: EntityMap$2;
1238
+ }
1239
+ interface FormSubmissionHandlerConfig {
1240
+ dataSource: DataSource;
1241
+ entityMap: EntityMap$2;
1242
+ json: (body: unknown, init?: {
1243
+ status?: number;
1244
+ }) => Response;
1245
+ /** When set, form submission notification email is queued (CRM recipient). */
1246
+ getCms?: () => Promise<{
1247
+ getPlugin: (name: string) => unknown;
1248
+ }>;
1249
+ getCompanyDetails?: () => Promise<CompanyDetails>;
1250
+ getRecipientForChannel?: (channel: 'crm' | 'sales' | 'fulfilment') => Promise<string | null>;
1251
+ }
1252
+ interface FormSubmissionGetByIdConfig extends CmsHandlersBase {
1253
+ dataSource: DataSource;
1254
+ entityMap: EntityMap$2;
1255
+ json: (body: unknown, init?: {
1256
+ status?: number;
1257
+ }) => Response;
1258
+ }
1259
+ interface UsersApiConfig extends CmsHandlersBase {
1260
+ dataSource: DataSource;
1261
+ entityMap: EntityMap$2;
1262
+ baseUrl: string;
1263
+ /** When set with email queue/plugin, invite emails are sent on user create and regenerate-invite. */
1264
+ getCms?: () => Promise<{
1265
+ getPlugin: (name: string) => unknown;
1266
+ }>;
1267
+ getCompanyDetails?: () => Promise<CompanyDetails>;
1268
+ /** When set, soft-delete sets `deletedBy` on the user row. */
1269
+ getSessionUser?: () => Promise<SessionUser | null>;
1270
+ }
1271
+ declare function createUsersApiHandlers(config: UsersApiConfig): {
1272
+ list(req: Request): Promise<Response>;
1273
+ create(req: Request): Promise<Response>;
1274
+ getById(_req: Request, id: string): Promise<Response>;
1275
+ update(req: Request, id: string): Promise<Response>;
1276
+ delete(_req: Request, id: string): Promise<Response>;
1277
+ regenerateInvite(_req: Request, id: string): Promise<Response>;
1278
+ };
1279
+ interface UserAvatarConfig extends CmsHandlersBase {
1280
+ getSession: () => Promise<{
1281
+ user?: {
1282
+ email?: string | null;
1283
+ };
1284
+ } | null>;
1285
+ /** Save avatar (buffer, fileName) => publicUrl. Default: local public/uploads/avatars */
1286
+ saveAvatar?: (buffer: Buffer, fileName: string) => Promise<string>;
1287
+ }
1288
+ declare function createUserAvatarHandler(config: UserAvatarConfig): (req: Request) => Promise<Response>;
1289
+ interface UserProfileConfig extends CmsHandlersBase {
1290
+ dataSource: DataSource;
1291
+ entityMap: EntityMap$2;
1292
+ getSession: () => Promise<{
1293
+ user?: {
1294
+ id?: string;
1295
+ email?: string | null;
1296
+ name?: string | null;
1297
+ };
1298
+ } | null>;
1299
+ /** Optional hook after a successful profile PUT (e.g. audit logging). */
1300
+ onProfileUpdated?: (req: Request, user: {
1301
+ id: number;
1302
+ name: string;
1303
+ email: string;
1304
+ phone: string | null;
1305
+ }) => Promise<void>;
1306
+ }
993
1307
  /**
994
- * Optional `llm_agents` row: when present and enabled, model / temperature / max_tokens
995
- * are applied to {@link LlmServiceInterface.chatAgent} (system + user content still come from blog generator defaults / UI).
1308
+ * GET / PUT handlers for `/api/users/profile` (current session user).
1309
+ * GET merges DB fields with the session; PUT updates the user row and callers should refresh the client session (e.g. `useSession().update()`).
996
1310
  */
997
- declare const BLOG_GENERATOR_LLM_AGENT_SLUG = "blog-generator";
998
- /** Line that separates multiple articles in the model reply (HTML or legacy markdown; must match parser and prompts). */
999
- declare const BLOG_GENERATOR_MARKDOWN_ARTICLE_SEPARATOR = "---BLOG_GENERATOR_NEXT---";
1000
- declare const BLOG_GENERATOR_DEFAULT_SYSTEM_INSTRUCTION = "You are a professional financial and business content writer.\n\nYour task is to generate completely original, high-quality blog article(s) from the latest RSS-derived source material in the user message (one block per feed). The user message is factual input only.\n\nIMPORTANT RULES:\n\n1. NEVER copy the RSS article directly.\n2. Rewrite the information into a fresh, human-like article.\n3. Expand the topic with professional insights and explanations.\n4. Maintain a natural editorial tone.\n5. Make the article SEO-friendly.\n6. Use engaging headings and subheadings.\n7. Avoid robotic AI phrasing.\n8. Do not mention that the content came from RSS or feeds.\n9. Preserve factual accuracy from the source material.\n10. The output should feel like a professionally written industry blog.\n\nMULTIPLE FEEDS:\n- If several feeds are provided, compare them: if they largely cover the same story or overlap heavily, produce ONE cohesive article.\n- If they cover clearly different topics or distinct stories, produce MULTIPLE articles (one per distinct story).\n- You may also produce one synthesis plus a short separate angle when that best serves the reader\u2014use your judgment.\n\nWRITING STYLE:\n- Professional\n- Clear\n- Informative\n- Business-focused\n- Human sounding\n- Modern editorial style\n\nARTICLE STRUCTURE (each article \u2014 express in HTML):\n1. Engaging introduction\n2. Industry context\n3. Main developments\n4. Key implications\n5. Expert/business analysis\n6. Conclusion\n\nHTML STRUCTURE (STRICT \u2014 each article must be valid, semantic HTML only):\n- Output HTML only. Do not use Markdown (no # headings, no **bold**, no `code fences`).\n- Wrap each complete article in a single root: <article class=\"blog-post\"> ... </article>\n- Inside <article>, use this outline:\n - <header><h1 class=\"blog-post-title\">\u2026main title\u2026</h1></header> (exactly one h1 per article)\n - <section class=\"blog-post-body\"> for all following content\n - Use <h2> and <h3> for section and subsection titles (never skip levels: h1 \u2192 h2 \u2192 h3).\n - Use <p> for paragraphs; keep paragraphs focused (avoid huge unbroken text).\n - Use <ul>/<ol> with <li> for lists where appropriate.\n - Use <strong> and <em> for emphasis sparingly; use <blockquote> only when quoting or callouts fit.\n- Do not include <html>, <head>, <body>, or document-level wrappers \u2014 only the fragment(s) described above.\n- Do not use <script>, <style>, <iframe>, or inline event handlers. Avoid inline style=\"\" except when essential for accessibility (prefer none).\n- Escape angle brackets in body text if you must mention markup; keep output safe for embedding in a CMS.\n\nCONTENT REQUIREMENTS:\n- Minimum 800 words per article unless source material is very small.\n- Add context around industry trends where appropriate.\n- Explain why the topic matters.\n- Include practical implications for businesses/professionals.\n\nIF RSS CONTENT IS LIMITED:\n- Expand intelligently using general industry knowledge.\n- Keep the article relevant to the original topic.\n- Do not invent fake facts or statistics.\n\nOUTPUT FORMAT (STRICT \u2014 HTML only):\n- Return ONLY the article HTML fragment(s). No JSON, no preamble or postscript (\"Here is your article\u2026\"), no markdown.\n- If you output more than one article, output multiple <article class=\"blog-post\">\u2026</article> blocks in sequence, and between articles put a single line containing exactly this (and nothing else on that line):\n---BLOG_GENERATOR_NEXT---\n- If you output a single article, use one <article> only and do not use that separator line.";
1311
+ declare function createUserProfileHandler(config: UserProfileConfig): {
1312
+ GET(_req: Request): Promise<Response>;
1313
+ PUT(req: Request): Promise<Response>;
1314
+ };
1315
+ interface SettingsApiConfig extends CmsHandlersBase {
1316
+ dataSource: DataSource;
1317
+ entityMap: EntityMap$2;
1318
+ encryptionKey?: string;
1319
+ /** Groups in this list are readable without auth (GET returns all keys for the group). */
1320
+ publicGetGroups?: string[];
1321
+ }
1322
+ declare function simpleEncrypt(text: string, key: string): string;
1323
+ declare function simpleDecrypt(encoded: string, key: string): string;
1001
1324
  /**
1002
- * JSON so {@link parseLlmAgentValidationRules} can attach guardrails and allow long source payloads.
1003
- * Edit in the admin UI if needed; defaults match product intent.
1325
+ * Structural types so apps with their own `typeorm` install (e.g. npm link) typecheck without duplicate-package errors.
1004
1326
  */
1005
- declare const BLOG_GENERATOR_DEFAULT_VALIDATION_RULES: string;
1327
+ type GetPublicSettingsGroupDataSource = {
1328
+ getRepository(entity: unknown): {
1329
+ find(options: object): Promise<unknown[]>;
1330
+ };
1331
+ };
1332
+ interface GetPublicSettingsGroupConfig {
1333
+ dataSource: GetPublicSettingsGroupDataSource;
1334
+ entityMap: Record<string, unknown>;
1335
+ encryptionKey?: string;
1336
+ }
1337
+ /** Same rows as unauthenticated GET /api/settings/:group when the group is in publicGetGroups. */
1338
+ declare function getPublicSettingsGroup(config: GetPublicSettingsGroupConfig, group: string): Promise<Record<string, string>>;
1339
+ declare function createSettingsApiHandlers(config: SettingsApiConfig): {
1340
+ GET(req: Request, group: string): Promise<Response>;
1341
+ PUT(req: Request, group: string): Promise<Response>;
1342
+ };
1343
+ interface ChatApiConfig extends CmsHandlersBase {
1344
+ dataSource: DataSource;
1345
+ entityMap: EntityMap$2;
1346
+ getCms: () => Promise<{
1347
+ getPlugin: (name: string) => unknown;
1348
+ }>;
1349
+ }
1350
+ /** Safe subset of `llm` settings for the storefront chat widget (`GET /api/chat/config`). */
1351
+ interface ChatPublicConfig {
1352
+ enabled: boolean;
1353
+ chatMode: 'whatsapp' | 'external' | 'llm';
1354
+ /** When `chatMode === 'llm'`, slug of the chatbot-scoped agent (`llm_agents.scope = chatbot`). */
1355
+ agentSlug: string;
1356
+ botName: string;
1357
+ icon: string;
1358
+ iconImageUrl: string;
1359
+ iconBackgroundColor: string;
1360
+ headerColor: string;
1361
+ whatsappPhone: string;
1362
+ }
1006
1363
 
1007
1364
  /**
1008
- * Second-step LLM: classifies one finished HTML blog body into CMS fields (category, SEO, tags).
1009
- *
1010
- * Optional `llm_agents` row: slug {@link BLOG_METADATA_ENRICHER_LLM_AGENT_SLUG} — when present and enabled,
1011
- * model / temperature / max_tokens apply to this call only (writer step uses `blog-generator`).
1365
+ * Admin API: attach knowledge base documents to an LLM agent, ingest text into chunks + embeddings.
1366
+ * Routes: GET/POST /api/llm_agents/:slug/knowledge, DELETE /api/llm_agents/:slug/knowledge/:documentId
1012
1367
  *
1013
- * To change how metadata is produced, edit the constants in this file (system instruction + validation JSON).
1014
- * No admin UI override is wired yet; add request body fields in `cms-api-handler` if you need runtime overrides later.
1368
+ * Pipeline logs (grep `[llm-agent-knowledge] pipeline`):
1369
+ * - 01_request incoming POST, content-type preview
1370
+ * - 02_agent_loaded — agent id for slug
1371
+ * - 03_body_parsed — JSON vs multipart, sizes / documentId
1372
+ * - 04_* — file decode or PDF extract (multipart)
1373
+ * - 05_branch — link_existing_document | new_upload_ingest
1374
+ * - 06_* — KB row + junction (link create / exists)
1375
+ * - 06b_chunks_existing_count — link path: existing chunk rows
1376
+ * - 06_knowledge_document_saved — new ingest: document row id
1377
+ * - 07_chunk_split — split stats
1378
+ * - 07b_chunks_persisted — chunk rows saved
1379
+ * - 07_query_chunks_missing_embedding — link path: rows with NULL embedding
1380
+ * - 08_* — resolve LLM plugin, embed availability or skip
1381
+ * - 09_embedding_workers_start / 10_embedding_workers_finished — concurrent embed+DB update
1382
+ * - 11_response — final outcome summary
1383
+ * - 99_pipeline_error — uncaught exception
1015
1384
  */
1016
- declare const BLOG_METADATA_ENRICHER_AGENT_NAME = "Blog Generator Metadata";
1017
- /** `llm_agents.slug` for routing model/temperature for the metadata-only chat step. */
1018
- declare const BLOG_METADATA_ENRICHER_LLM_AGENT_SLUG = "blog-generator-metadata";
1019
- declare const BLOG_METADATA_ENRICHER_DEFAULT_SYSTEM_INSTRUCTION = "You are a careful CMS metadata assistant for a publishing system.\n\nYou receive ONE complete blog post as HTML (title is usually in <h1 class=\"blog-post-title\"> or the first <h1>). Your job is to propose structured fields so an editor can save the post: category, URL slug, SEO block, and topical tags.\n\nRULES:\n1. Read the whole article and infer the primary topic and audience.\n2. categoryName must be EXACTLY one string from AVAILABLE_BLOG_CATEGORIES in the user message, or \"\" if none fit.\n3. blogSlug: lowercase kebab-case, ASCII letters/digits/hyphens only, no leading/trailing hyphens, max ~80 chars. Derive from the main topic or title.\n4. seo.title: concise meta title (~50\u201360 characters when reasonable).\n5. seo.description: meta description (~150\u2013160 characters when reasonable), plain text.\n6. seo.keywords: comma-separated phrases, no stuffing.\n7. seo.ogTitle / seo.ogDescription: may mirror title/description or be slightly adapted for social.\n8. tags: 4\u201310 short labels (1\u20133 words each). Prefer exact matches from EXISTING_TAG_NAMES when they truly apply; otherwise invent precise new labels (they may be created in the CMS later).\n9. Do not invent statistics, quotes, or URLs not implied by the article.\n10. Output JSON only \u2014 no markdown outside the JSON, no commentary.\n\nOUTPUT FORMAT (STRICT):\nReturn a single JSON object only. Do not wrap it in a markdown code fence.\n\n{\n \"categoryName\": \"string \u2014 exact match from list or empty string\",\n \"blogSlug\": \"string \u2014 url-safe kebab-case\",\n \"seo\": {\n \"title\": \"string or empty\",\n \"description\": \"string or empty\",\n \"keywords\": \"string or empty\",\n \"ogTitle\": \"string or empty\",\n \"ogDescription\": \"string or empty\"\n },\n \"tags\": [\"tag-one\", \"tag-two\"]\n}";
1020
- declare const BLOG_METADATA_ENRICHER_DEFAULT_VALIDATION_RULES: string;
1021
1385
 
1022
- interface BlogGeneratorPluginConfig {
1023
- /** Set to false to skip registering the plugin. */
1024
- enabled?: boolean;
1386
+ interface LlmAgentKnowledgeApiConfig {
1387
+ dataSource: DataSource;
1388
+ entityMap: EntityMap$2;
1389
+ getCms: () => Promise<{
1390
+ getPlugin: (name: string) => unknown;
1391
+ }>;
1392
+ json: (body: unknown, init?: {
1393
+ status?: number;
1394
+ }) => Response;
1395
+ requireAuth: (req: Request) => Promise<Response | null>;
1396
+ requireEntityPermission?: RequireEntityPermissionFn;
1025
1397
  }
1026
- declare function blogGeneratorPlugin(config?: BlogGeneratorPluginConfig): CmsPlugin<BlogGeneratorService | undefined>;
1398
+ declare function createLlmAgentKnowledgeHandlers(config: LlmAgentKnowledgeApiConfig): {
1399
+ list(req: Request, slug: string): Promise<Response>;
1400
+ post(req: Request, slug: string): Promise<Response>;
1401
+ unlink(req: Request, slug: string, documentIdStr: string): Promise<Response>;
1402
+ } | null;
1027
1403
 
1028
- interface SocialMediaApiConfig {
1404
+ /**
1405
+ * Single CMS API handler: dashboard, analytics, upload, media zip extract, blog/form by slug, users API, user auth, CRUD. Mount once (e.g. app/api/[[...path]]/route.ts).
1406
+ */
1407
+
1408
+ /** CMS instance with getPlugin; when provided, analytics and userAuth.sendEmail can be resolved from plugins when not passed. */
1409
+ type CmsGetter = () => Promise<{
1410
+ getPlugin: (name: string) => unknown;
1411
+ }>;
1412
+ interface CmsApiHandlerConfig {
1029
1413
  dataSource: DataSource;
1030
1414
  entityMap: EntityMap$2;
1415
+ requireAuth: (req: Request) => Promise<Response | null>;
1031
1416
  json: (body: unknown, init?: {
1032
1417
  status?: number;
1033
1418
  }) => Response;
1034
- requireAuth: (req: Request) => Promise<Response | null>;
1035
- requireEntityPermission: (req: Request, entity: string, action: EntityCrudAction) => Promise<Response | null>;
1036
- encryptionKey?: string;
1037
- /** Used to resolve relative cover image URLs (e.g. https://mysite.com). */
1038
- publicSiteUrl?: string;
1419
+ pathToModel?: (segment: string) => string;
1420
+ crudResources?: string[];
1421
+ /** When set, analytics and userAuth.sendEmail can be derived from getPlugin('analytics') and getPlugin('email') when not provided. */
1422
+ getCms?: CmsGetter;
1423
+ /** Optional: used when deriving userAuth.sendEmail to pass company details into email templates (e.g. from settings). */
1424
+ getCompanyDetails?: () => Promise<CompanyDetails>;
1425
+ /** Optional: used for form submission and other channel-based email recipients (from settings group "email"). */
1426
+ getRecipientForChannel?: (channel: 'crm' | 'sales' | 'fulfilment') => Promise<string | null>;
1427
+ userAuth?: UserAuthApiConfig;
1428
+ /** GET /api/dashboard/stats */
1429
+ dashboard?: DashboardStatsConfig;
1430
+ /** GET /api/dashboard/ecommerce */
1431
+ ecommerceAnalytics?: EcommerceAnalyticsConfig;
1432
+ /** GET /api/analytics. If omitted and getCms is set, uses getCms().getPlugin('analytics'). */
1433
+ analytics?: AnalyticsHandlerConfig;
1434
+ /** POST /api/upload (S3 or local) */
1435
+ upload?: UploadHandlerConfig;
1436
+ /** GET /api/blogs/slug/:slug (public) */
1437
+ blogBySlug?: BlogBySlugConfig;
1438
+ /** GET /api/forms/slug/:slug (public) */
1439
+ formBySlug?: FormBySlugConfig;
1440
+ /** POST/PUT /api/forms (save form + fields; when set, overrides CRUD for forms) */
1441
+ formSave?: FormSaveHandlersConfig;
1442
+ /** POST /api/form-submissions (public, no auth) */
1443
+ formSubmission?: FormSubmissionHandlerConfig;
1444
+ /** GET /api/form-submissions/:id (auth) with form + contact relations */
1445
+ formSubmissionGetById?: FormSubmissionGetByIdConfig;
1446
+ /** GET/POST /api/users, GET/PUT/DELETE /api/users/:id, POST /api/users/:id/regenerate-invite */
1447
+ usersApi?: UsersApiConfig;
1448
+ /** POST /api/users/avatar */
1449
+ userAvatar?: UserAvatarConfig;
1450
+ /** GET/PUT /api/users/profile (current session user) */
1451
+ userProfile?: UserProfileConfig;
1452
+ /** GET/PUT /api/settings/:group */
1453
+ settings?: SettingsApiConfig;
1454
+ /** GET /api/chat/config (public); POST /api/chat/identify; GET /api/chat/conversations/:id/messages; POST /api/chat/messages */
1455
+ chat?: ChatApiConfig;
1039
1456
  /**
1040
- * When true (default), `console.info` / `console.warn` lines are emitted for LinkedIn blog publish
1041
- * (text vs image path, sizes, errors). Set false or `CMS_LINKEDIN_PUBLISH_LOG=0` to silence.
1457
+ * GET/POST /api/llm_agents/:slug/knowledge; DELETE …/knowledge/:documentId agent KB ingest + links.
1458
+ * When omitted but `chat` is set, the same dataSource / entityMap / getCms / json / requireAuth are reused automatically.
1042
1459
  */
1043
- linkedInPublishLogging?: boolean;
1044
- }
1045
- declare function createSocialMediaHandlers(config: SocialMediaApiConfig): {
1046
- getLinkedInStatus(req: Request): Promise<Response>;
1047
- fetchLinkedInOrganizations(req: Request): Promise<Response>;
1048
- syncLinkedInProfile(req: Request): Promise<Response>;
1049
- publishBlogToLinkedIn(req: Request, blogId: number): Promise<Response>;
1050
- getFacebookStatus(req: Request): Promise<Response>;
1051
- publishBlogToFacebook(req: Request, blogId: number): Promise<Response>;
1460
+ llmAgentKnowledge?: LlmAgentKnowledgeApiConfig;
1052
1461
  /**
1053
- * POST JSON `{ appId, appSecret, userAccessToken }`. Calls Graph `GET /me/accounts` with the user token.
1054
- * App ID and secret are validated but not used yet (reserved for future token flows).
1055
- * Persist credentials via Plugins → Save: `meta_app_id` (public), `meta_app_secret` and `meta_user_access_token` (encrypted).
1462
+ * Entity-level RBAC (session `entityPerms` / Administrator). When omitted, admin routes that need it respond with 403
1463
+ * (`entity_rbac_required`) so CRUD cannot run as auth-only. Pass `createAuthHelpers(...).requireEntityPermission` from the app.
1056
1464
  */
1057
- fetchFacebookManagedPages(req: Request): Promise<Response>;
1465
+ requireEntityPermission?: (req: Request, entity: string, action: EntityCrudAction) => Promise<Response | null>;
1466
+ /** Required for vendor store RBAC + scoping. Alias: `getAuthenticatedUser`. */
1467
+ getSessionUser?: () => Promise<SessionUser | null>;
1468
+ /** Same as `getSessionUser` (from `createAuthHelpers().getAuthenticatedUser`). */
1469
+ getAuthenticatedUser?: () => Promise<SessionUser | null>;
1470
+ }
1471
+ declare function createCmsApiHandler(config: CmsApiHandlerConfig): {
1472
+ handle(method: string, pathInput: string[], req: Request): Promise<Response>;
1058
1473
  };
1059
1474
 
1060
- /**
1061
- * Meta (Facebook) Graph API helpers (server-side). Uses fetch — no SDK.
1062
- * @see https://developers.facebook.com/docs/graph-api/reference/user/accounts
1063
- */
1064
- type FacebookPageAccount = {
1065
- access_token?: string;
1066
- category?: string;
1067
- name?: string;
1068
- id?: string;
1069
- /** Graph may return additional fields */
1070
- [key: string]: unknown;
1071
- };
1072
- type FacebookMeAccountsResponse = {
1073
- data?: FacebookPageAccount[];
1074
- paging?: Record<string, unknown>;
1075
- error?: {
1076
- message?: string;
1077
- type?: string;
1078
- code?: number;
1079
- fbtrace_id?: string;
1080
- };
1081
- };
1082
- /**
1083
- * Lists Facebook Pages the user manages (page access tokens + metadata).
1084
- * Requires a User access token with `pages_show_list` or equivalent page permissions.
1085
- */
1086
- declare function metaFetchUserManagedPages(userAccessToken: string): Promise<FacebookMeAccountsResponse>;
1087
- type MetaGraphMutationResponse = {
1088
- id?: string;
1089
- post_id?: string;
1090
- error?: {
1091
- message?: string;
1092
- type?: string;
1093
- code?: number;
1094
- fbtrace_id?: string;
1095
- };
1475
+ interface JobScheduleApiConfig {
1476
+ dataSource: DataSource;
1477
+ entityMap: EntityMap$2;
1478
+ json: (body: unknown, init?: ResponseInit) => Response;
1479
+ requireAuth: (req: Request) => Promise<Response | null>;
1480
+ requireEntityPermission?: (req: Request, entity: string, action: 'read' | 'create' | 'update' | 'delete') => Promise<Response | null>;
1481
+ getCms?: CmsGetter;
1482
+ config?: Record<string, string>;
1483
+ }
1484
+ declare function createJobScheduleHandlers(apiConfig: JobScheduleApiConfig): {
1485
+ list(req: Request): Promise<Response>;
1486
+ getById(req: Request, id: string): Promise<Response>;
1487
+ create(req: Request): Promise<Response>;
1488
+ update(req: Request, id: string): Promise<Response>;
1489
+ remove(req: Request, id: string): Promise<Response>;
1490
+ runNow(req: Request, id: string): Promise<Response>;
1491
+ listRuns(req: Request, id: string): Promise<Response>;
1096
1492
  };
1097
- /** Resolves the long-lived page access token for a Page ID from `/me/accounts` data. */
1098
- declare function metaResolvePageAccessToken(accounts: FacebookMeAccountsResponse, pageId: string): string | null;
1099
- /**
1100
- * Upload a photo to a Page timeline (multipart).
1101
- * @see https://developers.facebook.com/docs/graph-api/reference/page/photos#Creating
1102
- */
1103
- declare function metaPostPagePhoto(opts: {
1104
- pageId: string;
1105
- pageAccessToken: string;
1106
- imageBuffer: Buffer;
1107
- contentType: string;
1108
- caption: string;
1109
- }): Promise<MetaGraphMutationResponse>;
1110
- /**
1111
- * Publish a text-only post to the Page feed (when no JPEG/PNG image is available).
1112
- * @see https://developers.facebook.com/docs/graph-api/reference/page/feed#Creating
1113
- */
1114
- declare function metaPostPageFeed(opts: {
1115
- pageId: string;
1116
- pageAccessToken: string;
1117
- message: string;
1118
- }): Promise<MetaGraphMutationResponse>;
1119
1493
 
1120
- interface SocialMediaPluginConfig {
1121
- /** Set to false to skip registering the plugin instance (API routes still work if wired in the app handler). */
1122
- enabled?: boolean;
1494
+ interface EventOrderMessageTemplateHandlersConfig {
1495
+ dataSource: DataSource;
1496
+ entityMap: EntityMap$2;
1497
+ json: (body: unknown, init?: {
1498
+ status?: number;
1499
+ }) => Response;
1500
+ requireAuth: (req: Request) => Promise<Response | null>;
1501
+ requireEntityPermission?: RequireEntityPermissionFn;
1123
1502
  }
1124
- /**
1125
- * Optional CMS plugin instance for `getPlugin('social_media')`.
1126
- * LinkedIn publishing is implemented in {@link createSocialMediaHandlers} and mounted from the CMS API handler.
1127
- */
1128
- declare function socialMediaPlugin(config?: SocialMediaPluginConfig): CmsPlugin<{
1129
- name: string;
1130
- } | undefined>;
1503
+ declare function createEventOrderMessageTemplateHandlers(config: EventOrderMessageTemplateHandlersConfig): {
1504
+ GET(req: Request): Promise<Response>;
1505
+ PUT(req: Request): Promise<Response>;
1506
+ };
1131
1507
 
1132
1508
  declare function cn(...inputs: ClassValue[]): string;
1133
1509
  declare function generateSlug(title: string): string;
@@ -1176,6 +1552,24 @@ declare function resolvePublicMetadata(args: {
1176
1552
  /** Links an unclaimed contact (same email, no userId) to the new user after signup or invite. */
1177
1553
  declare function linkUnclaimedContactToUser(dataSource: DataSource, contactsEntity: EntityTarget<ObjectLiteral>, userId: number, email: string): Promise<void>;
1178
1554
 
1555
+ type EnsureCustomerUserInput = {
1556
+ id: number;
1557
+ name: string;
1558
+ email: string;
1559
+ phone?: string | null;
1560
+ };
1561
+ /** Stable unique placeholder when no phone is available (customer.phone is NOT NULL + UNIQUE). */
1562
+ declare function customerPhoneForUser(userId: number, phone?: string | null): string;
1563
+ /**
1564
+ * Ensures a `customer` row exists for the given user (idempotent by userId / email).
1565
+ * Returns null when customer entity is missing or email belongs to another user.
1566
+ */
1567
+ declare function ensureCustomerForUser(dsOrEm: DataSource | EntityManager, customerEntity: EntityTarget<ObjectLiteral>, user: EnsureCustomerUserInput, overrides?: {
1568
+ phone?: string | null;
1569
+ }): Promise<{
1570
+ id: number;
1571
+ } | null>;
1572
+
1179
1573
  /** Parse stored config value into a list of emails (JSON array, or comma/semicolon-separated string). */
1180
1574
  declare function parseEmailRecipientsFromConfig(raw: string | undefined | null): string[];
1181
1575
  /** Serialize email list for config storage (JSON array in DB). */
@@ -1242,79 +1636,6 @@ interface SendOrderPlacedEmailDeps {
1242
1636
  /** After payment confirmation: email customer + each sales team address from plugin settings. */
1243
1637
  declare function sendOrderPlacedEmailsAfterConfirmation(orderId: number, deps: SendOrderPlacedEmailDeps): Promise<void>;
1244
1638
 
1245
- type VendorOnboardedActivation = 'invite' | 'password';
1246
- type VendorOnboardedKind = 'vendor_onboard' | 'team_invite';
1247
-
1248
- interface EntityMapLike {
1249
- configs: unknown;
1250
- }
1251
- interface SendVendorOnboardEmailInput {
1252
- vendorName: string;
1253
- vendorSlug?: string;
1254
- ownerName: string;
1255
- ownerEmail: string;
1256
- activation: VendorOnboardedActivation;
1257
- inviteLink?: string;
1258
- signInLink: string;
1259
- kind?: VendorOnboardedKind;
1260
- /** When false, skips owner email but still notifies internal recipients. Default true. */
1261
- sendToOwner?: boolean;
1262
- }
1263
- interface SendVendorOnboardEmailDeps {
1264
- getDataSource: () => Promise<DataSource>;
1265
- entityMap: EntityMapLike;
1266
- getCms: () => Promise<CmsAppLike$2>;
1267
- }
1268
- /** After vendor onboard / team invite: email owner + platform team from plugin settings. */
1269
- declare function sendVendorOnboardEmails(input: SendVendorOnboardEmailInput, deps: SendVendorOnboardEmailDeps): Promise<{
1270
- ownerEmailSent: boolean;
1271
- }>;
1272
-
1273
- interface DataSourceManager {
1274
- getDataSource: () => DataSource;
1275
- getDataSourceInitialized: () => Promise<DataSource>;
1276
- resetDataSource: () => void;
1277
- registerOnReset: (cb: () => void) => void;
1278
- isConnectionError: (e: unknown) => boolean;
1279
- }
1280
- declare function createDataSourceManager(entityMap: Record<string, unknown>, options?: {
1281
- databaseUrl?: string;
1282
- idleTimeoutMillis?: number;
1283
- }): DataSourceManager;
1284
-
1285
- interface SeedEntityMap {
1286
- users: unknown;
1287
- user_groups: unknown;
1288
- }
1289
- declare function seedDefaultAdmin(ds: DataSource, entityMap: SeedEntityMap, opts?: {
1290
- email?: string;
1291
- password?: string;
1292
- }): Promise<void>;
1293
-
1294
- type VendorInviteStatus = 'none' | 'pending' | 'expired' | 'accepted';
1295
- declare class Vendor {
1296
- id: number;
1297
- name: string;
1298
- slug: string;
1299
- email: string | null;
1300
- phone: string | null;
1301
- logo: string | null;
1302
- description: string | null;
1303
- metadata: Record<string, unknown> | null;
1304
- active: boolean;
1305
- /** Primary owner user for this vendor (set on onboard). */
1306
- userId: number | null;
1307
- inviteStatus: VendorInviteStatus;
1308
- createdAt: Date;
1309
- updatedAt: Date;
1310
- deletedAt: Date | null;
1311
- deleted: boolean;
1312
- createdBy: number | null;
1313
- updatedBy: number | null;
1314
- deletedBy: number | null;
1315
- vendorUsers: VendorUser[];
1316
- }
1317
-
1318
1639
  declare class Permission {
1319
1640
  id: number;
1320
1641
  groupId: number;
@@ -1369,117 +1690,138 @@ declare class User {
1369
1690
  group: UserGroup | null;
1370
1691
  }
1371
1692
 
1693
+ declare class VendorRolePermission {
1694
+ id: number;
1695
+ vendorRoleId: number;
1696
+ entity: string;
1697
+ canCreate: boolean;
1698
+ canRead: boolean;
1699
+ canUpdate: boolean;
1700
+ canDelete: boolean;
1701
+ createdAt: Date;
1702
+ updatedAt: Date;
1703
+ role: VendorRole;
1704
+ }
1705
+
1706
+ declare class VendorRole {
1707
+ id: number;
1708
+ vendorId: number;
1709
+ name: string;
1710
+ description: string | null;
1711
+ isSystem: boolean;
1712
+ isOwnerRole: boolean;
1713
+ createdAt: Date;
1714
+ updatedAt: Date;
1715
+ deletedAt: Date | null;
1716
+ deleted: boolean;
1717
+ vendor: Vendor;
1718
+ permissions: VendorRolePermission[];
1719
+ }
1720
+
1372
1721
  /** Links a staff user to a vendor store. */
1373
1722
  type VendorUserRole = 'owner' | 'staff';
1374
1723
  declare class VendorUser {
1375
1724
  id: number;
1376
1725
  vendorId: number;
1377
1726
  userId: number;
1727
+ /** @deprecated use vendorRoleId — kept for migration compatibility */
1378
1728
  role: VendorUserRole;
1729
+ vendorRoleId: number | null;
1379
1730
  createdAt: Date;
1380
1731
  updatedAt: Date;
1381
1732
  vendor: Vendor;
1382
1733
  user: User;
1734
+ vendorRole: VendorRole | null;
1383
1735
  }
1384
1736
 
1385
- /** Load vendor membership for session (call from app `getUserByEmail`).
1386
- *
1387
- * Uses a raw SQL query so it works even when the consuming app's DataSource
1388
- * does not explicitly register the VendorUser entity.
1389
- */
1390
- declare function loadUserVendorContext(dataSource: DataSource, userId: number, preferredVendorId?: number | null): Promise<{
1391
- vendorIds: number[];
1392
- activeVendorId: number | null;
1393
- vendorRole: VendorUserRole | null;
1394
- }>;
1395
-
1396
- /** Attach vendorIds / activeVendorId / vendorRole for NextAuth (use in app getUserByEmail). */
1397
- declare function enrichUserWithVendorContext(dataSource: DataSource, user: NextAuthUser | null): Promise<NextAuthUser | null>;
1398
-
1399
- /** Merge DB group + vendor_users into session (JWT often missing these). Server/API only. */
1400
- declare function hydrateVendorSessionUser(dataSource: DataSource, user: SessionUser | null | undefined): Promise<SessionUser | null | undefined>;
1401
-
1402
- interface PublicThemeSettingsPayload {
1403
- activeThemeId: string;
1404
- primaryColor: string;
1405
- secondaryColor: string;
1406
- navbarConfig: NavbarConfig;
1407
- footerOverrides: Partial<FooterConfig>;
1737
+ type VendorInviteStatus = 'none' | 'pending' | 'expired' | 'accepted';
1738
+ type VendorRegistrationStatus = 'pending' | 'approved' | 'rejected' | 'suspended';
1739
+ declare class Vendor {
1740
+ id: number;
1741
+ name: string;
1742
+ slug: string;
1743
+ email: string | null;
1744
+ phone: string | null;
1745
+ legalName: string | null;
1746
+ businessType: string | null;
1747
+ website: string | null;
1748
+ addressLine1: string | null;
1749
+ addressLine2: string | null;
1750
+ city: string | null;
1751
+ state: string | null;
1752
+ country: string | null;
1753
+ postalCode: string | null;
1754
+ gstin: string | null;
1755
+ pan: string | null;
1756
+ logo: string | null;
1757
+ description: string | null;
1758
+ metadata: Record<string, unknown> | null;
1759
+ active: boolean;
1760
+ /** Primary owner user for this vendor (set on onboard). */
1761
+ userId: number | null;
1762
+ inviteStatus: VendorInviteStatus;
1763
+ registrationStatus: VendorRegistrationStatus;
1764
+ createdAt: Date;
1765
+ updatedAt: Date;
1766
+ deletedAt: Date | null;
1767
+ deleted: boolean;
1768
+ createdBy: number | null;
1769
+ updatedBy: number | null;
1770
+ deletedBy: number | null;
1771
+ vendorUsers: VendorUser[];
1408
1772
  }
1409
- declare function loadPublicThemeSettings(config: {
1410
- dataSource: DataSource;
1411
- entityMap: EntityMap$2;
1412
- encryptionKey?: string;
1413
- defaultActiveThemeId?: string;
1414
- defaultPrimaryColor?: string;
1415
- defaultSecondaryColor?: string;
1416
- }): Promise<PublicThemeSettingsPayload>;
1417
-
1418
- /** Normalize a logical media folder path: no leading/trailing slashes, no ".." segments, max length. */
1419
- declare function sanitizeMediaFolderPath(input: unknown): string;
1420
- /** Single path segment for storage (folder name or legacy path segment). */
1421
- declare function sanitizeStorageSegment(name: string): string;
1422
-
1423
- type EntityMap = Record<string, EntityTarget<ObjectLiteral>>;
1424
- /** Build `a/b/c` path under `uploads/` from the chain of folder rows up to root. */
1425
- declare function relativePathFromMediaParentId(dataSource: DataSource, entityMap: EntityMap, parentId: number | null): Promise<string>;
1426
-
1427
- declare const ZIP_MIME_TYPES: Set<string>;
1428
- declare function isZipMedia(mime: string | null | undefined, filename: string): boolean;
1429
-
1430
- /**
1431
- * Executes `fn` inside a transaction where the PostgreSQL GUC
1432
- * `app.vendor_id` is set for the duration of that transaction.
1433
- *
1434
- * This activates the `vendor_isolation` RLS policy added by the
1435
- * `VendorRls1775940000000` migration.
1436
- *
1437
- * vendorId = 0 → admin / all-access (policy allows everything)
1438
- * vendorId > 0 → only rows whose `vendorId` column matches
1439
- *
1440
- * Example:
1441
- * const orders = await withVendorRlsContext(dataSource, 4, (ds) =>
1442
- * ds.getRepository(Order).find({ where: { deleted: false } })
1443
- * );
1444
- */
1445
- declare function withVendorRlsContext<T>(dataSource: DataSource, vendorId: number, fn: (dataSource: DataSource) => Promise<T>): Promise<T>;
1446
- /**
1447
- * Convenience wrapper: sets admin mode (vendor_id = '0') so all rows are
1448
- * visible regardless of their vendorId. Use for platform-admin queries.
1449
- */
1450
- declare function withAdminRlsContext<T>(dataSource: DataSource, fn: (dataSource: DataSource) => Promise<T>): Promise<T>;
1451
-
1452
- declare function isCustomerTypeContact(type: unknown): boolean;
1453
- /** Restrict contact list to rows linked in `vendor_customers` with type customer. */
1454
- declare function applyVendorCustomersContactFilter(qb: SelectQueryBuilder<typeorm.ObjectLiteral>, contactAlias: string, scope: VendorScope, vendorIdFilter: number | null): void;
1455
- declare function contactIsVendorCustomer(dataSource: DataSource, entityMap: EntityMap$2, vendorId: number, contactId: number): Promise<boolean>;
1456
- /** Returns an error message when the contact is not a vendor-linked customer; otherwise null. */
1457
- declare function assertContactAllowedForVendorOrder(dataSource: DataSource, entityMap: EntityMap$2, vendorId: number, contactId: number): Promise<string | null>;
1458
- declare function resolveVendorIdForContactCheck(scope: VendorScope, bodyOrRow: Record<string, unknown>): number | null;
1459
1773
 
1460
- declare class OtpChallenge {
1774
+ declare class FormField {
1461
1775
  id: number;
1462
- purpose: string;
1463
- channel: string;
1464
- identifier: string;
1465
- codeHash: string;
1466
- expiresAt: Date;
1467
- attempts: number;
1468
- consumedAt: Date | null;
1776
+ formId: number;
1777
+ label: string;
1778
+ type: string;
1779
+ placeholder: string | null;
1780
+ options: string | null;
1781
+ required: boolean;
1782
+ validation: string | null;
1783
+ order: number;
1784
+ groupId: number;
1785
+ columnWidth: number;
1469
1786
  createdAt: Date;
1787
+ updatedAt: Date;
1788
+ deletedAt: Date | null;
1789
+ deleted: boolean;
1790
+ createdBy: number | null;
1791
+ updatedBy: number | null;
1792
+ deletedBy: number | null;
1793
+ form: Form;
1470
1794
  }
1471
1795
 
1472
- declare class PasswordResetToken {
1796
+ declare class Address {
1473
1797
  id: number;
1474
- email: string;
1475
- token: string;
1476
- expiresAt: Date;
1798
+ contactId: number;
1799
+ tag: string | null;
1800
+ line1: string | null;
1801
+ line2: string | null;
1802
+ city: string | null;
1803
+ state: string | null;
1804
+ postalCode: string | null;
1805
+ country: string | null;
1477
1806
  createdAt: Date;
1807
+ updatedAt: Date;
1808
+ contact: Contact;
1478
1809
  }
1479
1810
 
1480
- declare class Category {
1811
+ declare class ProductCategory {
1481
1812
  id: number;
1813
+ /** Null for platform catalog categories (`isCatalog`). */
1814
+ vendorId: number | null;
1815
+ /** Platform-wide catalog type — all vendors add collections/products under these categories. */
1816
+ isCatalog: boolean;
1482
1817
  name: string;
1818
+ slug: string;
1819
+ parentId: number | null;
1820
+ image: string | null;
1821
+ description: string | null;
1822
+ metadata: Record<string, unknown> | null;
1823
+ active: boolean;
1824
+ sortOrder: number;
1483
1825
  createdAt: Date;
1484
1826
  updatedAt: Date;
1485
1827
  deletedAt: Date | null;
@@ -1487,18 +1829,16 @@ declare class Category {
1487
1829
  createdBy: number | null;
1488
1830
  updatedBy: number | null;
1489
1831
  deletedBy: number | null;
1490
- blogs: Blog[];
1832
+ vendor: Vendor | null;
1833
+ parent: ProductCategory | null;
1834
+ children: ProductCategory[];
1835
+ products: Product[];
1836
+ collections: Collection[];
1491
1837
  }
1492
1838
 
1493
- declare class Seo {
1839
+ declare class Category {
1494
1840
  id: number;
1495
- title: string | null;
1496
- description: string | null;
1497
- keywords: string | null;
1498
- ogTitle: string | null;
1499
- ogDescription: string | null;
1500
- ogImage: string | null;
1501
- slug: string;
1841
+ name: string;
1502
1842
  createdAt: Date;
1503
1843
  updatedAt: Date;
1504
1844
  deletedAt: Date | null;
@@ -1564,85 +1904,15 @@ declare class Blog {
1564
1904
  tags: Tag[];
1565
1905
  }
1566
1906
 
1567
- declare class FormField {
1907
+ declare class Seo {
1568
1908
  id: number;
1569
- formId: number;
1570
- label: string;
1571
- type: string;
1572
- placeholder: string | null;
1573
- options: string | null;
1574
- required: boolean;
1575
- validation: string | null;
1576
- order: number;
1577
- groupId: number;
1578
- columnWidth: number;
1579
- createdAt: Date;
1580
- updatedAt: Date;
1581
- deletedAt: Date | null;
1582
- deleted: boolean;
1583
- createdBy: number | null;
1584
- updatedBy: number | null;
1585
- deletedBy: number | null;
1586
- form: Form;
1587
- }
1588
-
1589
- declare class Form {
1590
- id: number;
1591
- name: string;
1909
+ title: string | null;
1592
1910
  description: string | null;
1593
- campaign: string | null;
1594
- slug: string;
1595
- published: boolean;
1596
- createdAt: Date;
1597
- updatedAt: Date;
1598
- deletedAt: Date | null;
1599
- deleted: boolean;
1600
- createdBy: number | null;
1601
- updatedBy: number | null;
1602
- deletedBy: number | null;
1603
- fields: FormField[];
1604
- submissions: FormSubmission[];
1605
- }
1606
-
1607
- declare class FormSubmission {
1608
- id: number;
1609
- formId: number;
1610
- contactId: number | null;
1611
- data: Record<string, unknown>;
1612
- ipAddress: string | null;
1613
- userAgent: string | null;
1614
- createdAt: Date;
1615
- updatedAt: Date;
1616
- form: Form;
1617
- contact: Contact | null;
1618
- }
1619
-
1620
- declare class Address {
1621
- id: number;
1622
- contactId: number;
1623
- tag: string | null;
1624
- line1: string | null;
1625
- line2: string | null;
1626
- city: string | null;
1627
- state: string | null;
1628
- postalCode: string | null;
1629
- country: string | null;
1630
- createdAt: Date;
1631
- updatedAt: Date;
1632
- contact: Contact;
1633
- }
1634
-
1635
- declare class ProductCategory {
1636
- id: number;
1637
- vendorId: number;
1638
- name: string;
1911
+ keywords: string | null;
1912
+ ogTitle: string | null;
1913
+ ogDescription: string | null;
1914
+ ogImage: string | null;
1639
1915
  slug: string;
1640
- parentId: number | null;
1641
- image: string | null;
1642
- description: string | null;
1643
- metadata: Record<string, unknown> | null;
1644
- active: boolean;
1645
- sortOrder: number;
1646
1916
  createdAt: Date;
1647
1917
  updatedAt: Date;
1648
1918
  deletedAt: Date | null;
@@ -1650,11 +1920,7 @@ declare class ProductCategory {
1650
1920
  createdBy: number | null;
1651
1921
  updatedBy: number | null;
1652
1922
  deletedBy: number | null;
1653
- vendor: Vendor;
1654
- parent: ProductCategory | null;
1655
- children: ProductCategory[];
1656
- products: Product[];
1657
- collections: Collection[];
1923
+ blogs: Blog[];
1658
1924
  }
1659
1925
 
1660
1926
  declare class Brand {
@@ -1683,7 +1949,8 @@ declare class Brand {
1683
1949
 
1684
1950
  declare class Collection {
1685
1951
  id: number;
1686
- vendorId: number;
1952
+ /** Null for platform catalog collections (`isCatalog`). */
1953
+ vendorId: number | null;
1687
1954
  categoryId: number | null;
1688
1955
  brandId: number | null;
1689
1956
  name: string;
@@ -1694,6 +1961,8 @@ declare class Collection {
1694
1961
  metadata: Record<string, unknown> | null;
1695
1962
  variants: Array<Record<string, unknown>> | null;
1696
1963
  active: boolean;
1964
+ /** Platform-wide catalog type — all vendors add products under these collections. */
1965
+ isCatalog: boolean;
1697
1966
  sortOrder: number;
1698
1967
  createdAt: Date;
1699
1968
  updatedAt: Date;
@@ -1703,7 +1972,7 @@ declare class Collection {
1703
1972
  updatedBy: number | null;
1704
1973
  deletedBy: number | null;
1705
1974
  seoId: number | null;
1706
- vendor: Vendor;
1975
+ vendor: Vendor | null;
1707
1976
  seo: Seo | null;
1708
1977
  category: ProductCategory | null;
1709
1978
  brand: Brand | null;
@@ -1762,15 +2031,64 @@ declare class Tax {
1762
2031
  vendor: Vendor;
1763
2032
  }
1764
2033
 
1765
- declare class ProductTax {
2034
+ declare enum RefundPolicyStatus {
2035
+ ACTIVE = "active",
2036
+ INACTIVE = "inactive"
2037
+ }
2038
+ declare enum RefundPolicyType$1 {
2039
+ PERCENTAGE = "percentage",
2040
+ EVENT_TIERS = "event_tiers"
2041
+ }
2042
+ type RefundPolicyTierRow = {
2043
+ fromDaysBefore: number;
2044
+ toDaysBefore: number | null;
2045
+ percentage: number;
2046
+ };
2047
+ declare class RefundPolicy {
2048
+ id: number;
2049
+ name: string;
2050
+ desc?: string;
2051
+ vendorId: number;
2052
+ vendor: Vendor;
2053
+ refundWindowDays: number;
2054
+ status: RefundPolicyStatus;
2055
+ type: RefundPolicyType$1;
2056
+ value: number;
2057
+ /** Day bands before event start → refund % (when type is event_tiers). */
2058
+ tiers?: RefundPolicyTierRow[] | null;
2059
+ productConfigs: ProductConfig[];
2060
+ }
2061
+
2062
+ declare class ProductConfig {
1766
2063
  id: number;
1767
2064
  productId: number;
1768
2065
  taxId: number;
2066
+ refundPolicyId: number | null;
1769
2067
  rate: number | null;
1770
2068
  createdAt: Date;
1771
2069
  updatedAt: Date;
1772
2070
  product: Product;
1773
2071
  tax: Tax;
2072
+ refundPolicy: RefundPolicy | null;
2073
+ }
2074
+
2075
+ type ProductVariantStatus = 'draft' | 'available' | 'reserved' | 'sold';
2076
+ /** Option dimensions (Color, Size, …) plus optional `image_url` for PDP image switching. */
2077
+ type ProductVariantAttributes = Record<string, string>;
2078
+ declare class ProductVariant {
2079
+ id: number;
2080
+ productId: number;
2081
+ sku: string | null;
2082
+ price: number | null;
2083
+ compareAtPrice: number | null;
2084
+ currencyPrices: Record<string, number> | null;
2085
+ inventory: number;
2086
+ status: ProductVariantStatus;
2087
+ attributes: ProductVariantAttributes | null;
2088
+ imageUrls: string[] | null;
2089
+ createdAt: Date;
2090
+ updatedAt: Date;
2091
+ product: Product;
1774
2092
  }
1775
2093
 
1776
2094
  declare class Product {
@@ -1786,8 +2104,11 @@ declare class Product {
1786
2104
  type: 'product' | 'service';
1787
2105
  slug: string | null;
1788
2106
  name: string | null;
2107
+ /** Optional display title (kept in sync with `name` by the products API). */
2108
+ title: string | null;
1789
2109
  price: number;
1790
2110
  compareAtPrice: number | null;
2111
+ currencyPrices: Record<string, number> | null;
1791
2112
  quantity: number;
1792
2113
  status: 'draft' | 'available' | 'reserved' | 'sold';
1793
2114
  featured: boolean;
@@ -1800,13 +2121,17 @@ declare class Product {
1800
2121
  updatedBy: number | null;
1801
2122
  deletedBy: number | null;
1802
2123
  seoId: number | null;
2124
+ /** CMS form used for product checkout / attendee capture. */
2125
+ contactFormId: number | null;
1803
2126
  vendor: Vendor;
1804
2127
  seo: Seo | null;
2128
+ contactForm: Form | null;
1805
2129
  collection: Collection | null;
1806
2130
  brand: Brand | null;
1807
2131
  category: ProductCategory | null;
1808
2132
  attributes: ProductAttribute[];
1809
- taxes: ProductTax[];
2133
+ taxes: ProductConfig[];
2134
+ variants: ProductVariant[];
1810
2135
  }
1811
2136
 
1812
2137
  declare class OrderItem {
@@ -1814,6 +2139,8 @@ declare class OrderItem {
1814
2139
  orderId: number;
1815
2140
  productId: number;
1816
2141
  discountIds: number[];
2142
+ vendorId: number | null;
2143
+ vendor: Vendor | null;
1817
2144
  quantity: number;
1818
2145
  unitPrice: number;
1819
2146
  subTotal: number;
@@ -1835,6 +2162,13 @@ declare class OrderItem {
1835
2162
  product: Product;
1836
2163
  }
1837
2164
 
2165
+ declare enum PaymentStatus {
2166
+ Unpaid = "unpaid",
2167
+ Paid = "paid",
2168
+ Pending = "pending",
2169
+ Failed = "failed",
2170
+ Refunded = "refunded"
2171
+ }
1838
2172
  declare class Payment {
1839
2173
  id: number;
1840
2174
  vendorId: number;
@@ -1842,7 +2176,7 @@ declare class Payment {
1842
2176
  contactId: number | null;
1843
2177
  amount: number;
1844
2178
  currency: string;
1845
- status: 'pending' | 'processing' | 'completed' | 'failed' | 'refunded';
2179
+ status: PaymentStatus;
1846
2180
  method: string | null;
1847
2181
  externalReference: string | null;
1848
2182
  metadata: Record<string, unknown> | null;
@@ -1904,88 +2238,990 @@ declare class Customer_Contacts {
1904
2238
  contact: Contact;
1905
2239
  }
1906
2240
 
1907
- type OrderKind = 'sale' | 'return' | 'replacement';
1908
- declare class Order {
1909
- id: number;
1910
- vendorId: number;
1911
- orderNumber: string;
1912
- qrToken: string | null;
1913
- orderKind: OrderKind;
1914
- parentOrderId: number | null;
1915
- contactId: number;
1916
- /** Junction row linking the account customer to the checkout contact (storefront checkout). */
1917
- customerContactId: number | null;
1918
- billingAddressId: number | null;
1919
- shippingAddressId: number | null;
1920
- status: 'pending' | 'confirmed' | 'processing' | 'completed' | 'cancelled';
1921
- subtotal: number;
1922
- tax: number;
1923
- discount: number;
1924
- total: number;
1925
- currency: string;
1926
- metadata: Record<string, unknown> | null;
1927
- createdAt: Date;
1928
- updatedAt: Date;
1929
- deletedAt: Date | null;
1930
- deleted: boolean;
1931
- createdBy: number | null;
1932
- updatedBy: number | null;
1933
- deletedBy: number | null;
1934
- vendor: Vendor;
1935
- parentOrder: Order | null;
1936
- children: Order[];
1937
- contact: Contact;
1938
- customerContact: Customer_Contacts | null;
1939
- billingAddress: OrderAddresses | null;
1940
- shippingAddress: OrderAddresses | null;
1941
- items: OrderItem[];
1942
- payments: Payment[];
1943
- }
2241
+ type OrderKind = 'sale' | 'return' | 'replacement';
2242
+ declare enum OrderStatus {
2243
+ Pending = "pending",
2244
+ Confirmed = "confirmed",
2245
+ Processing = "processing",
2246
+ Completed = "completed",
2247
+ Cancelled = "cancelled"
2248
+ }
2249
+ declare class Order {
2250
+ id: number;
2251
+ vendorId: number;
2252
+ orderNumber: string;
2253
+ qrToken: string | null;
2254
+ orderKind: OrderKind;
2255
+ parentOrderId: number | null;
2256
+ contactId: number;
2257
+ /** Junction row linking the account customer to the checkout contact (storefront checkout). */
2258
+ customerContactId: number | null;
2259
+ billingAddressId: number | null;
2260
+ shippingAddressId: number | null;
2261
+ status: OrderStatus;
2262
+ subtotal: number;
2263
+ tax: number;
2264
+ discount: number;
2265
+ total: number;
2266
+ currency: string;
2267
+ metadata: Record<string, unknown> | null;
2268
+ createdAt: Date;
2269
+ updatedAt: Date;
2270
+ deletedAt: Date | null;
2271
+ deleted: boolean;
2272
+ createdBy: number | null;
2273
+ updatedBy: number | null;
2274
+ deletedBy: number | null;
2275
+ vendor: Vendor;
2276
+ parentOrder: Order | null;
2277
+ children: Order[];
2278
+ contact: Contact;
2279
+ customerContact: Customer_Contacts | null;
2280
+ billingAddress: OrderAddresses | null;
2281
+ shippingAddress: OrderAddresses | null;
2282
+ items: OrderItem[];
2283
+ payments: Payment[];
2284
+ }
2285
+
2286
+ declare class ChatMessage {
2287
+ id: number;
2288
+ conversationId: number;
2289
+ role: 'user' | 'assistant' | 'system';
2290
+ content: string;
2291
+ createdAt: Date;
2292
+ conversation: ChatConversation;
2293
+ }
2294
+
2295
+ declare class ChatConversation {
2296
+ id: number;
2297
+ contactId: number;
2298
+ createdAt: Date;
2299
+ updatedAt: Date;
2300
+ /** Set when a chat lead email was sent for this conversation (intent tool). */
2301
+ leadEmailSentAt: Date | null;
2302
+ contact: Contact;
2303
+ messages: ChatMessage[];
2304
+ }
2305
+
2306
+ declare class Contact {
2307
+ id: number;
2308
+ name: string;
2309
+ email: string;
2310
+ phone: string | null;
2311
+ type: string | null;
2312
+ company: string | null;
2313
+ taxId: string | null;
2314
+ notes: string | null;
2315
+ createdAt: Date;
2316
+ updatedAt: Date;
2317
+ deletedAt: Date | null;
2318
+ deleted: boolean;
2319
+ createdBy: number | null;
2320
+ updatedBy: number | null;
2321
+ deletedBy: number | null;
2322
+ userId: number | null;
2323
+ user: User | null;
2324
+ form_submissions: FormSubmission[];
2325
+ addresses: Address[];
2326
+ orders: Order[];
2327
+ payments: Payment[];
2328
+ chatConversations: ChatConversation[];
2329
+ orderAddresses: OrderAddresses[];
2330
+ }
2331
+
2332
+ declare class FormSubmission {
2333
+ id: number;
2334
+ formId: number;
2335
+ contactId: number | null;
2336
+ data: Record<string, unknown>;
2337
+ ipAddress: string | null;
2338
+ userAgent: string | null;
2339
+ createdAt: Date;
2340
+ updatedAt: Date;
2341
+ form: Form;
2342
+ contact: Contact | null;
2343
+ }
2344
+
2345
+ declare class Form {
2346
+ id: number;
2347
+ name: string;
2348
+ description: string | null;
2349
+ campaign: string | null;
2350
+ slug: string;
2351
+ published: boolean;
2352
+ createdAt: Date;
2353
+ updatedAt: Date;
2354
+ deletedAt: Date | null;
2355
+ deleted: boolean;
2356
+ createdBy: number | null;
2357
+ updatedBy: number | null;
2358
+ deletedBy: number | null;
2359
+ fields: FormField[];
2360
+ submissions: FormSubmission[];
2361
+ }
2362
+
2363
+ declare class EventProduct {
2364
+ id: number;
2365
+ eventId: number;
2366
+ productId: number;
2367
+ displayOrder: number;
2368
+ isActive: boolean;
2369
+ createdAt: Date;
2370
+ updatedAt: Date;
2371
+ event: Event;
2372
+ product: Product;
2373
+ }
2374
+
2375
+ type EventSocialMediaLinks = {
2376
+ facebook?: string;
2377
+ instagram?: string;
2378
+ linkedin?: string;
2379
+ youtube?: string;
2380
+ twitter?: string;
2381
+ tiktok?: string;
2382
+ whatsapp?: string;
2383
+ };
2384
+ type EventPricingType = 'free' | 'paid';
2385
+ type EventEntityMode = 'inperson' | 'online' | 'hybrid';
2386
+ type EventVisibility = 'public' | 'private';
2387
+ declare class Event {
2388
+ id: number;
2389
+ vendorId: number | null;
2390
+ name: string;
2391
+ slug: string;
2392
+ description: string | null;
2393
+ expectedSpeakers: number | null;
2394
+ expectedParticipants: number | null;
2395
+ isActive: boolean;
2396
+ comingSoon: boolean;
2397
+ bannerImageUrl: string | null;
2398
+ logoUrl: string | null;
2399
+ venue: string | null;
2400
+ additionalVenueDetails: string | null;
2401
+ visibility: EventVisibility;
2402
+ startDate: Date | null;
2403
+ endDate: Date | null;
2404
+ registrationOpensAt: Date | null;
2405
+ registrationClosesAt: Date | null;
2406
+ pricingType: EventPricingType | null;
2407
+ entityTypes: string[] | null;
2408
+ entityMode: EventEntityMode | null;
2409
+ city: string | null;
2410
+ country: string | null;
2411
+ cityCountry: string | null;
2412
+ defaultCurrency: string | null;
2413
+ supportedCurrencies: string[] | null;
2414
+ timezone: string | null;
2415
+ socialMediaLinks: EventSocialMediaLinks | null;
2416
+ officialWebsiteUrl: string | null;
2417
+ supportContact: string | null;
2418
+ allowGroupOrders: boolean;
2419
+ sendIndividualTicketPDFToAttendees: boolean;
2420
+ /** CMS contact/attendee form used for this event's registration checkout. */
2421
+ contactFormId: number | null;
2422
+ /** GST / tax applied to event ticket sales. */
2423
+ taxId: number | null;
2424
+ /** Optional return/refund policy applied when cancelling orders for this event. */
2425
+ refundPolicyId: number | null;
2426
+ taxRate: number | null;
2427
+ maxGroupPurchaseQuantity: number | null;
2428
+ sponsors: Record<string, unknown> | unknown[] | null;
2429
+ agenda: Record<string, unknown> | unknown[] | null;
2430
+ workshops: Record<string, unknown> | unknown[] | null;
2431
+ exhibitors: Record<string, unknown> | unknown[] | null;
2432
+ partners: Record<string, unknown> | unknown[] | null;
2433
+ speakers: Record<string, unknown> | unknown[] | null;
2434
+ sortOrder: number;
2435
+ createdAt: Date;
2436
+ updatedAt: Date;
2437
+ deletedAt: Date | null;
2438
+ deleted: boolean;
2439
+ createdBy: number | null;
2440
+ updatedBy: number | null;
2441
+ deletedBy: number | null;
2442
+ vendor: Vendor | null;
2443
+ contactForm: Form | null;
2444
+ tax: Tax | null;
2445
+ refundPolicy: RefundPolicy | null;
2446
+ eventProducts: EventProduct[];
2447
+ }
2448
+
2449
+ type OrderLineForTemplate = {
2450
+ name: string;
2451
+ quantity: number;
2452
+ total: number | string;
2453
+ currency: string;
2454
+ };
2455
+ declare function buildEventOrderTemplateVariables(input: {
2456
+ event: Event;
2457
+ order: {
2458
+ orderNumber: string;
2459
+ total: number | string;
2460
+ currency: string;
2461
+ qrToken?: string | null;
2462
+ };
2463
+ contact: {
2464
+ name?: string | null;
2465
+ email?: string | null;
2466
+ phone?: string | null;
2467
+ };
2468
+ productNames: string;
2469
+ orderLines?: OrderLineForTemplate[];
2470
+ siteUrl?: string;
2471
+ }): Record<string, string>;
2472
+
2473
+ declare const EVENT_ORDER_TEMPLATE_KEY = "eventOrderPlaced";
2474
+ type EventOrderNotificationChannel = 'email' | 'whatsapp';
2475
+ type EventOrderTemplateOverride = {
2476
+ subject?: string;
2477
+ body?: string;
2478
+ externalTemplateRef?: string;
2479
+ };
2480
+ type EventOrderNotificationTemplates = Partial<Record<EventOrderNotificationChannel, EventOrderTemplateOverride>>;
2481
+ type EventOrderMessageTemplateDefault = {
2482
+ channel: EventOrderNotificationChannel;
2483
+ templateKey: string;
2484
+ name: string;
2485
+ subject?: string;
2486
+ body: string;
2487
+ externalTemplateRef?: string;
2488
+ };
2489
+ /** Variables available in email HTML and WhatsApp text templates. */
2490
+ declare const EVENT_ORDER_TEMPLATE_VARIABLES: readonly ["eventName", "eventSlug", "venue", "startDate", "orderNumber", "orderTotal", "currency", "customerName", "customerEmail", "customerPhone", "productNames", "trackUrl", "qrImageUrl", "orderDetails", "orderDetailsHtml"];
2491
+ declare const EVENT_ORDER_MESSAGE_TEMPLATE_DEFAULTS: EventOrderMessageTemplateDefault[];
2492
+ type ResolvedEventOrderTemplate = {
2493
+ subject?: string;
2494
+ body: string;
2495
+ externalTemplateRef?: string;
2496
+ name?: string;
2497
+ language?: string;
2498
+ paramOrder?: string[];
2499
+ enabled: boolean;
2500
+ };
2501
+ declare function resolveEventOrderTemplate(channel: EventOrderNotificationChannel, getRow: (channel: string, key: string) => Promise<{
2502
+ subject: string | null;
2503
+ body: string;
2504
+ externalTemplateRef: string | null;
2505
+ name?: string | null;
2506
+ language?: string | null;
2507
+ paramOrder?: string[] | null;
2508
+ enabled: boolean;
2509
+ } | null>, eventOverride?: EventOrderTemplateOverride | null): Promise<ResolvedEventOrderTemplate | null>;
2510
+
2511
+ interface EmitOrderNotificationTriggerDeps {
2512
+ dataSource: DataSource;
2513
+ entityMap: Record<string, unknown>;
2514
+ }
2515
+ declare function emitOrderNotificationTrigger(triggerKey: string, orderId: number, deps: EmitOrderNotificationTriggerDeps, extra?: {
2516
+ refundAmount?: number | null;
2517
+ }): Promise<void>;
2518
+ /** Fire-and-forget wrapper for API handlers (storefront, CRUD, CMS). */
2519
+ declare function fireOrderNotificationTrigger(triggerKey: string, orderId: number, deps: EmitOrderNotificationTriggerDeps, extra?: {
2520
+ refundAmount?: number | null;
2521
+ }): void;
2522
+
2523
+ interface WhatsappTriggerDispatcherDeps {
2524
+ dataSource: DataSource;
2525
+ entityMap: EntityMap$2;
2526
+ getCms: () => Promise<CmsAppLike$1>;
2527
+ }
2528
+ declare function initWhatsappTriggerDispatcher(deps: WhatsappTriggerDispatcherDeps): void;
2529
+ /** Manually re-fire a trigger for an existing order (admin testing / resend). */
2530
+ declare function resendOrderNotification(triggerKey: string, orderId: number, deps: WhatsappTriggerDispatcherDeps): Promise<{
2531
+ ok: boolean;
2532
+ error?: string;
2533
+ }>;
2534
+
2535
+ declare const KNOWN_NOTIFICATION_TRIGGERS: {
2536
+ readonly ORDER_PLACED: "order_placed";
2537
+ readonly ORDER_CANCELLED: "order_cancelled";
2538
+ };
2539
+ interface OrderTriggerPayload {
2540
+ orderId: number;
2541
+ orderNumber: string;
2542
+ customerName: string;
2543
+ customerPhone: string | null;
2544
+ total: number | string;
2545
+ currency: string;
2546
+ vendorId?: number | null;
2547
+ refundAmount?: number | null;
2548
+ }
2549
+ declare class NotificationTriggerEmitter extends EventEmitter {
2550
+ emitTrigger(triggerKey: string, payload: OrderTriggerPayload): void;
2551
+ onAnyTrigger(listener: (triggerKey: string, payload: OrderTriggerPayload) => void): void;
2552
+ }
2553
+ declare const notificationTriggerEmitter: NotificationTriggerEmitter;
2554
+
2555
+ /** Default order lifecycle triggers — seeded by migration, not tied to the `events` table. */
2556
+ declare const DEFAULT_ORDER_NOTIFICATION_TRIGGER_SEEDS: readonly [{
2557
+ readonly triggerKey: "order_placed";
2558
+ readonly label: "Order placed";
2559
+ readonly description: "Fires when a new order is created (storefront checkout or admin).";
2560
+ readonly category: "order";
2561
+ readonly sortOrder: 1;
2562
+ }, {
2563
+ readonly triggerKey: "order_cancelled";
2564
+ readonly label: "Order cancelled";
2565
+ readonly description: "Fires when an order is cancelled (includes refund amount when applicable).";
2566
+ readonly category: "order";
2567
+ readonly sortOrder: 2;
2568
+ }];
2569
+
2570
+ /** @deprecated Use DB catalog `order_notification_triggers`; kept for type hints. */
2571
+ declare const ORDER_NOTIFICATION_TRIGGERS: readonly [{
2572
+ readonly key: "order_placed";
2573
+ readonly label: "Order placed";
2574
+ }, {
2575
+ readonly key: "order_cancelled";
2576
+ readonly label: "Order cancelled";
2577
+ }];
2578
+ type OrderNotificationTriggerKey = (typeof ORDER_NOTIFICATION_TRIGGERS)[number]['key'];
2579
+
2580
+ type VendorOnboardedActivation = 'invite' | 'password';
2581
+ type VendorOnboardedKind = 'vendor_onboard' | 'team_invite';
2582
+
2583
+ interface EntityMapLike {
2584
+ configs: unknown;
2585
+ }
2586
+ interface SendVendorOnboardEmailInput {
2587
+ vendorName: string;
2588
+ vendorSlug?: string;
2589
+ ownerName: string;
2590
+ ownerEmail: string;
2591
+ activation: VendorOnboardedActivation;
2592
+ inviteLink?: string;
2593
+ signInLink: string;
2594
+ kind?: VendorOnboardedKind;
2595
+ /** When false, skips owner email but still notifies internal recipients. Default true. */
2596
+ sendToOwner?: boolean;
2597
+ }
2598
+ interface SendVendorOnboardEmailDeps {
2599
+ getDataSource: () => Promise<DataSource>;
2600
+ entityMap: EntityMapLike;
2601
+ getCms: () => Promise<CmsAppLike$3>;
2602
+ }
2603
+ /** After vendor onboard / team invite: email owner + platform team from plugin settings. */
2604
+ declare function sendVendorOnboardEmails(input: SendVendorOnboardEmailInput, deps: SendVendorOnboardEmailDeps): Promise<{
2605
+ ownerEmailSent: boolean;
2606
+ }>;
2607
+
2608
+ interface DataSourceManager {
2609
+ getDataSource: () => DataSource;
2610
+ getDataSourceInitialized: () => Promise<DataSource>;
2611
+ resetDataSource: () => void;
2612
+ registerOnReset: (cb: () => void) => void;
2613
+ isConnectionError: (e: unknown) => boolean;
2614
+ }
2615
+ declare function createDataSourceManager(entityMap: Record<string, unknown>, options?: {
2616
+ databaseUrl?: string;
2617
+ idleTimeoutMillis?: number;
2618
+ }): DataSourceManager;
2619
+
2620
+ interface SeedEntityMap {
2621
+ users: unknown;
2622
+ user_groups: unknown;
2623
+ }
2624
+ declare function seedDefaultAdmin(ds: DataSource, entityMap: SeedEntityMap, opts?: {
2625
+ email?: string;
2626
+ password?: string;
2627
+ }): Promise<void>;
2628
+
2629
+ type UserVendorContext = {
2630
+ vendorIds: number[];
2631
+ activeVendorId: number | null;
2632
+ /** @deprecated legacy vendor_users.role */
2633
+ vendorRole: VendorUserRole | null;
2634
+ vendorRoleId: number | null;
2635
+ vendorRoleName: string | null;
2636
+ isVendorRoleOwner: boolean;
2637
+ vendorEntityPerms: Record<string, EntityPermissionFlags>;
2638
+ };
2639
+ /** Load vendor membership + active vendor role permissions for session. */
2640
+ declare function loadUserVendorContext(dataSource: DataSource, userId: number, preferredVendorId?: number | null): Promise<UserVendorContext>;
2641
+
2642
+ /**
2643
+ * Build NextAuth options for credentials auth. App can extend/override via extend().
2644
+ */
2645
+
2646
+ interface NextAuthUser {
2647
+ id: number;
2648
+ email: string;
2649
+ name: string | null;
2650
+ password: string | null;
2651
+ blocked?: boolean;
2652
+ deleted?: boolean;
2653
+ groupId?: number | null;
2654
+ adminAccess?: boolean;
2655
+ group?: {
2656
+ name?: string;
2657
+ permissions?: Array<{
2658
+ entity: string;
2659
+ canCreate: boolean;
2660
+ canRead: boolean;
2661
+ canUpdate: boolean;
2662
+ canDelete: boolean;
2663
+ }>;
2664
+ };
2665
+ vendorIds?: number[];
2666
+ activeVendorId?: number | null;
2667
+ vendorRole?: 'owner' | 'staff' | null;
2668
+ vendorRoleId?: number | null;
2669
+ vendorRoleName?: string | null;
2670
+ isVendorRoleOwner?: boolean;
2671
+ vendorEntityPerms?: Record<string, {
2672
+ c: boolean;
2673
+ r: boolean;
2674
+ u: boolean;
2675
+ d: boolean;
2676
+ }>;
2677
+ }
2678
+ interface AuthorizeOtpInput {
2679
+ identifier: string;
2680
+ channel: 'email' | 'sms';
2681
+ code: string;
2682
+ }
2683
+ interface NextAuthOptionsConfig {
2684
+ /** Resolve user by email (e.g. from TypeORM). Return null if not found. */
2685
+ getUserByEmail: (email: string) => Promise<NextAuthUser | null>;
2686
+ comparePassword: (plain: string, hash: string) => Promise<boolean>;
2687
+ signInPage?: string;
2688
+ secret?: string;
2689
+ extend?: (options: NextAuthOptions) => NextAuthOptions;
2690
+ /** When false, password CredentialsProvider is omitted. Default true. */
2691
+ enablePasswordLogin?: boolean;
2692
+ /** When true, registers CredentialsProvider id `otp`. Requires authorizeOtp. Default false. */
2693
+ enableOtpLogin?: boolean;
2694
+ /** Validate OTP and return user (same shape as password flow) or null. */
2695
+ authorizeOtp?: (input: AuthorizeOtpInput) => Promise<NextAuthUser | null>;
2696
+ /**
2697
+ * Customer group sign-in policy for credentials/OTP on a shared `/api/auth` route:
2698
+ * - `true` — always allow (dedicated storefront auth)
2699
+ * - `false` — always block
2700
+ * - omitted — auto: allow unless `callbackUrl` targets `/admin` (storefront `/signin` works unchanged)
2701
+ */
2702
+ allowCustomerLogin?: boolean;
2703
+ }
2704
+ declare function getNextAuthOptions(config: NextAuthOptionsConfig): NextAuthOptions;
2705
+ /** Storefront sign-in: allows Customer group; use with signInPage `/signin`. */
2706
+ declare function getStorefrontNextAuthOptions(config: Omit<NextAuthOptionsConfig, 'allowCustomerLogin'>): NextAuthOptions;
2707
+
2708
+ declare function enrichUserWithVendorContext(dataSource: DataSource, user: NextAuthUser | null): Promise<NextAuthUser | null>;
2709
+
2710
+ /** Merge DB group + vendor_users into session (JWT often missing these). Server/API only. */
2711
+ declare function hydrateVendorSessionUser(dataSource: DataSource, user: SessionUser | null | undefined): Promise<SessionUser | null | undefined>;
2712
+ declare function invalidateMultiVendorCache(): void;
2713
+ declare function checkMultiVendorEnabled(dataSource: DataSource): Promise<boolean>;
2714
+ declare function invalidateEventsCache(): void;
2715
+ declare function checkEventsEnabled(dataSource: DataSource): Promise<boolean>;
2716
+
2717
+ interface NavItem {
2718
+ id: string;
2719
+ label: string;
2720
+ url: string;
2721
+ openInNewTab?: boolean;
2722
+ /** When set, url is derived from the linked page slug. */
2723
+ pageId?: number;
2724
+ children?: NavItem[];
2725
+ }
2726
+ interface NavbarConfig {
2727
+ logo: string;
2728
+ items: NavItem[];
2729
+ ctaLabel?: string;
2730
+ ctaUrl?: string;
2731
+ /** Optional variant for theme-specific layout (e.g. "page2"). */
2732
+ variant?: string;
2733
+ }
2734
+ interface FooterConfig {
2735
+ copyright: string;
2736
+ columns: {
2737
+ title: string;
2738
+ links: {
2739
+ label: string;
2740
+ url: string;
2741
+ }[];
2742
+ }[];
2743
+ socialLinks: {
2744
+ icon: string;
2745
+ url: string;
2746
+ }[];
2747
+ /** When set, footer shows this logo (e.g. same as navbar). */
2748
+ logo?: string;
2749
+ }
2750
+
2751
+ interface PublicThemeSettingsPayload {
2752
+ activeThemeId: string;
2753
+ primaryColor: string;
2754
+ secondaryColor: string;
2755
+ navbarConfig: NavbarConfig;
2756
+ footerOverrides: Partial<FooterConfig>;
2757
+ }
2758
+ declare function loadPublicThemeSettings(config: {
2759
+ dataSource: DataSource;
2760
+ entityMap: EntityMap$2;
2761
+ encryptionKey?: string;
2762
+ defaultActiveThemeId?: string;
2763
+ defaultPrimaryColor?: string;
2764
+ defaultSecondaryColor?: string;
2765
+ }): Promise<PublicThemeSettingsPayload>;
2766
+
2767
+ /** Normalize a logical media folder path: no leading/trailing slashes, no ".." segments, max length. */
2768
+ declare function sanitizeMediaFolderPath(input: unknown): string;
2769
+ /** Single path segment for storage (folder name or legacy path segment). */
2770
+ declare function sanitizeStorageSegment(name: string): string;
2771
+
2772
+ type EntityMap = Record<string, EntityTarget<ObjectLiteral>>;
2773
+ /** Build `a/b/c` path under `uploads/` from the chain of folder rows up to root. */
2774
+ declare function relativePathFromMediaParentId(dataSource: DataSource, entityMap: EntityMap, parentId: number | null): Promise<string>;
2775
+
2776
+ declare const ZIP_MIME_TYPES: Set<string>;
2777
+ declare function isZipMedia(mime: string | null | undefined, filename: string): boolean;
2778
+
2779
+ /**
2780
+ * Executes `fn` inside a transaction where the PostgreSQL GUC
2781
+ * `app.vendor_id` is set for the duration of that transaction.
2782
+ *
2783
+ * This activates the `vendor_isolation` RLS policy added by the
2784
+ * `VendorRls1775940000000` migration.
2785
+ *
2786
+ * vendorId = 0 → admin / all-access (policy allows everything)
2787
+ * vendorId > 0 → only rows whose `vendorId` column matches
2788
+ *
2789
+ * Example:
2790
+ * const orders = await withVendorRlsContext(dataSource, 4, (ds) =>
2791
+ * ds.getRepository(Order).find({ where: { deleted: false } })
2792
+ * );
2793
+ */
2794
+ declare function withVendorRlsContext<T>(dataSource: DataSource, vendorId: number, fn: (dataSource: DataSource) => Promise<T>): Promise<T>;
2795
+ /**
2796
+ * Convenience wrapper: sets admin mode (vendor_id = '0') so all rows are
2797
+ * visible regardless of their vendorId. Use for platform-admin queries.
2798
+ */
2799
+ declare function withAdminRlsContext<T>(dataSource: DataSource, fn: (dataSource: DataSource) => Promise<T>): Promise<T>;
2800
+
2801
+ type EnsureVendorCustomerDetails = {
2802
+ name: string;
2803
+ email: string;
2804
+ phone?: string | null;
2805
+ };
2806
+ declare function isCustomerTypeContact(type: unknown): boolean;
2807
+ /** Restrict contact list to rows linked in `vendor_customers` with type customer. */
2808
+ declare function applyVendorCustomersContactFilter(qb: SelectQueryBuilder<typeorm.ObjectLiteral>, contactAlias: string, scope: VendorScope, vendorIdFilter: number | null): void;
2809
+ declare function contactIsVendorCustomer(dataSource: DataSource, entityMap: EntityMap$2, vendorId: number, contactId: number): Promise<boolean>;
2810
+ /** Returns an error message when the contact is not a vendor-linked customer; otherwise null. */
2811
+ declare function assertContactAllowedForVendorOrder(dataSource: DataSource, entityMap: EntityMap$2, vendorId: number, contactId: number): Promise<string | null>;
2812
+ declare function resolveVendorIdForContactCheck(scope: VendorScope, bodyOrRow: Record<string, unknown>): number | null;
2813
+ /**
2814
+ * When an order is placed for a manually entered customer, ensure they appear in
2815
+ * vendor customers: customer row, vendor_customers link, and contact type.
2816
+ */
2817
+ declare function ensureVendorCustomerForOrderContact(dataSource: DataSource, entityMap: EntityMap$2, vendorId: number, contactId: number, details: EnsureVendorCustomerDetails): Promise<void>;
2818
+
2819
+ /** One band: refund % when cancellation falls N days before event start. */
2820
+ type RefundPolicyTier = {
2821
+ /** Inclusive lower bound (days before event start; 0 = event day). */
2822
+ fromDaysBefore: number;
2823
+ /** Exclusive upper bound, or null for open-ended (e.g. 20+ days). */
2824
+ toDaysBefore: number | null;
2825
+ percentage: number;
2826
+ };
2827
+ type RefundPolicyType = 'percentage' | 'event_tiers';
2828
+ type RefundPolicyLike = {
2829
+ id?: number;
2830
+ type: RefundPolicyType;
2831
+ value: number;
2832
+ refundWindowDays: number;
2833
+ tiers?: RefundPolicyTier[] | null;
2834
+ };
2835
+ type RefundCalculationResult = {
2836
+ amount: number;
2837
+ percentage: number;
2838
+ daysBeforeEvent: number | null;
2839
+ daysSincePurchase: number | null;
2840
+ policyId: number | null;
2841
+ summary: string;
2842
+ /** Order cancelled without policy-based refund (no policy on event). */
2843
+ directCancellation?: boolean;
2844
+ eventId?: number | null;
2845
+ eventName?: string | null;
2846
+ };
2847
+ declare function normalizeRefundTiers(raw: unknown): RefundPolicyTier[];
2848
+ declare function validateRefundTiers(tiers: RefundPolicyTier[]): string | null;
2849
+ declare function daysBeforeEventStart(eventStart: Date, asOf?: Date): number;
2850
+ declare function formatTierRange(tier: RefundPolicyTier): string;
2851
+ declare function describeEventTierPolicy(tiers: RefundPolicyTier[]): string;
2852
+ declare function calculateRefundFromPolicy(policy: RefundPolicyLike | null | undefined, orderTotal: number, options?: {
2853
+ orderCreatedAt?: Date | null;
2854
+ eventStartDate?: Date | null;
2855
+ asOf?: Date;
2856
+ }): RefundCalculationResult;
2857
+
2858
+ type PolicyRow = RefundPolicyLike & {
2859
+ id: number;
2860
+ };
2861
+ declare function calculateOrderRefundPreview(dataSource: DataSource, entityMap: EntityMap$2, order: {
2862
+ id: number;
2863
+ vendorId?: number | null;
2864
+ total?: number | null;
2865
+ createdAt?: Date | string | null;
2866
+ }, asOf?: Date): Promise<RefundCalculationResult & {
2867
+ eventStartDate: string | null;
2868
+ directCancellation: boolean;
2869
+ eventId: number | null;
2870
+ eventName: string | null;
2871
+ }>;
2872
+ /** @deprecated Use event-attached policy via calculateOrderRefundPreview. */
2873
+ declare function findActiveRefundPolicyForVendor(dataSource: DataSource, entityMap: EntityMap$2, vendorId: number | null | undefined): Promise<PolicyRow | null>;
2874
+
2875
+ type CaptchaProviderId = 'turnstile' | 'recaptcha_v3';
2876
+ interface CaptchaPublicConfig {
2877
+ enabled: boolean;
2878
+ activeProvider: CaptchaProviderId | null;
2879
+ siteKey: string | null;
2880
+ availableProviders: Array<{
2881
+ id: CaptchaProviderId;
2882
+ siteKey: string;
2883
+ }>;
2884
+ multipleProviders: boolean;
2885
+ }
2886
+ type CaptchaVerifyResult = {
2887
+ ok: true;
2888
+ } | {
2889
+ ok: false;
2890
+ status: number;
2891
+ message: string;
2892
+ };
2893
+ declare function buildCaptchaPublicConfig(config: Record<string, string>): CaptchaPublicConfig;
2894
+ declare class CaptchaService {
2895
+ private readonly env;
2896
+ constructor(env: Record<string, string>);
2897
+ isEnforced(): boolean;
2898
+ getPublicConfig(): CaptchaPublicConfig;
2899
+ verify(body: Record<string, unknown>, req: Request): Promise<CaptchaVerifyResult>;
2900
+ }
2901
+
2902
+ declare function captchaPlugin(): CmsPlugin<CaptchaService | void>;
2903
+
2904
+ type JsonResponse = (body: unknown, init?: {
2905
+ status?: number;
2906
+ headers?: HeadersInit;
2907
+ }) => Response;
2908
+ declare function assertCaptchaOk(getCms: (() => Promise<{
2909
+ getPlugin: (name: string) => unknown;
2910
+ }>) | undefined, body: Record<string, unknown>, req: Request, json: JsonResponse): Promise<Response | null>;
2911
+
2912
+ interface LatestArticleFromFeed {
2913
+ title?: string;
2914
+ link?: string;
2915
+ /** Short excerpt */
2916
+ summary?: string;
2917
+ /** Full content if available */
2918
+ content?: string;
2919
+ date: Date;
2920
+ creator?: string;
2921
+ categories?: string[];
2922
+ }
2923
+ type RssItem = {
2924
+ title?: string;
2925
+ link?: string;
2926
+ pubDate?: string;
2927
+ isoDate?: string;
2928
+ contentSnippet?: string;
2929
+ summary?: string;
2930
+ description?: string;
2931
+ content?: string;
2932
+ creator?: string;
2933
+ 'dc:creator'?: string;
2934
+ 'content:encoded'?: string;
2935
+ categories?: string[];
2936
+ guid?: string | {
2937
+ _: string;
2938
+ };
2939
+ };
2940
+ declare function getRssArticleSummaryFromItem(item: RssItem): {
2941
+ summary: string;
2942
+ fullContent: string;
2943
+ };
2944
+ type BlogGeneratorDraftParseMode = 'json' | 'plaintext';
2945
+ interface BlogGeneratorSeoDraft {
2946
+ title: string | null;
2947
+ description: string | null;
2948
+ keywords: string | null;
2949
+ ogTitle: string | null;
2950
+ ogDescription: string | null;
2951
+ }
2952
+ interface BlogGeneratorBlogDraft {
2953
+ title: string;
2954
+ slug?: string;
2955
+ markdown: string;
2956
+ /** Short plain-text copy for social (e.g. LinkedIn); optional until social LLM step runs. */
2957
+ socialMediaContent?: string | null;
2958
+ categoryName: string | null;
2959
+ seo: BlogGeneratorSeoDraft;
2960
+ /** Suggested tag labels (may not exist in CMS yet). */
2961
+ tags: string[];
2962
+ parseMode: BlogGeneratorDraftParseMode;
2963
+ }
2964
+ /**
2965
+ * Parses the LLM reply: prefers a single JSON object with blogTitle, blogHtml/blogMarkdown/content, categoryName, seo, …
2966
+ * Falls back to treating the entire string as HTML (or legacy markdown) if JSON parsing fails.
2967
+ */
2968
+ declare function parseBlogGeneratorAgentContent(raw: string): BlogGeneratorBlogDraft;
2969
+ declare function resolveBlogCategoryIdByName(needle: string | null | undefined, rows: readonly {
2970
+ id: number;
2971
+ name: string;
2972
+ }[]): {
2973
+ categoryId: number | null;
2974
+ matched: boolean;
2975
+ };
2976
+ /**
2977
+ * Minimal user payload: latest item per feed only (system prompt carries writing rules).
2978
+ */
2979
+ declare function buildRssUserPromptFromFeeds(feeds: ReadonlyArray<{
2980
+ rssUrl: string;
2981
+ article: LatestArticleFromFeed;
2982
+ }>): string;
2983
+ /**
2984
+ * User message for the metadata-only LLM step (one blog at a time).
2985
+ */
2986
+ declare function buildBlogMetadataUserPrompt(opts: {
2987
+ title: string;
2988
+ markdown: string;
2989
+ categoryNames: readonly string[];
2990
+ tagNames: readonly string[];
2991
+ }): string;
2992
+ /** Parses JSON from the metadata-enrichment LLM (category, slug, seo, tags). */
2993
+ declare function parseBlogMetadataEnrichmentJson(raw: string): {
2994
+ categoryName: string | null;
2995
+ blogSlug: string | null;
2996
+ seo: BlogGeneratorSeoDraft;
2997
+ tags: string[];
2998
+ };
2999
+ /**
3000
+ * Parses LLM output: prefers HTML + {@link BLOG_GENERATOR_MARKDOWN_ARTICLE_SEPARATOR} for multiple articles.
3001
+ * If the model still returns legacy JSON with `blogHtml` / `blogMarkdown`, returns a single draft from that object.
3002
+ */
3003
+ declare function parseBlogGeneratorModelOutput(raw: string): BlogGeneratorBlogDraft[];
3004
+ declare class BlogGeneratorService {
3005
+ readonly version: "1.0.0";
3006
+ getLatestArticleFromFeed(rssUrl: string): Promise<LatestArticleFromFeed | null>;
3007
+ /** Defaults for the Blog Generator Agent (admin can override per request). */
3008
+ getAgentDefaults(): {
3009
+ agentName: string;
3010
+ systemInstruction: string;
3011
+ validationRules: string;
3012
+ };
3013
+ /**
3014
+ * Second LLM call: one draft at a time — category, URL slug, SEO fields, tags (JSON).
3015
+ */
3016
+ private enrichBlogDraftWithLlmMetadata;
3017
+ /**
3018
+ * Third LLM call: one draft at a time — short social copy (JSON `{ socialMediaContent }`).
3019
+ */
3020
+ private enrichBlogDraftWithLlmSocial;
3021
+ /**
3022
+ * Fetches the latest item for each RSS URL, then calls {@link LlmServiceInterface.chatAgent}.
3023
+ * `userPrompt` is only per-feed source material; rules live in the system prompt.
3024
+ * Expects HTML article fragment(s), optionally separated by {@link BLOG_GENERATOR_MARKDOWN_ARTICLE_SEPARATOR}.
3025
+ */
3026
+ generateBlogMarkdownFromRss(params: {
3027
+ llm: LlmServiceInterface;
3028
+ /** Single feed (legacy). */
3029
+ rssUrl?: string;
3030
+ /** One or more feeds; latest item per URL is sent together. Prefer this when multiple URLs. */
3031
+ rssUrls?: readonly string[];
3032
+ systemInstruction?: string;
3033
+ validationRules?: string;
3034
+ /** Reserved for future structured output; writer does not inject categories into the user prompt. */
3035
+ categoryNamesHint?: readonly string[];
3036
+ /** Names of non-deleted tags in CMS (hint for reuse). */
3037
+ tagNamesHint?: readonly string[];
3038
+ /** From optional `llm_agents` row (slug `blog-generator`): model / sampling for the writer step. */
3039
+ llmAgentChatOptions?: Pick<LlmAgentOptions, 'model' | 'temperature' | 'max_tokens'>;
3040
+ /** Optional overrides for the metadata step; defaults live in `blog-generator-metadata-defaults.ts`. */
3041
+ metadataSystemInstruction?: string;
3042
+ metadataValidationRules?: string;
3043
+ /** From optional `llm_agents` row (slug `blog-generator-metadata`): model / sampling for metadata only. */
3044
+ metadataLlmAgentChatOptions?: Pick<LlmAgentOptions, 'model' | 'temperature' | 'max_tokens'>;
3045
+ /** Optional overrides for the social-summary step; defaults in `blog-generator-social-defaults.ts`. */
3046
+ socialSystemInstruction?: string;
3047
+ socialValidationRules?: string;
3048
+ /** From optional `llm_agents` row (slug `blog-generator-social`): model / sampling for social copy only. */
3049
+ socialLlmAgentChatOptions?: Pick<LlmAgentOptions, 'model' | 'temperature' | 'max_tokens'>;
3050
+ }): Promise<{
3051
+ agentName: string;
3052
+ feedArticles: Array<{
3053
+ rssUrl: string;
3054
+ article: LatestArticleFromFeed;
3055
+ }>;
3056
+ /** First feed's article (backward compatibility). */
3057
+ article: LatestArticleFromFeed;
3058
+ /** Raw model reply (HTML body per defaults; legacy markdown or JSON still parsed when present). */
3059
+ blogMarkdown: string;
3060
+ blogDrafts: BlogGeneratorBlogDraft[];
3061
+ /** Same as first draft; backward compatibility. */
3062
+ blogDraft: BlogGeneratorBlogDraft;
3063
+ }>;
3064
+ }
3065
+
3066
+ /** Stable display name; not persisted as DB agent row in v1. */
3067
+ declare const BLOG_GENERATOR_AGENT_NAME = "Blog Generator Agent";
3068
+ /**
3069
+ * Optional `llm_agents` row: when present and enabled, model / temperature / max_tokens
3070
+ * are applied to {@link LlmServiceInterface.chatAgent} (system + user content still come from blog generator defaults / UI).
3071
+ */
3072
+ declare const BLOG_GENERATOR_LLM_AGENT_SLUG = "blog-generator";
3073
+ /** Line that separates multiple articles in the model reply (HTML or legacy markdown; must match parser and prompts). */
3074
+ declare const BLOG_GENERATOR_MARKDOWN_ARTICLE_SEPARATOR = "---BLOG_GENERATOR_NEXT---";
3075
+ declare const BLOG_GENERATOR_DEFAULT_SYSTEM_INSTRUCTION = "You are a professional financial and business content writer.\n\nYour task is to generate completely original, high-quality blog article(s) from the latest RSS-derived source material in the user message (one block per feed). The user message is factual input only.\n\nIMPORTANT RULES:\n\n1. NEVER copy the RSS article directly.\n2. Rewrite the information into a fresh, human-like article.\n3. Expand the topic with professional insights and explanations.\n4. Maintain a natural editorial tone.\n5. Make the article SEO-friendly.\n6. Use engaging headings and subheadings.\n7. Avoid robotic AI phrasing.\n8. Do not mention that the content came from RSS or feeds.\n9. Preserve factual accuracy from the source material.\n10. The output should feel like a professionally written industry blog.\n\nMULTIPLE FEEDS:\n- If several feeds are provided, compare them: if they largely cover the same story or overlap heavily, produce ONE cohesive article.\n- If they cover clearly different topics or distinct stories, produce MULTIPLE articles (one per distinct story).\n- You may also produce one synthesis plus a short separate angle when that best serves the reader\u2014use your judgment.\n\nWRITING STYLE:\n- Professional\n- Clear\n- Informative\n- Business-focused\n- Human sounding\n- Modern editorial style\n\nARTICLE STRUCTURE (each article \u2014 express in HTML):\n1. Engaging introduction\n2. Industry context\n3. Main developments\n4. Key implications\n5. Expert/business analysis\n6. Conclusion\n\nHTML STRUCTURE (STRICT \u2014 each article must be valid, semantic HTML only):\n- Output HTML only. Do not use Markdown (no # headings, no **bold**, no `code fences`).\n- Wrap each complete article in a single root: <article class=\"blog-post\"> ... </article>\n- Inside <article>, use this outline:\n - <header><h1 class=\"blog-post-title\">\u2026main title\u2026</h1></header> (exactly one h1 per article)\n - <section class=\"blog-post-body\"> for all following content\n - Use <h2> and <h3> for section and subsection titles (never skip levels: h1 \u2192 h2 \u2192 h3).\n - Use <p> for paragraphs; keep paragraphs focused (avoid huge unbroken text).\n - Use <ul>/<ol> with <li> for lists where appropriate.\n - Use <strong> and <em> for emphasis sparingly; use <blockquote> only when quoting or callouts fit.\n- Do not include <html>, <head>, <body>, or document-level wrappers \u2014 only the fragment(s) described above.\n- Do not use <script>, <style>, <iframe>, or inline event handlers. Avoid inline style=\"\" except when essential for accessibility (prefer none).\n- Escape angle brackets in body text if you must mention markup; keep output safe for embedding in a CMS.\n\nCONTENT REQUIREMENTS:\n- Minimum 800 words per article unless source material is very small.\n- Add context around industry trends where appropriate.\n- Explain why the topic matters.\n- Include practical implications for businesses/professionals.\n\nIF RSS CONTENT IS LIMITED:\n- Expand intelligently using general industry knowledge.\n- Keep the article relevant to the original topic.\n- Do not invent fake facts or statistics.\n\nOUTPUT FORMAT (STRICT \u2014 HTML only):\n- Return ONLY the article HTML fragment(s). No JSON, no preamble or postscript (\"Here is your article\u2026\"), no markdown.\n- If you output more than one article, output multiple <article class=\"blog-post\">\u2026</article> blocks in sequence, and between articles put a single line containing exactly this (and nothing else on that line):\n---BLOG_GENERATOR_NEXT---\n- If you output a single article, use one <article> only and do not use that separator line.";
3076
+ /**
3077
+ * JSON so {@link parseLlmAgentValidationRules} can attach guardrails and allow long source payloads.
3078
+ * Edit in the admin UI if needed; defaults match product intent.
3079
+ */
3080
+ declare const BLOG_GENERATOR_DEFAULT_VALIDATION_RULES: string;
3081
+
3082
+ /**
3083
+ * Second-step LLM: classifies one finished HTML blog body into CMS fields (category, SEO, tags).
3084
+ *
3085
+ * Optional `llm_agents` row: slug {@link BLOG_METADATA_ENRICHER_LLM_AGENT_SLUG} — when present and enabled,
3086
+ * model / temperature / max_tokens apply to this call only (writer step uses `blog-generator`).
3087
+ *
3088
+ * To change how metadata is produced, edit the constants in this file (system instruction + validation JSON).
3089
+ * No admin UI override is wired yet; add request body fields in `cms-api-handler` if you need runtime overrides later.
3090
+ */
3091
+ declare const BLOG_METADATA_ENRICHER_AGENT_NAME = "Blog Generator Metadata";
3092
+ /** `llm_agents.slug` for routing model/temperature for the metadata-only chat step. */
3093
+ declare const BLOG_METADATA_ENRICHER_LLM_AGENT_SLUG = "blog-generator-metadata";
3094
+ declare const BLOG_METADATA_ENRICHER_DEFAULT_SYSTEM_INSTRUCTION = "You are a careful CMS metadata assistant for a publishing system.\n\nYou receive ONE complete blog post as HTML (title is usually in <h1 class=\"blog-post-title\"> or the first <h1>). Your job is to propose structured fields so an editor can save the post: category, URL slug, SEO block, and topical tags.\n\nRULES:\n1. Read the whole article and infer the primary topic and audience.\n2. categoryName must be EXACTLY one string from AVAILABLE_BLOG_CATEGORIES in the user message, or \"\" if none fit.\n3. blogSlug: lowercase kebab-case, ASCII letters/digits/hyphens only, no leading/trailing hyphens, max ~80 chars. Derive from the main topic or title.\n4. seo.title: concise meta title (~50\u201360 characters when reasonable).\n5. seo.description: meta description (~150\u2013160 characters when reasonable), plain text.\n6. seo.keywords: comma-separated phrases, no stuffing.\n7. seo.ogTitle / seo.ogDescription: may mirror title/description or be slightly adapted for social.\n8. tags: 4\u201310 short labels (1\u20133 words each). Prefer exact matches from EXISTING_TAG_NAMES when they truly apply; otherwise invent precise new labels (they may be created in the CMS later).\n9. Do not invent statistics, quotes, or URLs not implied by the article.\n10. Output JSON only \u2014 no markdown outside the JSON, no commentary.\n\nOUTPUT FORMAT (STRICT):\nReturn a single JSON object only. Do not wrap it in a markdown code fence.\n\n{\n \"categoryName\": \"string \u2014 exact match from list or empty string\",\n \"blogSlug\": \"string \u2014 url-safe kebab-case\",\n \"seo\": {\n \"title\": \"string or empty\",\n \"description\": \"string or empty\",\n \"keywords\": \"string or empty\",\n \"ogTitle\": \"string or empty\",\n \"ogDescription\": \"string or empty\"\n },\n \"tags\": [\"tag-one\", \"tag-two\"]\n}";
3095
+ declare const BLOG_METADATA_ENRICHER_DEFAULT_VALIDATION_RULES: string;
3096
+
3097
+ interface BlogGeneratorPluginConfig {
3098
+ /** Set to false to skip registering the plugin. */
3099
+ enabled?: boolean;
3100
+ }
3101
+ declare function blogGeneratorPlugin(config?: BlogGeneratorPluginConfig): CmsPlugin<BlogGeneratorService | undefined>;
3102
+
3103
+ interface SocialMediaApiConfig {
3104
+ dataSource: DataSource;
3105
+ entityMap: EntityMap$2;
3106
+ json: (body: unknown, init?: {
3107
+ status?: number;
3108
+ }) => Response;
3109
+ requireAuth: (req: Request) => Promise<Response | null>;
3110
+ requireEntityPermission: (req: Request, entity: string, action: EntityCrudAction) => Promise<Response | null>;
3111
+ encryptionKey?: string;
3112
+ /** Used to resolve relative cover image URLs (e.g. https://mysite.com). */
3113
+ publicSiteUrl?: string;
3114
+ /**
3115
+ * When true (default), `console.info` / `console.warn` lines are emitted for LinkedIn blog publish
3116
+ * (text vs image path, sizes, errors). Set false or `CMS_LINKEDIN_PUBLISH_LOG=0` to silence.
3117
+ */
3118
+ linkedInPublishLogging?: boolean;
3119
+ }
3120
+ declare function createSocialMediaHandlers(config: SocialMediaApiConfig): {
3121
+ getLinkedInStatus(req: Request): Promise<Response>;
3122
+ fetchLinkedInOrganizations(req: Request): Promise<Response>;
3123
+ syncLinkedInProfile(req: Request): Promise<Response>;
3124
+ publishBlogToLinkedIn(req: Request, blogId: number): Promise<Response>;
3125
+ getFacebookStatus(req: Request): Promise<Response>;
3126
+ publishBlogToFacebook(req: Request, blogId: number): Promise<Response>;
3127
+ /**
3128
+ * POST JSON `{ appId, appSecret, userAccessToken }`. Calls Graph `GET /me/accounts` with the user token.
3129
+ * App ID and secret are validated but not used yet (reserved for future token flows).
3130
+ * Persist credentials via Plugins → Save: `meta_app_id` (public), `meta_app_secret` and `meta_user_access_token` (encrypted).
3131
+ */
3132
+ fetchFacebookManagedPages(req: Request): Promise<Response>;
3133
+ };
3134
+
3135
+ /**
3136
+ * Meta (Facebook) Graph API helpers (server-side). Uses fetch — no SDK.
3137
+ * @see https://developers.facebook.com/docs/graph-api/reference/user/accounts
3138
+ */
3139
+ type FacebookPageAccount = {
3140
+ access_token?: string;
3141
+ category?: string;
3142
+ name?: string;
3143
+ id?: string;
3144
+ /** Graph may return additional fields */
3145
+ [key: string]: unknown;
3146
+ };
3147
+ type FacebookMeAccountsResponse = {
3148
+ data?: FacebookPageAccount[];
3149
+ paging?: Record<string, unknown>;
3150
+ error?: {
3151
+ message?: string;
3152
+ type?: string;
3153
+ code?: number;
3154
+ fbtrace_id?: string;
3155
+ };
3156
+ };
3157
+ /**
3158
+ * Lists Facebook Pages the user manages (page access tokens + metadata).
3159
+ * Requires a User access token with `pages_show_list` or equivalent page permissions.
3160
+ */
3161
+ declare function metaFetchUserManagedPages(userAccessToken: string): Promise<FacebookMeAccountsResponse>;
3162
+ type MetaGraphMutationResponse = {
3163
+ id?: string;
3164
+ post_id?: string;
3165
+ error?: {
3166
+ message?: string;
3167
+ type?: string;
3168
+ code?: number;
3169
+ fbtrace_id?: string;
3170
+ };
3171
+ };
3172
+ /** Resolves the long-lived page access token for a Page ID from `/me/accounts` data. */
3173
+ declare function metaResolvePageAccessToken(accounts: FacebookMeAccountsResponse, pageId: string): string | null;
3174
+ /**
3175
+ * Upload a photo to a Page timeline (multipart).
3176
+ * @see https://developers.facebook.com/docs/graph-api/reference/page/photos#Creating
3177
+ */
3178
+ declare function metaPostPagePhoto(opts: {
3179
+ pageId: string;
3180
+ pageAccessToken: string;
3181
+ imageBuffer: Buffer;
3182
+ contentType: string;
3183
+ caption: string;
3184
+ }): Promise<MetaGraphMutationResponse>;
3185
+ /**
3186
+ * Publish a text-only post to the Page feed (when no JPEG/PNG image is available).
3187
+ * @see https://developers.facebook.com/docs/graph-api/reference/page/feed#Creating
3188
+ */
3189
+ declare function metaPostPageFeed(opts: {
3190
+ pageId: string;
3191
+ pageAccessToken: string;
3192
+ message: string;
3193
+ }): Promise<MetaGraphMutationResponse>;
1944
3194
 
1945
- declare class ChatMessage {
1946
- id: number;
1947
- conversationId: number;
1948
- role: 'user' | 'assistant' | 'system';
1949
- content: string;
1950
- createdAt: Date;
1951
- conversation: ChatConversation;
3195
+ interface SocialMediaPluginConfig {
3196
+ /** Set to false to skip registering the plugin instance (API routes still work if wired in the app handler). */
3197
+ enabled?: boolean;
1952
3198
  }
3199
+ /**
3200
+ * Optional CMS plugin instance for `getPlugin('social_media')`.
3201
+ * LinkedIn publishing is implemented in {@link createSocialMediaHandlers} and mounted from the CMS API handler.
3202
+ */
3203
+ declare function socialMediaPlugin(config?: SocialMediaPluginConfig): CmsPlugin<{
3204
+ name: string;
3205
+ } | undefined>;
1953
3206
 
1954
- declare class ChatConversation {
3207
+ declare class OtpChallenge {
1955
3208
  id: number;
1956
- contactId: number;
3209
+ purpose: string;
3210
+ channel: string;
3211
+ identifier: string;
3212
+ codeHash: string;
3213
+ expiresAt: Date;
3214
+ attempts: number;
3215
+ consumedAt: Date | null;
1957
3216
  createdAt: Date;
1958
- updatedAt: Date;
1959
- /** Set when a chat lead email was sent for this conversation (intent tool). */
1960
- leadEmailSentAt: Date | null;
1961
- contact: Contact;
1962
- messages: ChatMessage[];
1963
3217
  }
1964
3218
 
1965
- declare class Contact {
3219
+ declare class PasswordResetToken {
1966
3220
  id: number;
1967
- name: string;
1968
3221
  email: string;
1969
- phone: string | null;
1970
- type: string | null;
1971
- company: string | null;
1972
- taxId: string | null;
1973
- notes: string | null;
3222
+ token: string;
3223
+ expiresAt: Date;
1974
3224
  createdAt: Date;
1975
- updatedAt: Date;
1976
- deletedAt: Date | null;
1977
- deleted: boolean;
1978
- createdBy: number | null;
1979
- updatedBy: number | null;
1980
- deletedBy: number | null;
1981
- userId: number | null;
1982
- user: User | null;
1983
- form_submissions: FormSubmission[];
1984
- addresses: Address[];
1985
- orders: Order[];
1986
- payments: Payment[];
1987
- chatConversations: ChatConversation[];
1988
- orderAddresses: OrderAddresses[];
1989
3225
  }
1990
3226
 
1991
3227
  declare class Config {
@@ -2297,7 +3533,301 @@ declare class VendorCustomer {
2297
3533
  customer: Customer;
2298
3534
  }
2299
3535
 
3536
+ declare enum ComboItemType {
3537
+ FIXED = "fixed",
3538
+ ADDONS = "addons"
3539
+ }
3540
+ declare class ComboItem {
3541
+ id: number;
3542
+ comboId: number;
3543
+ combo: Combo;
3544
+ productId: number;
3545
+ product: Product;
3546
+ type: ComboItemType;
3547
+ }
3548
+
3549
+ declare enum ComboStatus {
3550
+ ACTIVE = "active",
3551
+ INACTIVE = "inactive",
3552
+ DRAFT = "draft"
3553
+ }
3554
+ declare class Combo {
3555
+ id: number;
3556
+ name: string;
3557
+ desc?: string;
3558
+ eventId: number;
3559
+ event: Event;
3560
+ price: number;
3561
+ currencyPrices: Record<string, number> | null;
3562
+ minSelectableItems: number;
3563
+ maxSelectableItems: number;
3564
+ status: ComboStatus;
3565
+ startsAt?: Date;
3566
+ endsAt?: Date;
3567
+ metadata?: Record<string, any>;
3568
+ items: ComboItem[];
3569
+ createdAt: Date;
3570
+ updatedAt: Date;
3571
+ deletedAt?: Date;
3572
+ deleted: boolean;
3573
+ createdBy?: number;
3574
+ updatedBy?: number;
3575
+ deletedBy?: number;
3576
+ }
3577
+
3578
+ declare enum RefundMethod {
3579
+ CARD = "card",
3580
+ UPI = "upi",
3581
+ NET_BANKING = "net_banking"
3582
+ }
3583
+ declare enum RefundRequestStatus {
3584
+ REQUESTED = "requested",
3585
+ APPROVED = "approved",
3586
+ REJECTED = "rejected",
3587
+ REFUNDED = "refunded"
3588
+ }
3589
+ declare class RefundRequest {
3590
+ id: number;
3591
+ refundPolicyId: number;
3592
+ refundPolicy: RefundPolicy;
3593
+ orderId: number;
3594
+ order: Order;
3595
+ customerId: number;
3596
+ customer: Customer;
3597
+ reason?: string;
3598
+ refundMethod: RefundMethod;
3599
+ status: RefundRequestStatus;
3600
+ expectedRefundAmount: number;
3601
+ approvedRefundAmount?: number;
3602
+ }
3603
+
3604
+ declare class Attendee {
3605
+ id: number;
3606
+ displayName: string;
3607
+ email: string;
3608
+ contactId: number | null;
3609
+ contact: Contact | null;
3610
+ }
3611
+
3612
+ declare class WhatsappTriggerBinding {
3613
+ id: number;
3614
+ triggerKey: string;
3615
+ messageTemplateId: number | null;
3616
+ enabled: boolean;
3617
+ createdAt: Date;
3618
+ updatedAt: Date;
3619
+ }
3620
+
3621
+ declare class OrderNotificationTrigger {
3622
+ id: number;
3623
+ triggerKey: string;
3624
+ label: string;
3625
+ description: string | null;
3626
+ category: string;
3627
+ enabled: boolean;
3628
+ sortOrder: number;
3629
+ createdAt: Date;
3630
+ updatedAt: Date;
3631
+ }
3632
+
2300
3633
  /** Map API resource segment (e.g. "blogs", "form_submissions") to entity. Used by CRUD handler. */
2301
3634
  declare const CMS_ENTITY_MAP: Record<string, EntityTarget<typeorm.ObjectLiteral>>;
2302
3635
 
2303
- export { Address, type AnalyticsPluginConfig, Attribute, BLOG_GENERATOR_AGENT_NAME, BLOG_GENERATOR_DEFAULT_SYSTEM_INSTRUCTION, BLOG_GENERATOR_DEFAULT_VALIDATION_RULES, BLOG_GENERATOR_LLM_AGENT_SLUG, BLOG_GENERATOR_MARKDOWN_ARTICLE_SEPARATOR, BLOG_METADATA_ENRICHER_AGENT_NAME, BLOG_METADATA_ENRICHER_DEFAULT_SYSTEM_INSTRUCTION, BLOG_METADATA_ENRICHER_DEFAULT_VALIDATION_RULES, BLOG_METADATA_ENRICHER_LLM_AGENT_SLUG, Blog, type BlogGeneratorBlogDraft, type BlogGeneratorDraftParseMode, type BlogGeneratorPluginConfig, type BlogGeneratorSeoDraft, BlogGeneratorService, Brand, CMS_ENTITY_MAP, type CachePluginConfig, type CacheService, type CaptchaProviderId, type CaptchaPublicConfig, CaptchaService, type CaptchaVerifyResult, Cart, CartItem, Category, ChatConversation, ChatMessage, type CmsApp, type CmsPlugin, Collection, Comment, CompanyDetails, Config, Contact, type CreateCmsAppOptions, Currency, CurrencyExchange, Customer, Customer_Contacts, type DataSourceManager, Discount, DiscountRules, type ERPPluginConfig, type ERPPluginInstance, ERPSubmissionService, type EmailData, type EmailJobPayload, type EmailPluginConfig, EmailService, type EmailServiceInterface, EmailTemplateName, EmailTemplateResult, EntityCrudAction, EntityMap$2 as EntityMap, type ErpContactSyncInput, type ErpCreateContactPayload, type ErpJobPayload, type ErpPaidOrderDataSource, type ErpPaidOrderEntityMap, type ExtraPublicWriteRule, type FacebookMeAccountsResponse, type FacebookPageAccount, Form, FormField, FormSubmission, JOB_RUNNER_QUEUE, type CmsAppLike as JobRunnerCmsAppLike, type JobRunnerDeps, type JobRunnerPayload, JobSchedule, JobScheduleRun, KnowledgeBaseChunk, KnowledgeBaseDocument, type LatestArticleFromFeed, LlmAgent, type LlmAgentOptions, type LlmChatOptions, type LlmEmbeddingProvider, type LlmMessage, type LlmPluginConfig, LlmService, type LlmServiceEmbedOptions, type LlmServiceInterface, type LocalStoragePluginConfig, type Logger, Media, MessageTemplate, type MetaGraphMutationResponse, NextAuthUser, Order, OrderAddresses, OrderDiscounts, OrderItem, type OrderPlacedEmailPayload, OrderPlacedLineItem, OtpChallenge, type OtpChannel, type OtpPurpose, Page, PasswordResetToken, Payment, type PaymentIntent, type PaymentPluginConfig, type PaymentServiceInterface, Permission, type PgBossPluginConfig, PgBossService, type PipelineNames, type PluginContext, Product, ProductAttribute, ProductCategory, ProductTax, type PublicThemeSettingsPayload, type QueuePluginConfig, type QueueService, type RenderEmailOptions, type RenderedEmail, RssArticle, RssFeed, type S3StoragePluginConfig, type SendVendorOnboardEmailInput, Seo, type SeoLike, type SeoMetadataOverrides, SessionUser, type SmsJobPayload, type SmsPluginConfig, type SmsProviderChoice, type SmsProviderId, type SmsServiceConfig, type SmsServiceInterface, type SocialMediaPluginConfig, StorageService, Tag, Tax, TemplateContext, User, UserGroup, Vendor, VendorCustomer, VendorUser, Wishlist, WishlistItem, ZIP_MIME_TYPES, allowRateLimit, analyticsPlugin, applyVendorCustomersContactFilter, assertCaptchaOk, assertContactAllowedForVendorOrder, blogGeneratorPlugin, buildBlogMetadataUserPrompt, buildCaptchaPublicConfig, buildCronFromSchedule, buildRssUserPromptFromFeeds, cachePlugin, captchaPlugin, cn, contactIsVendorCustomer, countRecentOtpSends, createCmsApp, createDataSourceManager, createOtpChallenge, createSocialMediaHandlers, emailPlugin, emailTemplates, enrichUserWithVendorContext, ensureScheduleQueueWorker, erpPlugin, fetchSeoBySlug, formatDate, formatDateOnly, formatDateTime, generateNumericOtp, generateSlug, getRssArticleSummaryFromItem, hashOtpCode, hydrateVendorSessionUser, isCustomerTypeContact, isZipMedia, joinRecipientsForSend, linkUnclaimedContactToUser, llmAgentToChatAgentOptions, llmPlugin, loadPublicThemeSettings, loadUserVendorContext, localStoragePlugin, mergeSeoBySlug, metaFetchUserManagedPages, metaPostPageFeed, metaPostPagePhoto, metaResolvePageAccessToken, normalizePhoneE164, parseBlogGeneratorAgentContent, parseBlogGeneratorModelOutput, parseBlogMetadataEnrichmentJson, parseEmailRecipientsFromConfig, parseHfInferenceEmbeddingBody, paymentPlugin, pgBossPlugin, pgBossScheduleNameForId, queueEmail, queueErp, queueErpCreateContactIfEnabled, queueErpPaidOrderForOrderId, queueJobScheduleNow, queueOrderPlacedEmails, queuePlugin, queueSms, queueVendorOnboardEmails, rateLimitCheckoutPost, rateLimitKeyForApiRequest, rateLimitPublicApiIfNeeded, registerEmailQueueProcessor, registerErpQueueProcessor, registerJobRunnerWorker, registerSmsQueueProcessor, relativePathFromMediaParentId, renderEmail, renderLayout, resolveBlogCategoryIdByName, resolvePublicMetadata, resolveVendorIdForContactCheck, s3StoragePlugin, sanitizeMediaFolderPath, sanitizeStorageSegment, seedDefaultAdmin, sendOrderPlacedEmailsAfterConfirmation, sendVendorOnboardEmails, serializeEmailRecipients, shouldRateLimitPublicWrite, smsPlugin, socialMediaPlugin, syncJobScheduleToPgBoss, truncateText, validateScheduleInput, validateSlug, verifyAndConsumeOtpChallenge, verifyOtpCodeHash, withAdminRlsContext, withVendorRlsContext };
3636
+ /** Minimal DB handle for RBAC debug (avoids importing `typeorm` in the auth bundle). */
3637
+ type RbacDebugDataSource = {
3638
+ query: (sql: string, parameters?: unknown[]) => Promise<unknown>;
3639
+ };
3640
+ /** Set `CMS_RBAC_DEBUG=true` in `.env` to log permission decisions (server console). Off by default. */
3641
+ declare function isRbacDebugEnabled(): boolean;
3642
+ declare function logRbac(message: string, data?: Record<string, unknown>): void;
3643
+ declare function summarizeEntityPerms(entityPerms: Record<string, EntityPermissionFlags> | undefined): Record<string, {
3644
+ c: boolean;
3645
+ r: boolean;
3646
+ u: boolean;
3647
+ d: boolean;
3648
+ }>;
3649
+ interface EntityAccessExplanation {
3650
+ allowed: boolean;
3651
+ reason: string;
3652
+ userSnapshot: Record<string, unknown>;
3653
+ }
3654
+ /** Same rules as `sessionHasEntityAccess`, but returns why access was granted or denied. */
3655
+ declare function explainSessionEntityAccess(user: SessionUser | null | undefined, entity: string, action: EntityCrudAction): EntityAccessExplanation;
3656
+ declare function logEntityAccessDecision(dataSource: RbacDebugDataSource | undefined, context: string, user: SessionUser | null | undefined, entity: string, action: EntityCrudAction, extra?: Record<string, unknown>): Promise<void>;
3657
+
3658
+ /** Platform super admin (`user_groups.id = 1` or Administrator group). */
3659
+ declare const SUPER_ADMIN_GROUP_ID = 1;
3660
+ /** Vendor store admin (`user_groups.id = 5` or vendor-linked portal users). */
3661
+ declare const VENDOR_ADMIN_GROUP_ID = 5;
3662
+ declare function isSuperAdmin(user: SessionUser | null | undefined): boolean;
3663
+ declare function isVendorAdmin(user: SessionUser | null | undefined): boolean;
3664
+
3665
+ /**
3666
+ * Ensures the Administrator group has full CRUD on every permissionable entity
3667
+ * for the given entity map. Idempotent: upserts per entity.
3668
+ */
3669
+ declare function seedAdministratorPermissions(dataSource: DataSource, entityMap: Record<string, unknown>): Promise<void>;
3670
+
3671
+ interface CmsMiddlewareRequest {
3672
+ nextUrl: {
3673
+ pathname: string;
3674
+ };
3675
+ url: string;
3676
+ method: string;
3677
+ cookies: {
3678
+ get: (name: string) => {
3679
+ value?: string;
3680
+ } | undefined;
3681
+ };
3682
+ /**
3683
+ * Full Next.js request (e.g. `NextRequest`). When provided, session is resolved via
3684
+ * `getToken()` so chunked `next-auth.session-token.N` cookies work.
3685
+ */
3686
+ req?: Parameters<typeof getToken>[0]['req'];
3687
+ }
3688
+ interface CmsMiddlewareConfig {
3689
+ publicAdminPaths?: string[];
3690
+ publicApiPaths?: string[];
3691
+ /** path -> allowed methods */
3692
+ publicApiMethods?: Record<string, string[]>;
3693
+ signInPath?: string;
3694
+ /** @deprecated Prefer passing `req` on the request; used only when `req` is omitted. */
3695
+ getSessionToken?: (request: CmsMiddlewareRequest) => string | undefined;
3696
+ secret?: string;
3697
+ }
3698
+ /** Default public API paths (no auth). Sites should extend this with their own routes. */
3699
+ declare const defaultPublicApiMethods: Record<string, string[]>;
3700
+ /**
3701
+ * Returns middleware logic. Use from Next.js middleware:
3702
+ * import { createCmsMiddleware } from '@infuro/cms-core';
3703
+ * export async function middleware(request: NextRequest) {
3704
+ * const result = await cmsMiddleware({ ...request fields, req: request });
3705
+ * ...
3706
+ * }
3707
+ * export const config = { matcher: ['/admin/:path*', '/api/:path*'] };
3708
+ */
3709
+ declare function createCmsMiddleware(config?: CmsMiddlewareConfig): (request: CmsMiddlewareRequest) => Promise<{
3710
+ type: "next";
3711
+ } | {
3712
+ type: "redirect";
3713
+ url: string;
3714
+ } | {
3715
+ type: "json";
3716
+ status: number;
3717
+ body: unknown;
3718
+ }>;
3719
+
3720
+ /** Set `CMS_AUTH_DEBUG=true` to log server auth decisions. Off by default (including in development). */
3721
+ declare function isAuthDebugEnabled(): boolean;
3722
+ /** Browser console logs; set `NEXT_PUBLIC_CMS_AUTH_DEBUG=true` to enable. */
3723
+ declare function isAuthDebugClientEnabled(): boolean;
3724
+ declare function logAuth(message: string, data?: Record<string, unknown>): void;
3725
+ declare function logAuthClient(message: string, data?: Record<string, unknown>): void;
3726
+ declare function summarizeSessionUserForLog(user: unknown): Record<string, unknown>;
3727
+ declare function nextAuthCookieDebugInfo(): Record<string, unknown>;
3728
+
3729
+ type VendorOwnerActivation = 'invite' | 'password';
3730
+ interface VendorOnboardHandlersConfig {
3731
+ dataSource: DataSource;
3732
+ entityMap: EntityMap$2;
3733
+ json: (body: unknown, init?: {
3734
+ status?: number;
3735
+ }) => Response;
3736
+ getSessionUser: () => Promise<SessionUser | null>;
3737
+ baseUrl: string;
3738
+ getCms?: () => Promise<{
3739
+ getPlugin: (name: string) => unknown;
3740
+ }>;
3741
+ hashPassword?: (plain: string) => Promise<string>;
3742
+ minPasswordLength?: number;
3743
+ }
3744
+ declare function createVendorOnboardHandlers(config: VendorOnboardHandlersConfig): {
3745
+ /** POST /api/admin/vendors/onboard — create vendor + owner user + vendor_users + invite */
3746
+ onboard(req: Request): Promise<Response>;
3747
+ /** POST /api/admin/vendor/switch — set active vendor in session (JWT update via client) */
3748
+ switchVendor(req: Request): Promise<Response>;
3749
+ /** GET /api/admin/vendor/team */
3750
+ listTeam(): Promise<Response>;
3751
+ /** POST /api/admin/vendor/team — add staff to vendor */
3752
+ addTeamMember(req: Request): Promise<Response>;
3753
+ /** PATCH /api/admin/vendor/team/:userId — change member store role */
3754
+ updateTeamMemberRole(req: Request, userIdStr: string): Promise<Response>;
3755
+ /** DELETE /api/admin/vendor/team/:userId */
3756
+ removeTeamMember(_req: Request, userIdStr: string): Promise<Response>;
3757
+ };
3758
+
3759
+ interface StorefrontOtpFlags {
3760
+ login?: boolean;
3761
+ verifyEmail?: boolean;
3762
+ verifyPhone?: boolean;
3763
+ }
3764
+ interface StorefrontApiConfig {
3765
+ dataSource: DataSource;
3766
+ entityMap: EntityMap$2;
3767
+ json: (body: unknown, init?: {
3768
+ status?: number;
3769
+ headers?: HeadersInit;
3770
+ }) => Response;
3771
+ getSessionUser: () => Promise<SessionUser | null>;
3772
+ guestCookieName?: string;
3773
+ /** Required for POST storefront/register */
3774
+ hashPassword?: (plain: string) => Promise<string>;
3775
+ /** When set, new registrations are blocked until email is verified and a signup email is sent. */
3776
+ getCms?: () => Promise<{
3777
+ getPlugin: (name: string) => unknown;
3778
+ }>;
3779
+ getCompanyDetails?: () => Promise<CompanyDetails>;
3780
+ /** Origin for verify links (e.g. process.env.NEXTAUTH_URL). Required with getCms for verification URLs. */
3781
+ publicSiteUrl?: string;
3782
+ /** When a flag is true, the corresponding OTP storefront route is enabled. */
3783
+ otpFlags?: StorefrontOtpFlags;
3784
+ /** Defaults to OTP_PEPPER or NEXTAUTH_SECRET. */
3785
+ otpPepper?: string;
3786
+ defaultPhoneCountryCode?: string;
3787
+ /** When false, login OTP send accepts email only (no phone). Default true. */
3788
+ otpAllowPhoneLogin?: boolean;
3789
+ }
3790
+ declare function createStorefrontApiHandler(config: StorefrontApiConfig): {
3791
+ handle(method: string, path: string[], req: Request): Promise<Response>;
3792
+ };
3793
+
3794
+ interface AdminNavItem {
3795
+ href: string;
3796
+ label: string;
3797
+ icon?: string;
3798
+ }
3799
+ declare const DEFAULT_ADMIN_NAV: AdminNavItem[];
3800
+
3801
+ interface EnsureMessagingPluginsOptions {
3802
+ dataSource: DataSource;
3803
+ entityMap: EntityMap$2;
3804
+ config?: Record<string, string>;
3805
+ /** Decrypts `configs.encrypted` rows (defaults to SETTINGS_ENCRYPTION_KEY or NEXTAUTH_SECRET). */
3806
+ encryptionKey?: string;
3807
+ logger?: Logger;
3808
+ }
3809
+ /** Minimal CMS handle (matches `CmsGetter` in cms-api-handler). */
3810
+ interface MessagingCmsLike {
3811
+ getPlugin(name: string): unknown;
3812
+ dataSource?: unknown;
3813
+ }
3814
+ /** Same key used by Plugins → settings PUT for encrypted secrets (e.g. WhatsApp access token). */
3815
+ declare function resolveSettingsEncryptionKey(config?: Record<string, string>): string | undefined;
3816
+ declare function loadSettingsGroupFromDb(dataSource: DataSource, entityMap: EntityMap$2, group: string, encryptionKey?: string): Promise<Record<string, string>>;
3817
+ declare function createMessageTemplateRowLoader(dataSource: DataSource, entityMap: EntityMap$2): MessageTemplateRowLoader;
3818
+ /** Register email + WhatsApp queue processors when a queue plugin is present. */
3819
+ declare function registerMessagingQueueProcessors(cms: CmsApp): void;
3820
+ /**
3821
+ * Ensures queue, email, and WhatsApp plugins exist on the CMS app (lazy overlay).
3822
+ * Consumer apps that omit `whatsappPlugin()` / `queuePlugin()` still get order notifications when env/DB is configured.
3823
+ */
3824
+ declare function ensureMessagingPluginsOnCms(base: MessagingCmsLike, options: EnsureMessagingPluginsOptions): Promise<CmsApp>;
3825
+ /** Cached wrapper so messaging plugins are initialized once per process. */
3826
+ declare function wrapGetCmsWithMessaging(getCms: () => Promise<MessagingCmsLike>, options: EnsureMessagingPluginsOptions): () => Promise<CmsApp>;
3827
+ /** Standard messaging plugins for `createCmsApp({ plugins: [...] })`. */
3828
+ declare function messagingPlugins(options: EnsureMessagingPluginsOptions): CmsPlugin[];
3829
+ type CreateCmsAppWithMessagingOptions = CreateCmsAppOptions & EnsureMessagingPluginsOptions;
3830
+ /** `createCmsApp` + messaging plugins + queue processor registration. */
3831
+ declare function createCmsAppWithMessaging(options: CreateCmsAppWithMessagingOptions): Promise<CmsApp>;
3832
+
3833
+ export { ADMIN_GROUP_NAME, Address, type AdminNavItem, type AnalyticsHandlerConfig, type AnalyticsPluginConfig, Attendee, Attribute, type AuthHandlersConfig, type AuthHelpers, type AuthorizeOtpInput, BLOG_GENERATOR_AGENT_NAME, BLOG_GENERATOR_DEFAULT_SYSTEM_INSTRUCTION, BLOG_GENERATOR_DEFAULT_VALIDATION_RULES, BLOG_GENERATOR_LLM_AGENT_SLUG, BLOG_GENERATOR_MARKDOWN_ARTICLE_SEPARATOR, BLOG_METADATA_ENRICHER_AGENT_NAME, BLOG_METADATA_ENRICHER_DEFAULT_SYSTEM_INSTRUCTION, BLOG_METADATA_ENRICHER_DEFAULT_VALIDATION_RULES, BLOG_METADATA_ENRICHER_LLM_AGENT_SLUG, Blog, type BlogBySlugConfig, type BlogGeneratorBlogDraft, type BlogGeneratorDraftParseMode, type BlogGeneratorPluginConfig, type BlogGeneratorSeoDraft, BlogGeneratorService, Brand, CMS_ENTITY_MAP, type CachePluginConfig, type CacheService, type CaptchaProviderId, type CaptchaPublicConfig, CaptchaService, type CaptchaVerifyResult, Cart, CartItem, Category, type ChangePasswordConfig, ChatConversation, ChatMessage, type ChatPublicConfig, type CmsApiHandlerConfig, type CmsApp, type CmsGetter, type CmsMiddlewareConfig, type CmsMiddlewareRequest, type CmsPlugin, Collection, Combo, ComboItem, Comment, type CompanyDetails, Config, Contact, type CreateCmsAppOptions, type CreateCmsAppWithMessagingOptions, type CrudHandlerOptions, Currency, CurrencyExchange, Customer, Customer_Contacts, DEFAULT_ADMIN_NAV, DEFAULT_ORDER_NOTIFICATION_TRIGGER_SEEDS, type DashboardStatsConfig, type DataSourceManager, Discount, DiscountRules, type ERPPluginConfig, type ERPPluginInstance, ERPSubmissionService, EVENT_ORDER_MESSAGE_TEMPLATE_DEFAULTS, EVENT_ORDER_TEMPLATE_KEY, EVENT_ORDER_TEMPLATE_VARIABLES, type EcommerceAnalyticsConfig, type EmailData, type EmailJobPayload, type EmailPluginConfig, EmailService, type EmailServiceInterface, type EmailTemplateName, type EmailTemplateResult, type EmitOrderNotificationTriggerDeps, type EnsureCustomerUserInput, type EnsureMessagingPluginsOptions, type EnsureVendorCustomerDetails, type EntityCrudAction, type EntityMap$2 as EntityMap, type EntityPermissionFlags, type ErpContactSyncInput, type ErpCreateContactPayload, type ErpJobPayload, type ErpPaidOrderDataSource, type ErpPaidOrderEntityMap, Event, type EventOrderMessageTemplateHandlersConfig, type EventOrderNotificationChannel, type EventOrderNotificationTemplates, type EventOrderTemplateOverride, EventProduct, type ExtraPublicWriteRule, type FacebookMeAccountsResponse, type FacebookPageAccount, type ForgotPasswordConfig, Form, type FormBySlugConfig, FormField, FormSubmission, type GetPublicSettingsGroupConfig, type GetPublicSettingsGroupDataSource, type GetSession, type InviteAcceptConfig, JOB_RUNNER_QUEUE, type CmsAppLike as JobRunnerCmsAppLike, type JobRunnerDeps, type JobRunnerPayload, JobSchedule, type JobScheduleApiConfig, JobScheduleRun, KNOWN_NOTIFICATION_TRIGGERS, KnowledgeBaseChunk, KnowledgeBaseDocument, type LatestArticleFromFeed, LlmAgent, type LlmAgentKnowledgeApiConfig, type LlmAgentOptions, type LlmAgentValidationRulesJson, type LlmChatOptions, type LlmEmbeddingProvider, type LlmMessage, type LlmPluginConfig, LlmService, type LlmServiceEmbedOptions, type LlmServiceInterface, type LocalStoragePluginConfig, type Logger, Media, MessageTemplate, type MetaGraphMutationResponse, type NextAuthOptionsConfig, type NextAuthUser, OPEN_ENDPOINTS, ORDER_NOTIFICATION_TRIGGERS, Order, OrderAddresses, OrderDiscounts, OrderItem, OrderNotificationTrigger, type OrderNotificationTriggerKey, type OrderPlacedEmailPayload, type OrderPlacedLineItem, type OrderTriggerPayload, OtpChallenge, type OtpChannel, type OtpPurpose, PERMISSION_REQUIRED_ENDPOINTS, Page, type ParsedLlmAgentValidation, PasswordResetToken, Payment, type PaymentIntent, type PaymentPluginConfig, type PaymentServiceInterface, Permission, type PgBossPluginConfig, PgBossService, type PipelineNames, type PluginContext, Product, ProductAttribute, ProductCategory, ProductConfig, ProductVariant, type PublicThemeSettingsPayload, type QueuePluginConfig, type QueueService, RBAC_ADMIN_ONLY_ENTITIES, type RefundCalculationResult, RefundPolicy, type RefundPolicyLike, type RefundPolicyTier, RefundRequest, type RenderEmailOptions, type RenderedEmail, RssArticle, RssFeed, type S3StoragePluginConfig, SUPER_ADMIN_GROUP_ID, type SendVendorOnboardEmailInput, Seo, type SeoLike, type SeoMetadataOverrides, type SessionUser, type SetPasswordConfig, type SettingsApiConfig, type SmsJobPayload, type SmsPluginConfig, type SmsProviderChoice, type SmsProviderId, type SmsServiceConfig, type SmsServiceInterface, type SocialLinkItem, type SocialMediaPluginConfig, type StorageService, type StorefrontApiConfig, type StorefrontOtpFlags, Tag, Tax, type TemplateContext, type UploadHandlerConfig, User, type UserAuthApiConfig, type UserAvatarConfig, UserGroup, type UserProfileConfig, type UsersApiConfig, VENDOR_ADMIN_GROUP_ID, VENDOR_OWNER_GROUP_NAME, VENDOR_SCOPED_STORE_ENTITIES, VENDOR_STORE_RBAC_ENTITIES, Vendor, VendorCustomer, type VendorDashboardConfig, type VendorOnboardHandlersConfig, type VendorOwnerActivation, VendorRole, VendorRolePermission, VendorUser, type WhatsAppJobPayload, type WhatsAppPluginConfig, type WhatsAppServiceConfig, type WhatsAppServiceInterface, WhatsappTriggerBinding, Wishlist, WishlistItem, ZIP_MIME_TYPES, allowRateLimit, analyticsPlugin, applyVendorCustomersContactFilter, assertCaptchaOk, assertContactAllowedForVendorOrder, blogGeneratorPlugin, buildBlogMetadataUserPrompt, buildCaptchaPublicConfig, buildCronFromSchedule, buildEventOrderTemplateVariables, buildRssUserPromptFromFeeds, cachePlugin, calculateOrderRefundPreview, calculateRefundFromPolicy, canManageRoles, canManageVendorRoles, canManageVendorTeam, canOnboardVendors, captchaPlugin, checkEventsEnabled, checkMultiVendorEnabled, cn, contactIsVendorCustomer, countRecentOtpSends, createAnalyticsHandlers, createAuthHelpers, createBlogBySlugHandler, createChangePasswordHandler, createCmsApiHandler, createCmsApp, createCmsAppWithMessaging, createCmsAuthBundle, createCmsMiddleware, createCrudByIdHandler, createCrudHandler, createDashboardStatsHandler, createDataSourceManager, createEcommerceAnalyticsHandler, createEventOrderMessageTemplateHandlers, createForgotPasswordHandler, createFormBySlugHandler, createInviteAcceptHandler, createJobScheduleHandlers, createLlmAgentKnowledgeHandlers, createMediaZipExtractHandler, createMessageTemplateRowLoader, createOtpChallenge, createSetPasswordHandler, createSettingsApiHandlers, createSocialMediaHandlers, createStorefrontApiHandler, createUploadHandler, createUserAuthApiRouter, createUserAvatarHandler, createUserProfileHandler, createUsersApiHandlers, createVendorDashboardHandler, createVendorOnboardHandlers, customerPhoneForUser, daysBeforeEventStart, defaultPublicApiMethods, describeEventTierPolicy, emailPlugin, emailTemplates, emitOrderNotificationTrigger, enrichUserWithVendorContext, ensureCustomerForUser, ensureMessagingPluginsOnCms, ensureScheduleQueueWorker, ensureVendorCustomerForOrderContact, erpPlugin, explainSessionEntityAccess, fetchSeoBySlug, findActiveRefundPolicyForVendor, fireOrderNotificationTrigger, formatDate, formatDateOnly, formatDateTime, formatTierRange, generateNumericOtp, generateSlug, getCompanyDetailsFromSettings, getNextAuthOptions, getPermissionableEntityKeys, getPublicSettingsGroup, getRequiredPermission, getRssArticleSummaryFromItem, getStorefrontNextAuthOptions, hasEntityPermission, hashOtpCode, hydrateVendorSessionUser, initWhatsappTriggerDispatcher, invalidateEventsCache, invalidateMultiVendorCache, isAuthDebugClientEnabled, isAuthDebugEnabled, isCustomerTypeContact, isOpenEndpoint, isPlatformAdministrator, isPublicMethod, isRbacDebugEnabled, isSuperAdmin, isSuperAdminGroupName, isVendorAdmin, isVendorGroupName, isVendorOwner, isVendorPortalUser, isVendorStaff, isZipMedia, joinRecipientsForSend, linkUnclaimedContactToUser, llmAgentToChatAgentOptions, llmPlugin, loadPublicThemeSettings, loadSettingsGroupFromDb, loadUserVendorContext, localStoragePlugin, logAuth, logAuthClient, logEntityAccessDecision, logRbac, mergeEmailLayoutCompanyDetails, mergeGuardrailsIntoSystemPrompt, mergeSeoBySlug, messagingPlugins, metaFetchUserManagedPages, metaPostPageFeed, metaPostPagePhoto, metaResolvePageAccessToken, nextAuthCookieDebugInfo, normalizePhoneE164, normalizeRefundTiers, notificationTriggerEmitter, overlayCmsPlugins, parseBlogGeneratorAgentContent, parseBlogGeneratorModelOutput, parseBlogMetadataEnrichmentJson, parseEmailRecipientsFromConfig, parseHfInferenceEmbeddingBody, parseLlmAgentValidationRules, paymentPlugin, permissionRowsToRecord, pgBossPlugin, pgBossScheduleNameForId, queueEmail, queueErp, queueErpCreateContactIfEnabled, queueErpPaidOrderForOrderId, queueJobScheduleNow, queueOrderPlacedEmails, queuePlugin, queueSms, queueVendorOnboardEmails, queueWhatsApp, rateLimitCheckoutPost, rateLimitKeyForApiRequest, rateLimitPublicApiIfNeeded, registerEmailQueueProcessor, registerErpQueueProcessor, registerJobRunnerWorker, registerMessagingQueueProcessors, registerSmsQueueProcessor, registerWhatsAppQueueProcessor, relativePathFromMediaParentId, renderEmail, renderLayout, resendOrderNotification, resolveBlogCategoryIdByName, resolveEventOrderTemplate, resolvePublicMetadata, resolveSettingsEncryptionKey, resolveVendorIdForContactCheck, resolveVendorScopeFromSessionUser, s3StoragePlugin, sanitizeMediaFolderPath, sanitizeStorageSegment, seedAdministratorPermissions, seedDefaultAdmin, sendOrderPlacedEmailsAfterConfirmation, sendVendorOnboardEmails, serializeEmailRecipients, sessionHasEntityAccess, shouldRateLimitPublicWrite, simpleDecrypt, simpleEncrypt, smsPlugin, socialMediaPlugin, summarizeEntityPerms, summarizeSessionUserForLog, syncJobScheduleToPgBoss, truncateText, validateRefundTiers, validateScheduleInput, validateSlug, validateUserMessageAgainstAgentRules, validateUserMessageAgainstStructuredRules, vendorPortalFlagsFromUser, verifyAndConsumeOtpChallenge, verifyOtpCodeHash, whatsappPlugin, withAdminRlsContext, withVendorRlsContext, wrapGetCmsWithMessaging };