@odla-ai/crm 0.3.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -486,6 +486,45 @@ declare class CrmNotFoundError extends Error {
486
486
  constructor(what: string);
487
487
  }
488
488
 
489
+ /** CRM resources that can be shared into a Discussion message. */
490
+ declare const CRM_DISCUSSION_REFERENCE_KINDS: readonly ["crm:record", "crm:activity"];
491
+ /** One CRM resource kind understood by the native CRM destination. */
492
+ type CrmDiscussionReferenceKind = (typeof CRM_DISCUSSION_REFERENCE_KINDS)[number];
493
+ /** Canonical CRM destination target parsed from an `odla-ref` deep link. */
494
+ interface CrmDiscussionReferenceTarget {
495
+ kind: CrmDiscussionReferenceKind;
496
+ type: string;
497
+ recordId: string;
498
+ activityId?: string;
499
+ }
500
+ /** Product-owned projection returned to Discussion typeahead and exact lookup. */
501
+ interface CrmDiscussionReference {
502
+ /** Canonical CRM kind used in stored Discussion ref markup. */
503
+ kind: CrmDiscussionReferenceKind;
504
+ /** Opaque durable product id; never infer CRM access from its segments. */
505
+ id: string;
506
+ /** Product-authored primary display name. */
507
+ label: string;
508
+ /** Short product-authored secondary context for the picker. */
509
+ hint: string;
510
+ /** Bounded product-authored context safe to show an LLM or person. */
511
+ summary: string;
512
+ /** Current product status at inspection time. */
513
+ status: string;
514
+ /** Human-readable native surface the link opens. */
515
+ destination: string;
516
+ /** Same-origin native link; navigation is not mutation authority. */
517
+ href: string;
518
+ }
519
+ /** Durable ref id: `type/recordId`, plus an activity id for feed entries. */
520
+ declare function crmDiscussionReferenceId(target: CrmDiscussionReferenceTarget): string;
521
+ /** Canonical value stored in the stable `odla-ref` query parameter. */
522
+ declare function formatCrmDiscussionReference(target: CrmDiscussionReferenceTarget): string;
523
+ /** Parse and validate a CRM `odla-ref`; malformed and cross-product refs fail closed. */
524
+ declare function parseCrmDiscussionReference(input: URL | string): CrmDiscussionReferenceTarget | null;
525
+ /** Build a Chapter-compatible CRM deep link and retain the exact ref for focus. */
526
+ declare function crmDiscussionReferenceHref(current: URL, target: CrmDiscussionReferenceTarget, basePath?: string): string;
527
+
489
528
  /** What every op needs: the resolved config, the injected db, test overrides. */
