@odla-ai/crm 0.9.2 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -764,7 +764,7 @@ declare function lintTemplate(template: string, knownVars: readonly string[]): {
764
764
  unused: string[];
765
765
  };
766
766
 
767
- /** Cast a raw row to {@link CrmRecord}, defaulting the json fields. */
767
+ /** Decode a raw row to {@link CrmRecord}, normalizing declared dates and defaulting JSON fields. */
768
768
  declare function rowToRecord(row: CrmRow): CrmRecord;
769
769
  /** Load one record by id, or null. */
770
770
  declare function getRecord(deps: CrmDeps, id: string): Promise<CrmRecord | null>;
@@ -781,13 +781,21 @@ declare function listRecords(deps: CrmDeps, params: CrmListParams): Promise<{
781
781
  /** Create a record of `type` from custom-field input. Also creates (or
782
782
  * upserts) the primary email contact channel when the type declares an
783
783
  * `emailField`. New records rank at `now` so manual order defaults to
784
- * creation order. */
784
+ * creation order. `stage: null` explicitly keeps a record outside its pipeline;
785
+ * omission retains the configured initial stage. An explicit `id` is create-only
786
+ * (atomically guarded), for convergent server projections. */
785
787
  declare function createRecord(deps: CrmDeps, opts: {
786
788
  type: string;
787
789
  input: Record<string, unknown>;
788
790
  ownerId?: string;
789
- stage?: string;
791
+ stage?: string | null;
790
792
  mutationId?: string;
793
+ id?: string;
794
+ guards?: CrmTransactGuard[];
795
+ emailConsent?: {
796
+ state: ConsentState;
797
+ source: string;
798
+ };
791
799
  }): Promise<{
792
800
  id: string;
793
801
  duplicate: boolean;
@@ -1020,7 +1028,10 @@ declare function listChannels(deps: CrmDeps, recordId: string): Promise<CrmConta
1020
1028
  * demote any other primary, or — with `email: null` — just demote. Returns
1021
1029
  * the ops plus the `emailStatus` the record should fold to.
1022
1030
  */
1023
- declare function emailChannelOps(deps: CrmDeps, recordId: string, email: string | null, existing: readonly CrmContactChannel[]): {
1031
+ declare function emailChannelOps(deps: CrmDeps, recordId: string, email: string | null, existing: readonly CrmContactChannel[], initialConsent?: {
1032
+ state: ConsentState;
1033
+ source: string;
1034
+ }): {
1024
1035
  ops: CrmOp[];
1025
1036
  emailStatus: EmailStatus;
1026
1037
  };
@@ -1130,7 +1141,7 @@ interface SendEmailOpts {
1130
1141
  baseUrl: string;
1131
1142
  /** Route mount point for the unsubscribe link. Default "/api/crm". */
1132
1143
  basePath?: string;
1133
- /** Admin test-send: bypasses the enabled flag — NEVER the consent gate. */
1144
+ /** Admin test-send: permits an explicitly disabled template, but never bypasses copy validation or consent. */
1134
1145
  force?: boolean;
1135
1146
  }
1136
1147
  /** What happened to the send — delivered, gated, logged, or failed. */
@@ -1142,7 +1153,8 @@ interface SendEmailResult {
1142
1153
  }
1143
1154
  /**
1144
1155
  * Render and send one templated email to a record's contact channel, with
1145
- * consent gating, dedupe, dev redirection, and an unconditional audit row.
1156
+ * copy validation, explicit enablement, consent gating, dedupe, dev redirection,
1157
+ * and audit rows for transport attempts. Incomplete or internal copy never reaches transport.
1146
1158
  * Marketing-class sends get `{{unsubscribeUrl}}` plus RFC 8058 one-click
1147
1159
  * headers automatically.
1148
1160
  */
@@ -1350,7 +1362,7 @@ declare class CrmClient {
1350
1362
  type: string;
1351
1363
  input: Record<string, unknown>;
1352
1364
  ownerId?: string;
1353
- stage?: string;
1365
+ stage?: string | null;
1354
1366
  mutationId?: string;
1355
1367
  }): Promise<{
1356
1368
  id: string;
@@ -1554,4 +1566,28 @@ declare const crmIntegration: CrmIntegrationDescriptor;
1554
1566
  */
1555
1567
  declare function createCrmIntegration(crm: Crm, options?: CrmIntegrationOptions): CrmIntegrationDescriptor;
1556
1568
 
1557
- export { ACTIVITY_KINDS, type ActivityKind, type AttrType, type BillingEvent, type BillingProvider, CONFIG_KEY, CONSENT_STATES, CRM_DISCUSSION_REFERENCE_KINDS, CRM_NS, CRM_RULES, CRM_SCHEMA, CRM_SLOTS, type CompiledList, type ConfigPatch, type ConsentEvent, type ConsentOutcome, type ConsentState, type Crm, type CrmActivity, type CrmActor, type CrmAggregateResult, type CrmAggregateSpec, type CrmAttrs, CrmClient, type CrmClientOptions, type CrmConfig, type CrmConfigRow, type CrmContactChannel, type CrmDb, type CrmDeps, type CrmDiscussionReference, type CrmDiscussionReferenceActor, type CrmDiscussionReferenceKind, type CrmDiscussionReferenceTarget, type CrmEmailLogRow, type CrmEmailSender, type CrmEntityRef, CrmInputError, type CrmIntegrationDescriptor, type CrmIntegrationOptions, type CrmIntegrationProbe, type CrmIntegrationSeed, type CrmLink, type CrmListParams, type CrmLookup, CrmNotFoundError, type CrmOp, type CrmQuery, type CrmRecord, type CrmRecordDelivery, type CrmRecordOrigin, type CrmResult, type CrmRouteOpts, type CrmRow, type CrmRule, type CrmRules, type CrmScalar, type CrmSlot, type CrmSort, type CrmTag, type CrmTransactGuard, type CrmView, DEFAULT_LIMIT, EMAIL_STATUSES, type EmailStatus, type FieldCondition, type FieldConditions, type FieldDef, type FieldFilter, type FieldState, type FieldType, MAX_LIMIT, type PipelineDef, type PreparedWrite, RANK_EPSILON, RANK_STEP, type RelationDef, SORTABLE_COLUMNS, type SendEmailOpts, type SendEmailResult, type SerializedAttr, type SerializedEntity, type SerializedLink, type SerializedLinkEnd, type SerializedSchema, type StageDef, type StoredTemplate, type SubscriptionSnapshot, TASK_STATUSES, type TaskStatus, type TemplateSpec, type TypeDef, type TypeFacets, type TypeSummary, type ViewFilters, type ViewSpec, addActivity, addLink, addTag, applyConsent, applyConsentEvent, assertFieldCondition, canEmail, canTransition, channelKey, compileList, composeCrmConfigs, createCrmIntegration, createCrmRoutes, createRecord, crmDiscussionReferenceHref, crmDiscussionReferenceId, crmIntegration, crmRules, defaultTemplates, defineCrm, deleteView, emailChannelOps, evaluateFieldCondition, foldEmailStatus, formatCrmDiscussionReference, getConfig, getRecord, getRecordByOrigin, getRecordOrigin, initialStage, linkIdentity, lintTemplate, listActivities, listChannels, listEmailLog, listLinks, listRecordDeliveries, listRecordOrigins, listRecords, listTags, listTasks, listViews, mustGetRecord, needsRebalance, normalizeTag, parseCrmDiscussionReference, prepare, rankBetween, rebalancePlan, rebalanceRanks, recordCanEmail, recordDeliveryAttempt, recordDeliveryKey, recordOriginKey, removeLink, removeTag, renderTemplate, resolveDeps, resolveFieldState, resolveFieldStates, resolveSortColumn, rowToRecord, saveConfig, saveView, searchTextFor, sendTemplatedEmail, setArchived, setRank, setStage, stageIndexOf, templateVars, typeSummary, updateRecord, updateTask, updateView, upsertRecordOrigin };
1569
+ /** One actionable problem with email copy or the data needed to render it. */
1570
+ interface EmailCopyIssue {
1571
+ code: string;
1572
+ message: string;
1573
+ variable?: string;
1574
+ }
1575
+ /** A display name suitable for membership mail, never a missing name or a provider identifier. */
1576
+ declare function isEmailTierName(value: unknown, id?: string): value is string;
1577
+ /** Variables and concrete data to check. Omit values when auditing saved copy before an event occurs. */
1578
+ interface EmailCopyValidation {
1579
+ allowedVariables?: readonly string[];
1580
+ optionalVariables?: readonly string[];
1581
+ requiredVariables?: readonly string[];
1582
+ values?: Record<string, string>;
1583
+ tierId?: string;
1584
+ }
1585
+ /** Validate saved copy and, when supplied, its actual event data. Does not render, store, or send mail.
1586
+ * Unknown tokens, missing required values, explicit internal draft notes and invalid tier names fail closed.
1587
+ * Optional values must be named by the event contract; arbitrary unknown placeholders never become blanks. */
1588
+ declare function validateEmailCopy(copy: {
1589
+ subject?: unknown;
1590
+ text?: unknown;
1591
+ }, options?: EmailCopyValidation): EmailCopyIssue[];
1592
+
1593
+ export { ACTIVITY_KINDS, type ActivityKind, type AttrType, type BillingEvent, type BillingProvider, CONFIG_KEY, CONSENT_STATES, CRM_DISCUSSION_REFERENCE_KINDS, CRM_NS, CRM_RULES, CRM_SCHEMA, CRM_SLOTS, type CompiledList, type ConfigPatch, type ConsentEvent, type ConsentOutcome, type ConsentState, type Crm, type CrmActivity, type CrmActor, type CrmAggregateResult, type CrmAggregateSpec, type CrmAttrs, CrmClient, type CrmClientOptions, type CrmConfig, type CrmConfigRow, type CrmContactChannel, type CrmDb, type CrmDeps, type CrmDiscussionReference, type CrmDiscussionReferenceActor, type CrmDiscussionReferenceKind, type CrmDiscussionReferenceTarget, type CrmEmailLogRow, type CrmEmailSender, type CrmEntityRef, CrmInputError, type CrmIntegrationDescriptor, type CrmIntegrationOptions, type CrmIntegrationProbe, type CrmIntegrationSeed, type CrmLink, type CrmListParams, type CrmLookup, CrmNotFoundError, type CrmOp, type CrmQuery, type CrmRecord, type CrmRecordDelivery, type CrmRecordOrigin, type CrmResult, type CrmRouteOpts, type CrmRow, type CrmRule, type CrmRules, type CrmScalar, type CrmSlot, type CrmSort, type CrmTag, type CrmTransactGuard, type CrmView, DEFAULT_LIMIT, EMAIL_STATUSES, type EmailCopyIssue, type EmailCopyValidation, type EmailStatus, type FieldCondition, type FieldConditions, type FieldDef, type FieldFilter, type FieldState, type FieldType, MAX_LIMIT, type PipelineDef, type PreparedWrite, RANK_EPSILON, RANK_STEP, type RelationDef, SORTABLE_COLUMNS, type SendEmailOpts, type SendEmailResult, type SerializedAttr, type SerializedEntity, type SerializedLink, type SerializedLinkEnd, type SerializedSchema, type StageDef, type StoredTemplate, type SubscriptionSnapshot, TASK_STATUSES, type TaskStatus, type TemplateSpec, type TypeDef, type TypeFacets, type TypeSummary, type ViewFilters, type ViewSpec, addActivity, addLink, addTag, applyConsent, applyConsentEvent, assertFieldCondition, canEmail, canTransition, channelKey, compileList, composeCrmConfigs, createCrmIntegration, createCrmRoutes, createRecord, crmDiscussionReferenceHref, crmDiscussionReferenceId, crmIntegration, crmRules, defaultTemplates, defineCrm, deleteView, emailChannelOps, evaluateFieldCondition, foldEmailStatus, formatCrmDiscussionReference, getConfig, getRecord, getRecordByOrigin, getRecordOrigin, initialStage, isEmailTierName, linkIdentity, lintTemplate, listActivities, listChannels, listEmailLog, listLinks, listRecordDeliveries, listRecordOrigins, listRecords, listTags, listTasks, listViews, mustGetRecord, needsRebalance, normalizeTag, parseCrmDiscussionReference, prepare, rankBetween, rebalancePlan, rebalanceRanks, recordCanEmail, recordDeliveryAttempt, recordDeliveryKey, recordOriginKey, removeLink, removeTag, renderTemplate, resolveDeps, resolveFieldState, resolveFieldStates, resolveSortColumn, rowToRecord, saveConfig, saveView, searchTextFor, sendTemplatedEmail, setArchived, setRank, setStage, stageIndexOf, templateVars, typeSummary, updateRecord, updateTask, updateView, upsertRecordOrigin, validateEmailCopy };
package/dist/index.d.ts CHANGED
@@ -764,7 +764,7 @@ declare function lintTemplate(template: string, knownVars: readonly string[]): {
764
764
  unused: string[];
765
765
  };
766
766
 
767
- /** Cast a raw row to {@link CrmRecord}, defaulting the json fields. */
767
+ /** Decode a raw row to {@link CrmRecord}, normalizing declared dates and defaulting JSON fields. */
768
768
  declare function rowToRecord(row: CrmRow): CrmRecord;
769
769
  /** Load one record by id, or null. */
770
770
  declare function getRecord(deps: CrmDeps, id: string): Promise<CrmRecord | null>;
@@ -781,13 +781,21 @@ declare function listRecords(deps: CrmDeps, params: CrmListParams): Promise<{
781
781
  /** Create a record of `type` from custom-field input. Also creates (or
782
782
  * upserts) the primary email contact channel when the type declares an
783
783
  * `emailField`. New records rank at `now` so manual order defaults to
784
- * creation order. */
784
+ * creation order. `stage: null` explicitly keeps a record outside its pipeline;
785
+ * omission retains the configured initial stage. An explicit `id` is create-only
786
+ * (atomically guarded), for convergent server projections. */
785
787
  declare function createRecord(deps: CrmDeps, opts: {
786
788
  type: string;
787
789
  input: Record<string, unknown>;
788
790
  ownerId?: string;
789
- stage?: string;
791
+ stage?: string | null;
790
792
  mutationId?: string;
793
+ id?: string;
794
+ guards?: CrmTransactGuard[];
795
+ emailConsent?: {
796
+ state: ConsentState;
797
+ source: string;
798
+ };
791
799
  }): Promise<{
792
800
  id: string;
793
801
  duplicate: boolean;
@@ -1020,7 +1028,10 @@ declare function listChannels(deps: CrmDeps, recordId: string): Promise<CrmConta
1020
1028
  * demote any other primary, or — with `email: null` — just demote. Returns
1021
1029
  * the ops plus the `emailStatus` the record should fold to.
1022
1030
  */
1023
- declare function emailChannelOps(deps: CrmDeps, recordId: string, email: string | null, existing: readonly CrmContactChannel[]): {
1031
+ declare function emailChannelOps(deps: CrmDeps, recordId: string, email: string | null, existing: readonly CrmContactChannel[], initialConsent?: {
1032
+ state: ConsentState;
1033
+ source: string;
1034
+ }): {
1024
1035
  ops: CrmOp[];
1025
1036
  emailStatus: EmailStatus;
1026
1037
  };
@@ -1130,7 +1141,7 @@ interface SendEmailOpts {
1130
1141
  baseUrl: string;
1131
1142
  /** Route mount point for the unsubscribe link. Default "/api/crm". */
1132
1143
  basePath?: string;
1133
- /** Admin test-send: bypasses the enabled flag — NEVER the consent gate. */
1144
+ /** Admin test-send: permits an explicitly disabled template, but never bypasses copy validation or consent. */
1134
1145
  force?: boolean;
1135
1146
  }
1136
1147
  /** What happened to the send — delivered, gated, logged, or failed. */
@@ -1142,7 +1153,8 @@ interface SendEmailResult {
1142
1153
  }
1143
1154
  /**
1144
1155
  * Render and send one templated email to a record's contact channel, with
1145
- * consent gating, dedupe, dev redirection, and an unconditional audit row.
1156
+ * copy validation, explicit enablement, consent gating, dedupe, dev redirection,
1157
+ * and audit rows for transport attempts. Incomplete or internal copy never reaches transport.
1146
1158
  * Marketing-class sends get `{{unsubscribeUrl}}` plus RFC 8058 one-click
1147
1159
  * headers automatically.
1148
1160
  */
@@ -1350,7 +1362,7 @@ declare class CrmClient {
1350
1362
  type: string;
1351
1363
  input: Record<string, unknown>;
1352
1364
  ownerId?: string;
1353
- stage?: string;
1365
+ stage?: string | null;
1354
1366
  mutationId?: string;
1355
1367
  }): Promise<{
1356
1368
  id: string;
@@ -1554,4 +1566,28 @@ declare const crmIntegration: CrmIntegrationDescriptor;
1554
1566
  */
1555
1567
  declare function createCrmIntegration(crm: Crm, options?: CrmIntegrationOptions): CrmIntegrationDescriptor;
1556
1568
 
1557
- export { ACTIVITY_KINDS, type ActivityKind, type AttrType, type BillingEvent, type BillingProvider, CONFIG_KEY, CONSENT_STATES, CRM_DISCUSSION_REFERENCE_KINDS, CRM_NS, CRM_RULES, CRM_SCHEMA, CRM_SLOTS, type CompiledList, type ConfigPatch, type ConsentEvent, type ConsentOutcome, type ConsentState, type Crm, type CrmActivity, type CrmActor, type CrmAggregateResult, type CrmAggregateSpec, type CrmAttrs, CrmClient, type CrmClientOptions, type CrmConfig, type CrmConfigRow, type CrmContactChannel, type CrmDb, type CrmDeps, type CrmDiscussionReference, type CrmDiscussionReferenceActor, type CrmDiscussionReferenceKind, type CrmDiscussionReferenceTarget, type CrmEmailLogRow, type CrmEmailSender, type CrmEntityRef, CrmInputError, type CrmIntegrationDescriptor, type CrmIntegrationOptions, type CrmIntegrationProbe, type CrmIntegrationSeed, type CrmLink, type CrmListParams, type CrmLookup, CrmNotFoundError, type CrmOp, type CrmQuery, type CrmRecord, type CrmRecordDelivery, type CrmRecordOrigin, type CrmResult, type CrmRouteOpts, type CrmRow, type CrmRule, type CrmRules, type CrmScalar, type CrmSlot, type CrmSort, type CrmTag, type CrmTransactGuard, type CrmView, DEFAULT_LIMIT, EMAIL_STATUSES, type EmailStatus, type FieldCondition, type FieldConditions, type FieldDef, type FieldFilter, type FieldState, type FieldType, MAX_LIMIT, type PipelineDef, type PreparedWrite, RANK_EPSILON, RANK_STEP, type RelationDef, SORTABLE_COLUMNS, type SendEmailOpts, type SendEmailResult, type SerializedAttr, type SerializedEntity, type SerializedLink, type SerializedLinkEnd, type SerializedSchema, type StageDef, type StoredTemplate, type SubscriptionSnapshot, TASK_STATUSES, type TaskStatus, type TemplateSpec, type TypeDef, type TypeFacets, type TypeSummary, type ViewFilters, type ViewSpec, addActivity, addLink, addTag, applyConsent, applyConsentEvent, assertFieldCondition, canEmail, canTransition, channelKey, compileList, composeCrmConfigs, createCrmIntegration, createCrmRoutes, createRecord, crmDiscussionReferenceHref, crmDiscussionReferenceId, crmIntegration, crmRules, defaultTemplates, defineCrm, deleteView, emailChannelOps, evaluateFieldCondition, foldEmailStatus, formatCrmDiscussionReference, getConfig, getRecord, getRecordByOrigin, getRecordOrigin, initialStage, linkIdentity, lintTemplate, listActivities, listChannels, listEmailLog, listLinks, listRecordDeliveries, listRecordOrigins, listRecords, listTags, listTasks, listViews, mustGetRecord, needsRebalance, normalizeTag, parseCrmDiscussionReference, prepare, rankBetween, rebalancePlan, rebalanceRanks, recordCanEmail, recordDeliveryAttempt, recordDeliveryKey, recordOriginKey, removeLink, removeTag, renderTemplate, resolveDeps, resolveFieldState, resolveFieldStates, resolveSortColumn, rowToRecord, saveConfig, saveView, searchTextFor, sendTemplatedEmail, setArchived, setRank, setStage, stageIndexOf, templateVars, typeSummary, updateRecord, updateTask, updateView, upsertRecordOrigin };
1569
+ /** One actionable problem with email copy or the data needed to render it. */
1570
+ interface EmailCopyIssue {
1571
+ code: string;
1572
+ message: string;
1573
+ variable?: string;
1574
+ }
1575
+ /** A display name suitable for membership mail, never a missing name or a provider identifier. */
1576
+ declare function isEmailTierName(value: unknown, id?: string): value is string;
1577
+ /** Variables and concrete data to check. Omit values when auditing saved copy before an event occurs. */
1578
+ interface EmailCopyValidation {
1579
+ allowedVariables?: readonly string[];
1580
+ optionalVariables?: readonly string[];
1581
+ requiredVariables?: readonly string[];
1582
+ values?: Record<string, string>;
1583
+ tierId?: string;
1584
+ }
1585
+ /** Validate saved copy and, when supplied, its actual event data. Does not render, store, or send mail.
1586
+ * Unknown tokens, missing required values, explicit internal draft notes and invalid tier names fail closed.
1587
+ * Optional values must be named by the event contract; arbitrary unknown placeholders never become blanks. */
1588
+ declare function validateEmailCopy(copy: {
1589
+ subject?: unknown;
1590
+ text?: unknown;
1591
+ }, options?: EmailCopyValidation): EmailCopyIssue[];
1592
+
1593
+ export { ACTIVITY_KINDS, type ActivityKind, type AttrType, type BillingEvent, type BillingProvider, CONFIG_KEY, CONSENT_STATES, CRM_DISCUSSION_REFERENCE_KINDS, CRM_NS, CRM_RULES, CRM_SCHEMA, CRM_SLOTS, type CompiledList, type ConfigPatch, type ConsentEvent, type ConsentOutcome, type ConsentState, type Crm, type CrmActivity, type CrmActor, type CrmAggregateResult, type CrmAggregateSpec, type CrmAttrs, CrmClient, type CrmClientOptions, type CrmConfig, type CrmConfigRow, type CrmContactChannel, type CrmDb, type CrmDeps, type CrmDiscussionReference, type CrmDiscussionReferenceActor, type CrmDiscussionReferenceKind, type CrmDiscussionReferenceTarget, type CrmEmailLogRow, type CrmEmailSender, type CrmEntityRef, CrmInputError, type CrmIntegrationDescriptor, type CrmIntegrationOptions, type CrmIntegrationProbe, type CrmIntegrationSeed, type CrmLink, type CrmListParams, type CrmLookup, CrmNotFoundError, type CrmOp, type CrmQuery, type CrmRecord, type CrmRecordDelivery, type CrmRecordOrigin, type CrmResult, type CrmRouteOpts, type CrmRow, type CrmRule, type CrmRules, type CrmScalar, type CrmSlot, type CrmSort, type CrmTag, type CrmTransactGuard, type CrmView, DEFAULT_LIMIT, EMAIL_STATUSES, type EmailCopyIssue, type EmailCopyValidation, type EmailStatus, type FieldCondition, type FieldConditions, type FieldDef, type FieldFilter, type FieldState, type FieldType, MAX_LIMIT, type PipelineDef, type PreparedWrite, RANK_EPSILON, RANK_STEP, type RelationDef, SORTABLE_COLUMNS, type SendEmailOpts, type SendEmailResult, type SerializedAttr, type SerializedEntity, type SerializedLink, type SerializedLinkEnd, type SerializedSchema, type StageDef, type StoredTemplate, type SubscriptionSnapshot, TASK_STATUSES, type TaskStatus, type TemplateSpec, type TypeDef, type TypeFacets, type TypeSummary, type ViewFilters, type ViewSpec, addActivity, addLink, addTag, applyConsent, applyConsentEvent, assertFieldCondition, canEmail, canTransition, channelKey, compileList, composeCrmConfigs, createCrmIntegration, createCrmRoutes, createRecord, crmDiscussionReferenceHref, crmDiscussionReferenceId, crmIntegration, crmRules, defaultTemplates, defineCrm, deleteView, emailChannelOps, evaluateFieldCondition, foldEmailStatus, formatCrmDiscussionReference, getConfig, getRecord, getRecordByOrigin, getRecordOrigin, initialStage, isEmailTierName, linkIdentity, lintTemplate, listActivities, listChannels, listEmailLog, listLinks, listRecordDeliveries, listRecordOrigins, listRecords, listTags, listTasks, listViews, mustGetRecord, needsRebalance, normalizeTag, parseCrmDiscussionReference, prepare, rankBetween, rebalancePlan, rebalanceRanks, recordCanEmail, recordDeliveryAttempt, recordDeliveryKey, recordOriginKey, removeLink, removeTag, renderTemplate, resolveDeps, resolveFieldState, resolveFieldStates, resolveSortColumn, rowToRecord, saveConfig, saveView, searchTextFor, sendTemplatedEmail, setArchived, setRank, setStage, stageIndexOf, templateVars, typeSummary, updateRecord, updateTask, updateView, upsertRecordOrigin, validateEmailCopy };
package/dist/index.js CHANGED
@@ -837,7 +837,7 @@ async function listChannels(deps, recordId) {
837
837
  });
838
838
  return (result[CRM_NS.channel] ?? []).map(rowToChannel);
839
839
  }
840
- function emailChannelOps(deps, recordId, email, existing) {
840
+ function emailChannelOps(deps, recordId, email, existing, initialConsent = { state: "subscribed", source: "record-write" }) {
841
841
  const { now, newId } = resolveDeps(deps);
842
842
  const ops = [];
843
843
  const current = existing.filter((c) => c.kind === "email" && c.isPrimary);
@@ -861,14 +861,14 @@ function emailChannelOps(deps, recordId, email, existing) {
861
861
  kind: "email",
862
862
  value: email,
863
863
  isPrimary: true,
864
- consent: "subscribed",
864
+ consent: initialConsent.state,
865
865
  consentAt: now(),
866
- consentSource: "record-write",
866
+ consentSource: initialConsent.source,
867
867
  unsubscribeToken: newId(),
868
868
  createdAt: now()
869
869
  }
870
870
  });
871
- return { ops, emailStatus: "ok" };
871
+ return { ops, emailStatus: foldEmailStatus(initialConsent.state) };
872
872
  }
873
873
  async function applyConsent(deps, opts) {
874
874
  const { db, now } = resolveDeps(deps);
@@ -924,7 +924,7 @@ function applyPatch(base, patch, alsoClear = []) {
924
924
 
925
925
  // src/records.ts
926
926
  function rowToRecord(row) {
927
- const record = row;
927
+ const record = rowAsWritten(CRM_NS.record, row);
928
928
  return { ...record, fields: record.fields ?? {}, searchText: record.searchText ?? "" };
929
929
  }
930
930
  async function getRecord(deps, id) {
@@ -974,9 +974,9 @@ async function createRecord(deps, opts) {
974
974
  const { crm, db, now, newId } = resolveDeps(deps);
975
975
  const prepared = crm.prepare(opts.type, opts.input);
976
976
  if (!prepared.ok) throw new CrmInputError("invalid input", prepared.errors);
977
- const id = newId();
977
+ const id = opts.id ?? newId();
978
978
  const at = now();
979
- const stage = opts.stage ?? crm.initialStage(opts.type);
979
+ const stage = opts.stage === void 0 ? crm.initialStage(opts.type) : opts.stage;
980
980
  const attrs = {
981
981
  id,
982
982
  // mirror the entity id as an attr so `where: { id }` reads can find it
@@ -996,7 +996,7 @@ async function createRecord(deps, opts) {
996
996
  const ops = [];
997
997
  const email = prepared.attrs["primaryEmail"] ?? null;
998
998
  if (crm.type(opts.type).emailField) {
999
- const channel = emailChannelOps(deps, id, email, []);
999
+ const channel = emailChannelOps(deps, id, email, [], opts.emailConsent);
1000
1000
  attrs.emailStatus = channel.emailStatus;
1001
1001
  ops.push(...channel.ops);
1002
1002
  } else {
@@ -1006,7 +1006,9 @@ async function createRecord(deps, opts) {
1006
1006
  const score = scoreOf(deps, opts.type, candidate);
1007
1007
  if (score !== void 0) attrs.score = score;
1008
1008
  ops.unshift({ t: "update", ns: CRM_NS.record, id, attrs });
1009
- const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId });
1009
+ const guards = [...opts.guards ?? [], ...opts.id ? [{ ns: CRM_NS.record, id, exists: false }] : []];
1010
+ const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId, ...guards.length ? { guards } : {} });
1011
+ if (duplicate && opts.id) return { id, duplicate, record: await mustGetRecord(deps, id) };
1010
1012
  return { id, duplicate, record: { id, ...attrs } };
1011
1013
  }
1012
1014
  async function updateRecord(deps, opts) {
@@ -1659,6 +1661,43 @@ async function saveConfig(deps, patch, opts = {}) {
1659
1661
  return { config: merged, duplicate };
1660
1662
  }
1661
1663
 
1664
+ // src/email-validation.ts
1665
+ function isEmailTierName(value, id) {
1666
+ return typeof value === "string" && !!value.trim() && value.trim() !== id && !/^(?:unknown|undefined|null|n\/a|(?:sku|price|tier|prod)_[\w-]+|[0-9a-f]{8}-[0-9a-f-]{27,})$/i.test(value.trim()) && !/[{}\r\n]/.test(value);
1667
+ }
1668
+ function validateEmailCopy(copy, options = {}) {
1669
+ const issues = [];
1670
+ const subject = typeof copy.subject === "string" ? copy.subject : "";
1671
+ const text = typeof copy.text === "string" ? copy.text : "";
1672
+ if (!subject.trim()) issues.push({ code: "subject-missing", message: "Add an email subject." });
1673
+ if (!text.trim()) issues.push({ code: "body-missing", message: "Add an email body." });
1674
+ if (/[\r\n]/.test(subject) || subject.length > 200) issues.push({ code: "subject-invalid", message: "Use a single-line subject of at most 200 characters." });
1675
+ if (text.length > 1e4) issues.push({ code: "body-invalid", message: "Keep the email body within 10,000 characters." });
1676
+ const combined = `${subject}
1677
+ ${text}`;
1678
+ if (/^\s*(?:\(\s*unused\s*:|Unused\.\s*Switched off\b|(?:TODO|TBD|PLACEHOLDER)\s*:|DRAFT\s*[-:]|\[\s*(?:draft|placeholder)\s*\]|do not (?:send|use) this (?:email|template))/im.test(combined)) {
1679
+ issues.push({ code: "internal-copy", message: "Replace internal draft or retirement notes with recipient-facing copy." });
1680
+ }
1681
+ const tokens = [...new Set([...combined.matchAll(/\{\{(\w+)\}\}/g)].map((match) => match[1]))];
1682
+ if (/[{}]/.test(combined.replace(/\{\{\w+\}\}/g, ""))) issues.push({ code: "placeholder-invalid", message: "Fix malformed placeholders; use {{variableName}}." });
1683
+ for (const variable of tokens) {
1684
+ if (options.allowedVariables && !options.allowedVariables.includes(variable)) issues.push({ code: "variable-unknown", variable, message: `This event does not supply {{${variable}}}.` });
1685
+ }
1686
+ if (options.values) {
1687
+ for (const variable of /* @__PURE__ */ new Set([...tokens, ...options.requiredVariables ?? []])) {
1688
+ const value = options.values[variable];
1689
+ if (typeof value !== "string" || !value.trim() && !options.optionalVariables?.includes(variable)) {
1690
+ issues.push({ code: "value-missing", variable, message: `Missing event value: ${variable}.` });
1691
+ } else if ((variable === "tierName" || variable === "tier") && !isEmailTierName(value, options.tierId)) {
1692
+ issues.push({ code: "tier-name-invalid", variable, message: "Resolve the membership tier's display name before sending." });
1693
+ } else if (/\{\{|\}\}/.test(value)) {
1694
+ issues.push({ code: "value-invalid", variable, message: `Unresolved placeholder in ${variable}.` });
1695
+ }
1696
+ }
1697
+ }
1698
+ return issues;
1699
+ }
1700
+
1662
1701
  // src/email.ts
1663
1702
  async function sendTemplatedEmail(deps, opts) {
1664
1703
  const { crm, db, now, newId } = resolveDeps(deps);
@@ -1667,7 +1706,8 @@ async function sendTemplatedEmail(deps, opts) {
1667
1706
  const config = await getConfig(deps);
1668
1707
  const stored = config?.emailTemplates[opts.templateId] ?? null;
1669
1708
  if (!stored || !stored.subject && !stored.text) return { sent: false, reason: "no_template_copy" };
1670
- if (!stored.enabled && !opts.force) return { sent: false, reason: "disabled" };
1709
+ if (typeof stored.enabled !== "boolean") return { sent: false, reason: "template-invalid" };
1710
+ if (stored.enabled !== true && !opts.force) return { sent: false, reason: "disabled" };
1671
1711
  const record = await mustGetRecord(deps, opts.recordId);
1672
1712
  const channels = await listChannels(deps, record.id);
1673
1713
  const channel = opts.channelId ? channels.find((c) => c.id === opts.channelId) : channels.find((c) => c.kind === "email" && c.isPrimary);
@@ -1686,8 +1726,10 @@ async function sendTemplatedEmail(deps, opts) {
1686
1726
  headers["List-Unsubscribe"] = `<${unsubscribeUrl}>`;
1687
1727
  headers["List-Unsubscribe-Post"] = "List-Unsubscribe=One-Click";
1688
1728
  }
1729
+ if (validateEmailCopy(stored, { allowedVariables: spec.vars, values: vars }).length) return { sent: false, reason: "template-invalid" };
1689
1730
  let subject = renderTemplate(stored.subject, vars);
1690
1731
  const text = renderTemplate(stored.text, vars);
1732
+ if (validateEmailCopy({ subject, text }, { allowedVariables: [] }).length) return { sent: false, reason: "template-invalid" };
1691
1733
  let to = channel.value;
1692
1734
  let redirected = false;
1693
1735
  let logOnly = !deps.sender;
@@ -1766,10 +1808,12 @@ async function recordCanEmail(deps, recordId, cls) {
1766
1808
  async function linkIdentity(deps, opts) {
1767
1809
  const { db, now } = resolveDeps(deps);
1768
1810
  const record = await mustGetRecord(deps, opts.recordId);
1811
+ if (record.clerkUserId) return { linked: true, clerkUserId: record.clerkUserId };
1769
1812
  const email = (opts.email ?? record.primaryEmail)?.trim().toLowerCase();
1770
1813
  if (!email) throw new CrmInputError("record has no email to match on");
1771
- const result = await db.query({ $users: { $: { where: { email }, limit: 1 } } });
1772
- const user = (result["$users"] ?? []).find((row) => !row["deleted"]);
1814
+ const result = await db.query({ $users: { $: { where: { email }, limit: 2 } } });
1815
+ const users = result["$users"] ?? [];
1816
+ const user = users.length === 1 && !users[0]["deleted"] ? users[0] : void 0;
1773
1817
  if (!user) return { linked: false };
1774
1818
  const { duplicate } = await db.transact(
1775
1819
  [
@@ -1780,7 +1824,24 @@ async function linkIdentity(deps, opts) {
1780
1824
  attrs: { clerkUserId: user.id, updatedAt: now() }
1781
1825
  }
1782
1826
  ],
1783
- { mutationId: opts.mutationId }
1827
+ { mutationId: opts.mutationId, guards: [
1828
+ {
1829
+ ns: "$users",
1830
+ id: user.id,
1831
+ exists: true,
1832
+ equals: {
1833
+ email,
1834
+ ...user["deleted"] !== void 0 ? { deleted: user["deleted"] } : {}
1835
+ },
1836
+ ...user["deleted"] === void 0 ? { absent: ["deleted"] } : {}
1837
+ },
1838
+ {
1839
+ ns: CRM_NS.record,
1840
+ id: record.id,
1841
+ exists: true,
1842
+ ...record.clerkUserId === null ? { equals: { clerkUserId: null } } : { absent: ["clerkUserId"] }
1843
+ }
1844
+ ] }
1784
1845
  );
1785
1846
  return { linked: true, clerkUserId: user.id, duplicate };
1786
1847
  }
@@ -2121,7 +2182,7 @@ async function handleRecordsRoot(ctx, req, url) {
2121
2182
  type: str(body, "type"),
2122
2183
  input: obj(body, "input"),
2123
2184
  ownerId: optStr(body, "ownerId"),
2124
- stage: optStr(body, "stage"),
2185
+ stage: nullableStr(body, "stage"),
2125
2186
  mutationId: optStr(body, "mutationId")
2126
2187
  });
2127
2188
  return json({ id: created.id, duplicate: created.duplicate, record: created.record }, 201);
@@ -2726,6 +2787,7 @@ export {
2726
2787
  getRecordByOrigin,
2727
2788
  getRecordOrigin,
2728
2789
  initialStage,
2790
+ isEmailTierName,
2729
2791
  linkIdentity,
2730
2792
  lintTemplate,
2731
2793
  listActivities,
@@ -2771,6 +2833,7 @@ export {
2771
2833
  updateRecord,
2772
2834
  updateTask,
2773
2835
  updateView,
2774
- upsertRecordOrigin
2836
+ upsertRecordOrigin,
2837
+ validateEmailCopy
2775
2838
  };
2776
2839
  //# sourceMappingURL=index.js.map