490
529
  interface CrmDeps {
491
530
  crm: Crm;
@@ -1062,6 +1101,13 @@ interface BillingProvider {
1062
1101
  interface CrmActor {
1063
1102
  userId: string;
1064
1103
  email?: string;
1104
+ /** Explicit product ACL for the read-only Discussion projection. Ordinary
1105
+ * CRM routes do not consult or grant this marker. */
1106
+ discussionReferenceScope?: "all";
1107
+ }
1108
+ /** Actor accepted by the product-owned CRM reference projection. */
1109
+ interface CrmDiscussionReferenceActor extends CrmActor {
1110
+ discussionReferenceScope: "all";
1065
1111
  }
1066
1112
  /** Everything `createCrmRoutes` needs from the host worker. */
1067
1113
  interface CrmRouteOpts {
@@ -1070,6 +1116,10 @@ interface CrmRouteOpts {
1070
1116
  /** Host-owned auth: resolve the request to an admin actor or null (401).
1071
1117
  * The unsubscribe endpoints are the only routes that skip this. */
1072
1118
  authorize: (req: Request) => Promise<CrmActor | null> | CrmActor | null;
1119
+ /** Optional host authority seam for read-only Discussion reference lookup.
1120
+ * Verify exact CRM product, crm.read capability, canonical audience,
1121
+ * principal, current app lifetime/environment, and agent grant provenance. */
1122
+ authorizeDiscussionReferences?: (req: Request) => Promise<CrmDiscussionReferenceActor | null> | CrmDiscussionReferenceActor | null;
1073
1123
  /** Email transport; omit for log-only behavior. */
1074
1124
  sender?: CrmEmailSender;
1075
1125
  /** Sender address for outbound mail (verified from-address). */
@@ -1081,6 +1131,8 @@ interface CrmRouteOpts {
1081
1131
  baseUrl?: string;
1082
1132
  /** Mount point. Default "/api/crm". */
1083
1133
  basePath?: string;
1134
+ /** Native UI mount used by returned Discussion deep links. Default "/admin/". */
1135
+ discussionBasePath?: string;
1084
1136
  /** Injectable clock/id factory (tests). */
1085
1137
  now?: () => number;
1086
1138
  newId?: () => string;
@@ -1338,4 +1390,4 @@ declare const crmIntegration: CrmIntegrationDescriptor;
1338
1390
  */
1339
1391
  declare function createCrmIntegration(crm: Crm, options?: CrmIntegrationOptions): CrmIntegrationDescriptor;
1340
1392
 
1341
- export { ACTIVITY_KINDS, type ActivityKind, type AttrType, type BillingEvent, type BillingProvider, CONFIG_KEY, CONSENT_STATES, 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 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 CrmResult, type CrmRouteOpts, type CrmRow, type CrmRule, type CrmRules, type CrmScalar, type CrmSlot, type CrmSort, type CrmTag, type CrmView, DEFAULT_LIMIT, EMAIL_STATUSES, type EmailStatus, type FieldDef, type FieldFilter, 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, canEmail, canTransition, channelKey, compileList, createCrmIntegration, createCrmRoutes, createRecord, crmIntegration, crmRules, defaultTemplates, defineCrm, deleteView, emailChannelOps, foldEmailStatus, getConfig, getRecord, initialStage, linkIdentity, lintTemplate, listActivities, listChannels, listEmailLog, listLinks, listRecords, listTags, listTasks, listViews, mustGetRecord, needsRebalance, normalizeTag, prepare, rankBetween, rebalancePlan, rebalanceRanks, recordCanEmail, removeLink, removeTag, renderTemplate, resolveDeps, resolveSortColumn, rowToRecord, saveConfig, saveView, searchTextFor, sendTemplatedEmail, setArchived, setRank, setStage, stageIndexOf, templateVars, typeSummary, updateRecord, updateTask, updateView };
1393
+ 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 CrmResult, type CrmRouteOpts, type CrmRow, type CrmRule, type CrmRules, type CrmScalar, type CrmSlot, type CrmSort, type CrmTag, type CrmView, DEFAULT_LIMIT, EMAIL_STATUSES, type EmailStatus, type FieldDef, type FieldFilter, 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, canEmail, canTransition, channelKey, compileList, createCrmIntegration, createCrmRoutes, createRecord, crmDiscussionReferenceHref, crmDiscussionReferenceId, crmIntegration, crmRules, defaultTemplates, defineCrm, deleteView, emailChannelOps, foldEmailStatus, formatCrmDiscussionReference, getConfig, getRecord, initialStage, linkIdentity, lintTemplate, listActivities, listChannels, listEmailLog, listLinks, listRecords, listTags, listTasks, listViews, mustGetRecord, needsRebalance, normalizeTag, parseCrmDiscussionReference, prepare, rankBetween, rebalancePlan, rebalanceRanks, recordCanEmail, removeLink, removeTag, renderTemplate, resolveDeps, resolveSortColumn, rowToRecord, saveConfig, saveView, searchTextFor, sendTemplatedEmail, setArchived, setRank, setStage, stageIndexOf, templateVars, typeSummary, updateRecord, updateTask, updateView };
package/dist/index.d.ts CHANGED
@@ -486,6 +486,45 @@ declare class CrmNotFoundError extends Error {
486
486
  constructor(what: string);
487
487
  }
488
488
 
489
+ /** CRM resources that can be shared into a Discussion message. */
490
+ declare const CRM_DISCUSSION_REFERENCE_KINDS: readonly ["crm:record", "crm:activity"];
491
+ /** One CRM resource kind understood by the native CRM destination. */
492
+ type CrmDiscussionReferenceKind = (typeof CRM_DISCUSSION_REFERENCE_KINDS)[number];
493
+ /** Canonical CRM destination target parsed from an `odla-ref` deep link. */
494
+ interface CrmDiscussionReferenceTarget {
495
+ kind: CrmDiscussionReferenceKind;
496
+ type: string;
497
+ recordId: string;
498
+ activityId?: string;
499
+ }
500
+ /** Product-owned projection returned to Discussion typeahead and exact lookup. */
501
+ interface CrmDiscussionReference {
502
+ /** Canonical CRM kind used in stored Discussion ref markup. */
503
+ kind: CrmDiscussionReferenceKind;
504
+ /** Opaque durable product id; never infer CRM access from its segments. */
505
+ id: string;
506
+ /** Product-authored primary display name. */
507
+ label: string;
508
+ /** Short product-authored secondary context for the picker. */
509
+ hint: string;
510
+ /** Bounded product-authored context safe to show an LLM or person. */
511
+ summary: string;
512
+ /** Current product status at inspection time. */
513
+ status: string;
514
+ /** Human-readable native surface the link opens. */
515
+ destination: string;
516
+ /** Same-origin native link; navigation is not mutation authority. */
517
+ href: string;
518
+ }
519
+ /** Durable ref id: `type/recordId`, plus an activity id for feed entries. */
520
+ declare function crmDiscussionReferenceId(target: CrmDiscussionReferenceTarget): string;
521
+ /** Canonical value stored in the stable `odla-ref` query parameter. */
522
+ declare function formatCrmDiscussionReference(target: CrmDiscussionReferenceTarget): string;
523
+ /** Parse and validate a CRM `odla-ref`; malformed and cross-product refs fail closed. */
524
+ declare function parseCrmDiscussionReference(input: URL | string): CrmDiscussionReferenceTarget | null;
525
+ /** Build a Chapter-compatible CRM deep link and retain the exact ref for focus. */
526
+ declare function crmDiscussionReferenceHref(current: URL, target: CrmDiscussionReferenceTarget, basePath?: string): string;
527
+
489
528
  /** What every op needs: the resolved config, the injected db, test overrides. */
490
529
  interface CrmDeps {
491
530
  crm: Crm;
@@ -1062,6 +1101,13 @@ interface BillingProvider {
1062
1101
  interface CrmActor {
1063
1102
  userId: string;
1064
1103
  email?: string;
1104
+ /** Explicit product ACL for the read-only Discussion projection. Ordinary
1105
+ * CRM routes do not consult or grant this marker. */
1106
+ discussionReferenceScope?: "all";
1107
+ }
1108
+ /** Actor accepted by the product-owned CRM reference projection. */
1109
+ interface CrmDiscussionReferenceActor extends CrmActor {
1110
+ discussionReferenceScope: "all";
1065
1111
  }
1066
1112
  /** Everything `createCrmRoutes` needs from the host worker. */
1067
1113
  interface CrmRouteOpts {
@@ -1070,6 +1116,10 @@ interface CrmRouteOpts {
1070
1116
  /** Host-owned auth: resolve the request to an admin actor or null (401).
1071
1117
  * The unsubscribe endpoints are the only routes that skip this. */
1072
1118
  authorize: (req: Request) => Promise<CrmActor | null> | CrmActor | null;
1119
+ /** Optional host authority seam for read-only Discussion reference lookup.
1120
+ * Verify exact CRM product, crm.read capability, canonical audience,
1121
+ * principal, current app lifetime/environment, and agent grant provenance. */
1122
+ authorizeDiscussionReferences?: (req: Request) => Promise<CrmDiscussionReferenceActor | null> | CrmDiscussionReferenceActor | null;
1073
1123
  /** Email transport; omit for log-only behavior. */
1074
1124
  sender?: CrmEmailSender;
1075
1125
  /** Sender address for outbound mail (verified from-address). */
@@ -1081,6 +1131,8 @@ interface CrmRouteOpts {
1081
1131
  baseUrl?: string;
1082
1132
  /** Mount point. Default "/api/crm". */
1083
1133
  basePath?: string;
1134
+ /** Native UI mount used by returned Discussion deep links. Default "/admin/". */
1135
+ discussionBasePath?: string;
1084
1136
  /** Injectable clock/id factory (tests). */
1085
1137
  now?: () => number;
1086
1138
  newId?: () => string;
@@ -1338,4 +1390,4 @@ declare const crmIntegration: CrmIntegrationDescriptor;
1338
1390
  */
1339
1391
  declare function createCrmIntegration(crm: Crm, options?: CrmIntegrationOptions): CrmIntegrationDescriptor;
1340
1392
 
1341
- export { ACTIVITY_KINDS, type ActivityKind, type AttrType, type BillingEvent, type BillingProvider, CONFIG_KEY, CONSENT_STATES, 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 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 CrmResult, type CrmRouteOpts, type CrmRow, type CrmRule, type CrmRules, type CrmScalar, type CrmSlot, type CrmSort, type CrmTag, type CrmView, DEFAULT_LIMIT, EMAIL_STATUSES, type EmailStatus, type FieldDef, type FieldFilter, 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, canEmail, canTransition, channelKey, compileList, createCrmIntegration, createCrmRoutes, createRecord, crmIntegration, crmRules, defaultTemplates, defineCrm, deleteView, emailChannelOps, foldEmailStatus, getConfig, getRecord, initialStage, linkIdentity, lintTemplate, listActivities, listChannels, listEmailLog, listLinks, listRecords, listTags, listTasks, listViews, mustGetRecord, needsRebalance, normalizeTag, prepare, rankBetween, rebalancePlan, rebalanceRanks, recordCanEmail, removeLink, removeTag, renderTemplate, resolveDeps, resolveSortColumn, rowToRecord, saveConfig, saveView, searchTextFor, sendTemplatedEmail, setArchived, setRank, setStage, stageIndexOf, templateVars, typeSummary, updateRecord, updateTask, updateView };
1393
+ 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 CrmResult, type CrmRouteOpts, type CrmRow, type CrmRule, type CrmRules, type CrmScalar, type CrmSlot, type CrmSort, type CrmTag, type CrmView, DEFAULT_LIMIT, EMAIL_STATUSES, type EmailStatus, type FieldDef, type FieldFilter, 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, canEmail, canTransition, channelKey, compileList, createCrmIntegration, createCrmRoutes, createRecord, crmDiscussionReferenceHref, crmDiscussionReferenceId, crmIntegration, crmRules, defaultTemplates, defineCrm, deleteView, emailChannelOps, foldEmailStatus, formatCrmDiscussionReference, getConfig, getRecord, initialStage, linkIdentity, lintTemplate, listActivities, listChannels, listEmailLog, listLinks, listRecords, listTags, listTasks, listViews, mustGetRecord, needsRebalance, normalizeTag, parseCrmDiscussionReference, prepare, rankBetween, rebalancePlan, rebalanceRanks, recordCanEmail, removeLink, removeTag, renderTemplate, resolveDeps, resolveSortColumn, rowToRecord, saveConfig, saveView, searchTextFor, sendTemplatedEmail, setArchived, setRank, setStage, stageIndexOf, templateVars, typeSummary, updateRecord, updateTask, updateView };
package/dist/index.js CHANGED
@@ -495,6 +495,49 @@ ${tpl.defaults.text}`, tpl.vars);
495
495
  };
496
496
  }
497
497
 
498
+ // src/discussion-reference.ts
499
+ var CRM_DISCUSSION_REFERENCE_KINDS = [
500
+ "crm:record",
501
+ "crm:activity"
502
+ ];
503
+ var SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,199}$/;
504
+ function crmDiscussionReferenceId(target) {
505
+ const root = `${target.type}/${target.recordId}`;
506
+ return target.activityId ? `${root}/${target.activityId}` : root;
507
+ }
508
+ function formatCrmDiscussionReference(target) {
509
+ return `${target.kind}/${crmDiscussionReferenceId(target)}`;
510
+ }
511
+ function parseCrmDiscussionReference(input) {
512
+ let raw;
513
+ try {
514
+ raw = input instanceof URL ? input.searchParams.get("odla-ref") : new URL(input, "https://crm.invalid").searchParams.get("odla-ref");
515
+ } catch {
516
+ return null;
517
+ }
518
+ if (!raw) return null;
519
+ const [kind, type, recordId, activityId, extra] = raw.split("/");
520
+ if (extra !== void 0 || !CRM_DISCUSSION_REFERENCE_KINDS.includes(
521
+ kind
522
+ ) || !type || !recordId || !SEGMENT.test(type) || !SEGMENT.test(recordId)) return null;
523
+ if (kind === "crm:record") {
524
+ return activityId === void 0 ? { kind, type, recordId } : null;
525
+ }
526
+ return activityId && SEGMENT.test(activityId) ? { kind: "crm:activity", type, recordId, activityId } : null;
527
+ }
528
+ function crmDiscussionReferenceHref(current, target, basePath = "/admin/") {
529
+ const next = new URL(current.origin);
530
+ next.pathname = basePath.startsWith("/") ? basePath : `/${basePath}`;
531
+ next.searchParams.set("odla-ref", formatCrmDiscussionReference(target));
532
+ next.hash = [
533
+ "people",
534
+ target.type,
535
+ target.recordId,
536
+ target.kind === "crm:activity" ? "notes" : "profile"
537
+ ].map(encodeURIComponent).join("/");
538
+ return next.toString();
539
+ }
540
+
498
541
  // src/deps.ts
499
542
  function resolveDeps(deps) {
500
543
  return {
@@ -543,14 +586,14 @@ function compileList(crm, params, tagRecordIds) {
543
586
  const column = resolveSortColumn(crm, params.type, sort.field);
544
587
  const limit = Math.min(Math.max(params.limit ?? DEFAULT_LIMIT, 1), MAX_LIMIT);
545
588
  const offset = Math.max(params.offset ?? 0, 0);
546
- const search = params.search?.trim();
589
+ const search2 = params.search?.trim();
547
590
  return {
548
591
  opts: {
549
592
  where: { and },
550
593
  order: { [column]: sort.dir },
551
594
  limit,
552
595
  offset,
553
- ...search ? { search } : {}
596
+ ...search2 ? { search: search2 } : {}
554
597
  },
555
598
  limit,
556
599
  offset
@@ -1479,8 +1522,8 @@ function parseListParams(url) {
1479
1522
  const type = q.get("type");
1480
1523
  if (!type) throw new CrmInputError("type is required");
1481
1524
  const params = { type };
1482
- const search = q.get("search");
1483
- if (search) params.search = search;
1525
+ const search2 = q.get("search");
1526
+ if (search2) params.search = search2;
1484
1527
  params.stage = csv(q.get("stage"));
1485
1528
  params.emailStatus = csv(q.get("emailStatus"));
1486
1529
  params.billingStatus = csv(q.get("billingStatus"));
@@ -1893,9 +1936,141 @@ async function handleUnsubscribe(deps, req, url) {
1893
1936
  return oneClick ? json({ ok: true }) : unsubscribePage(token, true);
1894
1937
  }
1895
1938
 
1939
+ // src/routes/discussion-references.ts
1940
+ var capLimit = (raw) => {
1941
+ const parsed = Number(raw ?? 20);
1942
+ return Number.isInteger(parsed) ? Math.max(1, Math.min(parsed, 20)) : 20;
1943
+ };
1944
+ var targetFromQuery = (url) => {
1945
+ const kind = url.searchParams.get("kind");
1946
+ const id = url.searchParams.get("id");
1947
+ if (!kind || !id) return null;
1948
+ const value = new URL("https://crm.invalid");
1949
+ value.searchParams.set("odla-ref", `${kind}/${id}`);
1950
+ return parseCrmDiscussionReference(value);
1951
+ };
1952
+ var recordItem = (ctx, req, record) => {
1953
+ const typeLabel = ctx.deps.crm.type(record.type).label;
1954
+ const status = record.archived ? "archived" : record.stage ?? "record";
1955
+ const target = {
1956
+ kind: "crm:record",
1957
+ type: record.type,
1958
+ recordId: record.id
1959
+ };
1960
+ return {
1961
+ kind: target.kind,
1962
+ id: crmDiscussionReferenceId(target),
1963
+ label: record.name,
1964
+ hint: `${typeLabel} \xB7 ${status}`,
1965
+ summary: `${typeLabel} record for ${record.name}`,
1966
+ status,
1967
+ destination: `CRM \xB7 ${typeLabel} profile`,
1968
+ href: crmDiscussionReferenceHref(
1969
+ new URL(req.url),
1970
+ target,
1971
+ ctx.opts.discussionBasePath
1972
+ )
1973
+ };
1974
+ };
1975
+ var activityItem = (ctx, req, record, activity) => {
1976
+ const target = {
1977
+ kind: "crm:activity",
1978
+ type: record.type,
1979
+ recordId: record.id,
1980
+ activityId: activity.id
1981
+ };
1982
+ return {
1983
+ kind: target.kind,
1984
+ id: crmDiscussionReferenceId(target),
1985
+ label: activity.body,
1986
+ hint: `${record.name} \xB7 ${activity.kind}${activity.status ? ` \xB7 ${activity.status}` : ""}`,
1987
+ summary: `${activity.kind} on ${record.name}: ${activity.body}`,
1988
+ status: activity.status ?? activity.kind,
1989
+ destination: `CRM \xB7 ${record.name} notes`,
1990
+ href: crmDiscussionReferenceHref(
1991
+ new URL(req.url),
1992
+ target,
1993
+ ctx.opts.discussionBasePath
1994
+ )
1995
+ };
1996
+ };
1997
+ async function exact(ctx, req, target) {
1998
+ const record = await getRecord(ctx.deps, target.recordId);
1999
+ if (!record || record.type !== target.type) return [];
2000
+ if (target.kind === "crm:record") return [recordItem(ctx, req, record)];
2001
+ const result = await ctx.deps.db.query({
2002
+ [CRM_NS.activity]: {
2003
+ $: { where: { id: target.activityId }, limit: 1 }
2004
+ }
2005
+ });
2006
+ const activity = (result[CRM_NS.activity] ?? [])[0];
2007
+ return activity && activity.recordId === record.id ? [activityItem(ctx, req, record, activity)] : [];
2008
+ }
2009
+ var matches = (item, needle) => !needle || `${item.label}
2010
+ ${item.hint}
2011
+ ${item.id}`.toLowerCase().includes(needle);
2012
+ async function searchableActivities(ctx, req, needle) {
2013
+ const result = await ctx.deps.db.query({
2014
+ [CRM_NS.activity]: {
2015
+ $: { order: { createdAt: "desc" }, limit: 100 }
2016
+ }
2017
+ });
2018
+ const rows = result[CRM_NS.activity] ?? [];
2019
+ const matching = rows.filter(
2020
+ (activity) => !needle || activity.body.toLowerCase().includes(needle)
2021
+ );
2022
+ const records = await Promise.all(
2023
+ [...new Set(matching.map((activity) => activity.recordId))].map((id) => getRecord(ctx.deps, id))
2024
+ );
2025
+ const byId = new Map(
2026
+ records.filter((record) => record !== null).map((record) => [record.id, record])
2027
+ );
2028
+ return matching.flatMap((activity) => {
2029
+ const record = byId.get(activity.recordId);
2030
+ return record ? [activityItem(ctx, req, record, activity)] : [];
2031
+ });
2032
+ }
2033
+ async function search(ctx, req, url) {
2034
+ const limit = capLimit(url.searchParams.get("limit"));
2035
+ const needle = (url.searchParams.get("q") ?? "").trim().toLowerCase().slice(0, 120);
2036
+ const recordPages = await Promise.all(
2037
+ Object.keys(ctx.deps.crm.config.types).map(
2038
+ (type) => listRecords(ctx.deps, {
2039
+ type,
2040
+ ...needle ? { search: needle } : {},
2041
+ limit,
2042
+ offset: 0
2043
+ })
2044
+ )
2045
+ );
2046
+ const records = recordPages.flatMap(
2047
+ (page) => page.records.map((record) => recordItem(ctx, req, record))
2048
+ );
2049
+ const activities = await searchableActivities(ctx, req, needle);
2050
+ return [...records, ...activities].filter((item) => matches(item, needle)).slice(0, limit);
2051
+ }
2052
+ async function handleCrmDiscussionReferences(ctx, req, url) {
2053
+ if (req.method !== "GET") return json({ error: "method not allowed" }, 405);
2054
+ if (ctx.actor.discussionReferenceScope !== "all") {
2055
+ return json({ error: "forbidden" }, 403);
2056
+ }
2057
+ const kind = url.searchParams.get("kind");
2058
+ const id = url.searchParams.get("id");
2059
+ if (kind && !id || !kind && id) {
2060
+ return json({ error: "kind and id must be paired" }, 400);
2061
+ }
2062
+ const target = targetFromQuery(url);
2063
+ if ((kind || id) && !target) return json({ items: [] });
2064
+ return json({
2065
+ items: target ? await exact(ctx, req, target) : await search(ctx, req, url)
2066
+ });
2067
+ }
2068
+
1896
2069
  // src/routes/index.ts
1897
2070
  async function route(ctx, req, url, seg) {
1898
2071
  const [head, id, action, ...rest] = seg;
2072
+ if (head === "discussion-references" && id === void 0)
2073
+ return handleCrmDiscussionReferences(ctx, req, url);
1899
2074
  if (head === "records") {
1900
2075
  if (id === void 0) return handleRecordsRoot(ctx, req, url);
1901
2076
  if (action === void 0) return handleRecordItem(ctx, req, id);
@@ -1926,7 +2101,8 @@ function createCrmRoutes(options) {
1926
2101
  ...options,
1927
2102
  basePath,
1928
2103
  envName: options.envName ?? "development",
1929
- baseUrl: options.baseUrl ?? ""
2104
+ baseUrl: options.baseUrl ?? "",
2105
+ discussionBasePath: options.discussionBasePath ?? "/admin/"
1930
2106
  };
1931
2107
  const deps = {
1932
2108
  crm: options.crm,
@@ -1942,9 +2118,14 @@ function createCrmRoutes(options) {
1942
2118
  try {
1943
2119
  if (segments[0] === "unsubscribe" && segments.length === 1)
1944
2120
  return await handleUnsubscribe(deps, req, url);
1945
- const actor = await options.authorize(req);
2121
+ const discussionReferences = segments[0] === "discussion-references";
2122
+ const actor = discussionReferences && options.authorizeDiscussionReferences ? await options.authorizeDiscussionReferences(req) : await options.authorize(req);
1946
2123
  if (!actor) return json({ error: "unauthorized" }, 401);
1947
- const ctx = { deps, opts, actor };
2124
+ const ctx = {
2125
+ deps,
2126
+ opts,
2127
+ actor: discussionReferences && !options.authorizeDiscussionReferences ? { ...actor, discussionReferenceScope: "all" } : actor
2128
+ };
1948
2129
  return await route(ctx, req, url, segments) ?? json({ error: "not found" }, 404);
1949
2130
  } catch (error) {
1950
2131
  return errorResponse(error);
@@ -2163,6 +2344,7 @@ export {
2163
2344
  ACTIVITY_KINDS,
2164
2345
  CONFIG_KEY,
2165
2346
  CONSENT_STATES,
2347
+ CRM_DISCUSSION_REFERENCE_KINDS,
2166
2348
  CRM_NS,
2167
2349
  CRM_RULES,
2168
2350
  CRM_SCHEMA,
@@ -2189,6 +2371,8 @@ export {
2189
2371
  createCrmIntegration,
2190
2372
  createCrmRoutes,
2191
2373
  createRecord,
2374
+ crmDiscussionReferenceHref,
2375
+ crmDiscussionReferenceId,
2192
2376
  crmIntegration,
2193
2377
  crmRules,
2194
2378
  defaultTemplates,
@@ -2196,6 +2380,7 @@ export {
2196
2380
  deleteView,
2197
2381
  emailChannelOps,
2198
2382
  foldEmailStatus,
2383
+ formatCrmDiscussionReference,
2199
2384
  getConfig,
2200
2385
  getRecord,
2201
2386
  initialStage,
@@ -2212,6 +2397,7 @@ export {
2212
2397
  mustGetRecord,
2213
2398
  needsRebalance,
2214
2399
  normalizeTag,
2400
+ parseCrmDiscussionReference,
2215
2401
  prepare,
2216
2402
  rankBetween,
2217
2403
  rebalancePlan,