clivly 0.20.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/{adapter-BXykDFyG.d.mts → adapter-B4v4dwgD.d.mts} +1 -1
  2. package/{adapter-BiUN_I3u.d.cts → adapter-BK3gsby5.d.cts} +1 -1
  3. package/{auth-adapter-BNvri2gX.d.mts → auth-adapter-BIa-ZyVV.d.mts} +1 -1
  4. package/{auth-adapter-D2MUT1Hk.d.cts → auth-adapter-DwtMJb7D.d.cts} +1 -1
  5. package/auth-better-auth.d.cts +1 -1
  6. package/auth-better-auth.d.mts +1 -1
  7. package/auth-clerk.d.cts +1 -1
  8. package/auth-clerk.d.mts +1 -1
  9. package/auth-workos.d.cts +1 -1
  10. package/auth-workos.d.mts +1 -1
  11. package/core-adapter.d.cts +2 -1
  12. package/core-adapter.d.mts +2 -1
  13. package/core-auth-adapter.d.cts +2 -1
  14. package/core-auth-adapter.d.mts +2 -1
  15. package/core-drizzle.d.cts +1 -1
  16. package/core-drizzle.d.mts +1 -1
  17. package/core-entity-config.cjs +1 -1
  18. package/core-entity-config.d.cts +2 -1
  19. package/core-entity-config.d.mts +2 -1
  20. package/core-entity-config.mjs +1 -1
  21. package/core-entity-heuristics.cjs +1 -1
  22. package/core-entity-heuristics.d.cts +1 -1
  23. package/core-entity-heuristics.d.mts +1 -1
  24. package/core-entity-heuristics.mjs +1 -1
  25. package/core-mapping-form.d.cts +2 -1
  26. package/core-mapping-form.d.mts +2 -1
  27. package/core-mappings-config.cjs +1 -1
  28. package/core-mappings-config.d.cts +2 -1
  29. package/core-mappings-config.d.mts +2 -1
  30. package/core-mappings-config.mjs +1 -1
  31. package/core-sync-engine.cjs +1 -1
  32. package/core-sync-engine.d.cts +2 -1
  33. package/core-sync-engine.d.mts +2 -1
  34. package/core-sync-engine.mjs +1 -1
  35. package/core-types.d.cts +2 -1
  36. package/core-types.d.mts +2 -1
  37. package/core-view-compiler.cjs +1 -1
  38. package/core-view-compiler.d.cts +2 -1
  39. package/core-view-compiler.d.mts +2 -1
  40. package/core-view-compiler.mjs +1 -1
  41. package/core.cjs +7 -7
  42. package/core.d.cts +11 -11
  43. package/core.d.mts +11 -11
  44. package/core.mjs +7 -7
  45. package/{drizzle-B9cjBavj.d.cts → drizzle-BNHGQXiY.d.cts} +1 -1
  46. package/{drizzle-L5FOGe_-.d.mts → drizzle-DFe7ILmd.d.mts} +1 -1
  47. package/drizzle.cjs +2 -2
  48. package/drizzle.d.cts +4 -3
  49. package/drizzle.d.mts +4 -3
  50. package/drizzle.mjs +2 -2
  51. package/{entity-config-DiCJ6mhI.cjs → entity-config-BP8Cc_nC.cjs} +54 -53
  52. package/{entity-config-g_oMPXlN.mjs → entity-config-CI5CGfaN.mjs} +54 -53
  53. package/{entity-config-X-KlnYXX.d.mts → entity-config-CXpGowQa.d.cts} +339 -339
  54. package/{entity-config-dNclLyBM.d.cts → entity-config-CXpGowQa.d.mts} +339 -339
  55. package/{entity-heuristics-DE5ujoHw.mjs → entity-heuristics-DAxqagJA.mjs} +1 -1
  56. package/{entity-heuristics-CIParuQe.cjs → entity-heuristics-DNmrcd0b.cjs} +1 -1
  57. package/index-Bh7o2J7K.d.mts +308 -0
  58. package/index-DRRTE5IJ.d.cts +308 -0
  59. package/index.cjs +53 -8
  60. package/index.mjs +53 -8
  61. package/{internal-9oDwwbNg.mjs → internal-BAw1MCMV.mjs} +99 -10
  62. package/{internal-COALpgov.d.cts → internal-CdfVkh4O.d.mts} +46 -132
  63. package/{internal-D3q4FPcA.d.mts → internal-D7qVRIFb.d.cts} +46 -132
  64. package/{internal-BKYt5j0l.cjs → internal-D88LTRlu.cjs} +99 -10
  65. package/internal-adapter.d.cts +1 -1
  66. package/internal-adapter.d.mts +1 -1
  67. package/internal-auth-adapter.d.cts +1 -1
  68. package/internal-auth-adapter.d.mts +1 -1
  69. package/internal-drizzle.d.cts +1 -1
  70. package/internal-drizzle.d.mts +1 -1
  71. package/internal-entity-config.cjs +1 -1
  72. package/internal-entity-config.d.cts +1 -1
  73. package/internal-entity-config.d.mts +1 -1
  74. package/internal-entity-config.mjs +1 -1
  75. package/internal-entity-heuristics.cjs +1 -1
  76. package/internal-entity-heuristics.d.cts +1 -1
  77. package/internal-entity-heuristics.d.mts +1 -1
  78. package/internal-entity-heuristics.mjs +1 -1
  79. package/internal-mapping-form.d.cts +1 -1
  80. package/internal-mapping-form.d.mts +1 -1
  81. package/internal-mappings-config.cjs +1 -1
  82. package/internal-mappings-config.d.cts +1 -1
  83. package/internal-mappings-config.d.mts +1 -1
  84. package/internal-mappings-config.mjs +1 -1
  85. package/internal-sync-engine.cjs +1 -1
  86. package/internal-sync-engine.d.cts +1 -1
  87. package/internal-sync-engine.d.mts +1 -1
  88. package/internal-sync-engine.mjs +1 -1
  89. package/internal-types.d.cts +1 -1
  90. package/internal-types.d.mts +1 -1
  91. package/internal-view-compiler.cjs +1 -1
  92. package/internal-view-compiler.d.cts +1 -1
  93. package/internal-view-compiler.d.mts +1 -1
  94. package/internal-view-compiler.mjs +1 -1
  95. package/internal.cjs +7 -7
  96. package/internal.d.cts +11 -11
  97. package/internal.d.mts +11 -11
  98. package/internal.mjs +7 -7
  99. package/{mapping-form-Bpvgf5b8.d.mts → mapping-form-Bg_hgNoL.d.cts} +1 -1
  100. package/{mapping-form-CV7y6qox.d.cts → mapping-form-KHUlnC7A.d.mts} +1 -1
  101. package/{mappings-config-CNxBrbt9.cjs → mappings-config-CC-vltWb.cjs} +1 -1
  102. package/{mappings-config-BBppW9fp.d.cts → mappings-config-DNo_Cum_.d.cts} +1 -1
  103. package/{mappings-config-D_g20PyS.mjs → mappings-config-Opw7ZM6Y.mjs} +1 -1
  104. package/{mappings-config-Dmm0H6p_.d.mts → mappings-config-wAe-p1rG.d.mts} +1 -1
  105. package/{namespace-probe-C1tm5rGh.d.cts → namespace-probe-Dh6LFwfo.d.cts} +9 -2
  106. package/{namespace-probe-ah2awcHO.d.mts → namespace-probe-xESu83KG.d.mts} +9 -2
  107. package/package.json +6 -4
  108. package/projection-CzBI2NL8.mjs +95 -0
  109. package/{projection-sql-CHz7KzNS.cjs → projection-sql-BkrHR2ea.cjs} +1 -1
  110. package/{projection-sql-C3gZE3GS.mjs → projection-sql-DQQdjw9I.mjs} +1 -1
  111. package/projection-w4Z6vSL2.cjs +118 -0
  112. package/{sdk-ChyrSl32.mjs → sdk-DfdHv-S9.mjs} +154 -13
  113. package/{sdk-BEHVvB18.cjs → sdk-oUjl5HNU.cjs} +154 -13
  114. package/sdk.cjs +2 -2
  115. package/sdk.d.cts +2 -2
  116. package/sdk.d.mts +2 -2
  117. package/sdk.mjs +2 -2
  118. package/{sync-engine-C7W0Gkq0.d.cts → sync-engine-DCjTr2XQ.d.cts} +2 -2
  119. package/{sync-engine-Di-vF26b.cjs → sync-engine-DNSoZeo0.cjs} +1 -1
  120. package/{sync-engine-C9Q2FkR9.d.mts → sync-engine-UNORma7f.d.mts} +2 -2
  121. package/{sync-engine-CwdLkmch.mjs → sync-engine-yFLEyId3.mjs} +1 -1
  122. package/{types-C08UluBS.d.cts → types-BBfwsDxe.d.cts} +13 -7
  123. package/{types-CZsSYbeC.d.mts → types-BBfwsDxe.d.mts} +13 -7
  124. package/{view-compiler-M23WiVGG.d.mts → view-compiler-BDD93Luw.d.cts} +1 -1
  125. package/{view-compiler-CLTi1VL-.mjs → view-compiler-CSHSqZl7.mjs} +2 -2
  126. package/{view-compiler-cXqt4X-c.d.cts → view-compiler-CSNhmCY2.d.mts} +1 -1
  127. package/{view-compiler-DaOz5QVl.cjs → view-compiler-NqiortOA.cjs} +2 -2
  128. package/vite.d.cts +1 -1
  129. package/vite.d.mts +1 -1
  130. package/integration-state-xK4PLm5T.d.cts +0 -171
  131. package/integration-state-xK4PLm5T.d.mts +0 -171
  132. package/projection-BkYXvjTr.mjs +0 -5587
  133. package/projection-By63gMC-.cjs +0 -5670
  134. package/schemas-BSuo_eZQ.d.cts +0 -2160
  135. package/schemas-BSuo_eZQ.d.mts +0 -2160
package/index.cjs CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const require_entity_config = require("./entity-config-DiCJ6mhI.cjs");
4
- const require_entity_heuristics = require("./entity-heuristics-CIParuQe.cjs");
3
+ const require_entity_config = require("./entity-config-BP8Cc_nC.cjs");
4
+ const require_entity_heuristics = require("./entity-heuristics-DNmrcd0b.cjs");
5
5
  require("./mapping-score-D2TCQiOr.cjs");
6
- const require_sdk = require("./sdk-BEHVvB18.cjs");
6
+ const require_sdk = require("./sdk-oUjl5HNU.cjs");
7
7
  let node_child_process = require("node:child_process");
8
8
  let node_fs = require("node:fs");
9
9
  let node_module = require("node:module");
@@ -2193,6 +2193,30 @@ function nodeOnlyDrivers(dependencies) {
2193
2193
  if (!dependencies) return [];
2194
2194
  return Object.keys(dependencies).filter((name) => NODE_ONLY_DRIVERS.has(name)).sort();
2195
2195
  }
2196
+ const NEXT_EDGE_BUNDLES_DRIVERS_MAJOR = 16;
2197
+ /**
2198
+ * Does this Next.js version need the edge-externals step?
2199
+ *
2200
+ * Only Next <= 15. Next 16 builds with Turbopack by default, and a post-init
2201
+ * Next 16.3 + `pg` app builds clean under Turbopack AND under `next build
2202
+ * --webpack` with no next.config help (verified 2026-11-12). Worse, handing
2203
+ * Turbopack a `webpack` block with no `turbopack` block FAILS the build, so on
2204
+ * 16 the step would break the very app it meant to fix. A version we cannot
2205
+ * read ("latest", "canary") resolves to 16 or later today, so it gets no step.
2206
+ */
2207
+ function nextNeedsEdgeExternals(versionRange) {
2208
+ const major = versionRange ? LEADING_MAJOR.exec(versionRange)?.[1] : void 0;
2209
+ return major !== void 0 && Number(major) < NEXT_EDGE_BUNDLES_DRIVERS_MAJOR;
2210
+ }
2211
+ /**
2212
+ * Does this next.config already externalise every driver on the edge pass?
2213
+ * A text check, not a parse: the developer owns the file and its shape varies,
2214
+ * so it asks only whether the edge branch is there and names each driver.
2215
+ */
2216
+ function nextConfigExternalisesDrivers(source, drivers) {
2217
+ if (!(source?.includes("nextRuntime") && source.includes("externals"))) return false;
2218
+ return drivers.every((d) => source.includes(`"${d}"`) || source.includes(`'${d}'`));
2219
+ }
2196
2220
  /** The next.config step an app needs when its config reaches a Node driver. */
2197
2221
  function nextEdgeExternalsStep(drivers) {
2198
2222
  const list = drivers.map((d) => `"${d}"`).join(", ");
@@ -2773,16 +2797,37 @@ function declaredNextVersion(args) {
2773
2797
  function declaredDependencies(args) {
2774
2798
  return hostManifest(args).dependencies;
2775
2799
  }
2776
- /** The edge-externals step, or null when no Node-only driver is declared. */
2777
- function edgeExternalsStepFor(dependencies) {
2778
- const drivers = nodeOnlyDrivers(dependencies);
2779
- return drivers.length > 0 ? nextEdgeExternalsStep(drivers) : null;
2800
+ const NEXT_CONFIG_CANDIDATES$1 = [
2801
+ "next.config.ts",
2802
+ "next.config.mjs",
2803
+ "next.config.js",
2804
+ "next.config.cjs",
2805
+ "next.config.mts"
2806
+ ];
2807
+ function nextConfigSource(args) {
2808
+ for (const candidate of NEXT_CONFIG_CANDIDATES$1) {
2809
+ const source = args.readFile((0, node_path.join)(args.cwd, candidate));
2810
+ if (source !== null) return source;
2811
+ }
2812
+ return null;
2813
+ }
2814
+ /**
2815
+ * The edge-externals step, or null when it does not apply: no Node-only driver,
2816
+ * Next >= 16 (whose edge pass bundles the driver unaided), or a next.config that already has
2817
+ * the edge externals in place.
2818
+ */
2819
+ function edgeExternalsStepFor(args) {
2820
+ const drivers = nodeOnlyDrivers(declaredDependencies(args));
2821
+ if (drivers.length === 0) return null;
2822
+ if (!nextNeedsEdgeExternals(declaredNextVersion(args))) return null;
2823
+ if (nextConfigExternalisesDrivers(nextConfigSource(args), drivers)) return null;
2824
+ return nextEdgeExternalsStep(drivers);
2780
2825
  }
2781
2826
  function planBootPatch(args) {
2782
2827
  if (bootHookPath(args.framework, args.layout) !== null) return {
2783
2828
  file: null,
2784
2829
  manual: args.framework === "nextjs" && nextNeedsInstrumentationFlag(declaredNextVersion(args)) ? NEXT_INSTRUMENTATION_FLAG_STEP : null,
2785
- extra: args.framework === "nextjs" ? edgeExternalsStepFor(declaredDependencies(args)) : null
2830
+ extra: args.framework === "nextjs" ? edgeExternalsStepFor(args) : null
2786
2831
  };
2787
2832
  if (args.framework === "remix") return {
2788
2833
  file: null,
package/index.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import { t as CANONICAL_FIELDS } from "./entity-config-g_oMPXlN.mjs";
3
- import { d as suggestCursorField, i as isFrameworkTable, l as scoreFieldMap, n as hasDefiningColumn, o as matchesConcept, p as toFieldMap, s as requiredFieldsFor, u as scoreRelationships } from "./entity-heuristics-DE5ujoHw.mjs";
2
+ import { t as CANONICAL_FIELDS } from "./entity-config-CI5CGfaN.mjs";
3
+ import { d as suggestCursorField, i as isFrameworkTable, l as scoreFieldMap, n as hasDefiningColumn, o as matchesConcept, p as toFieldMap, s as requiredFieldsFor, u as scoreRelationships } from "./entity-heuristics-DAxqagJA.mjs";
4
4
  import "./mapping-score-CS-MTDL9.mjs";
5
- import { n as createClivlySDK, u as isPlaceholderUrl } from "./sdk-ChyrSl32.mjs";
5
+ import { n as createClivlySDK, u as isPlaceholderUrl } from "./sdk-DfdHv-S9.mjs";
6
6
  import { createRequire } from "node:module";
7
7
  import { spawn } from "node:child_process";
8
8
  import { accessSync, constants, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, watch, writeFileSync } from "node:fs";
@@ -2192,6 +2192,30 @@ function nodeOnlyDrivers(dependencies) {
2192
2192
  if (!dependencies) return [];
2193
2193
  return Object.keys(dependencies).filter((name) => NODE_ONLY_DRIVERS.has(name)).sort();
2194
2194
  }
2195
+ const NEXT_EDGE_BUNDLES_DRIVERS_MAJOR = 16;
2196
+ /**
2197
+ * Does this Next.js version need the edge-externals step?
2198
+ *
2199
+ * Only Next <= 15. Next 16 builds with Turbopack by default, and a post-init
2200
+ * Next 16.3 + `pg` app builds clean under Turbopack AND under `next build
2201
+ * --webpack` with no next.config help (verified 2026-11-12). Worse, handing
2202
+ * Turbopack a `webpack` block with no `turbopack` block FAILS the build, so on
2203
+ * 16 the step would break the very app it meant to fix. A version we cannot
2204
+ * read ("latest", "canary") resolves to 16 or later today, so it gets no step.
2205
+ */
2206
+ function nextNeedsEdgeExternals(versionRange) {
2207
+ const major = versionRange ? LEADING_MAJOR.exec(versionRange)?.[1] : void 0;
2208
+ return major !== void 0 && Number(major) < NEXT_EDGE_BUNDLES_DRIVERS_MAJOR;
2209
+ }
2210
+ /**
2211
+ * Does this next.config already externalise every driver on the edge pass?
2212
+ * A text check, not a parse: the developer owns the file and its shape varies,
2213
+ * so it asks only whether the edge branch is there and names each driver.
2214
+ */
2215
+ function nextConfigExternalisesDrivers(source, drivers) {
2216
+ if (!(source?.includes("nextRuntime") && source.includes("externals"))) return false;
2217
+ return drivers.every((d) => source.includes(`"${d}"`) || source.includes(`'${d}'`));
2218
+ }
2195
2219
  /** The next.config step an app needs when its config reaches a Node driver. */
2196
2220
  function nextEdgeExternalsStep(drivers) {
2197
2221
  const list = drivers.map((d) => `"${d}"`).join(", ");
@@ -2772,16 +2796,37 @@ function declaredNextVersion(args) {
2772
2796
  function declaredDependencies(args) {
2773
2797
  return hostManifest(args).dependencies;
2774
2798
  }
2775
- /** The edge-externals step, or null when no Node-only driver is declared. */
2776
- function edgeExternalsStepFor(dependencies) {
2777
- const drivers = nodeOnlyDrivers(dependencies);
2778
- return drivers.length > 0 ? nextEdgeExternalsStep(drivers) : null;
2799
+ const NEXT_CONFIG_CANDIDATES$1 = [
2800
+ "next.config.ts",
2801
+ "next.config.mjs",
2802
+ "next.config.js",
2803
+ "next.config.cjs",
2804
+ "next.config.mts"
2805
+ ];
2806
+ function nextConfigSource(args) {
2807
+ for (const candidate of NEXT_CONFIG_CANDIDATES$1) {
2808
+ const source = args.readFile(join(args.cwd, candidate));
2809
+ if (source !== null) return source;
2810
+ }
2811
+ return null;
2812
+ }
2813
+ /**
2814
+ * The edge-externals step, or null when it does not apply: no Node-only driver,
2815
+ * Next >= 16 (whose edge pass bundles the driver unaided), or a next.config that already has
2816
+ * the edge externals in place.
2817
+ */
2818
+ function edgeExternalsStepFor(args) {
2819
+ const drivers = nodeOnlyDrivers(declaredDependencies(args));
2820
+ if (drivers.length === 0) return null;
2821
+ if (!nextNeedsEdgeExternals(declaredNextVersion(args))) return null;
2822
+ if (nextConfigExternalisesDrivers(nextConfigSource(args), drivers)) return null;
2823
+ return nextEdgeExternalsStep(drivers);
2779
2824
  }
2780
2825
  function planBootPatch(args) {
2781
2826
  if (bootHookPath(args.framework, args.layout) !== null) return {
2782
2827
  file: null,
2783
2828
  manual: args.framework === "nextjs" && nextNeedsInstrumentationFlag(declaredNextVersion(args)) ? NEXT_INSTRUMENTATION_FLAG_STEP : null,
2784
- extra: args.framework === "nextjs" ? edgeExternalsStepFor(declaredDependencies(args)) : null
2829
+ extra: args.framework === "nextjs" ? edgeExternalsStepFor(args) : null
2785
2830
  };
2786
2831
  if (args.framework === "remix") return {
2787
2832
  file: null,
@@ -1,9 +1,9 @@
1
- import { a as _enum, o as array, p as string, u as object } from "./projection-BkYXvjTr.mjs";
1
+ import { z } from "zod";
2
2
  // ../core/src/contact-segment.ts
3
3
  /** AND conditions over deliberately mapped host fields, never SQL identifiers. */
4
- const contactSegmentSchema = array(object({
5
- field: string().min(1).max(160),
6
- operator: _enum([
4
+ const contactSegmentSchema = z.array(z.object({
5
+ field: z.string().min(1).max(160),
6
+ operator: z.enum([
7
7
  "equals",
8
8
  "not_equals",
9
9
  "contains",
@@ -14,7 +14,7 @@ const contactSegmentSchema = array(object({
14
14
  "is_set",
15
15
  "is_not_set"
16
16
  ]),
17
- value: string().max(1e3).optional()
17
+ value: z.string().max(1e3).optional()
18
18
  }).strict().superRefine((rule, ctx) => {
19
19
  if (!["is_set", "is_not_set"].includes(rule.operator) && rule.value === void 0) ctx.addIssue({
20
20
  code: "custom",
@@ -32,8 +32,57 @@ const contactSegmentSchema = array(object({
32
32
  })).max(20);
33
33
  // ../core/src/deal-value.ts
34
34
  const MONTHS_PER_YEAR = 12;
35
+ const MONTHS_PER_QUARTER = 3;
36
+ const WEEKS_PER_YEAR = 52;
35
37
  /** Only two decimal-free seat counts make sense; anything else is bad data. */
36
38
  const SEAT_COUNT_REGEX = /^\d+$/;
39
+ const WHOLE_NUMBER_REGEX = /^\d+$/;
40
+ const DECIMAL_AMOUNT_REGEX = /^(\d+)(?:\.(\d{1,2}))?$/;
41
+ const INTERVAL_SYNONYMS = {
42
+ annual: "year",
43
+ annually: "year",
44
+ month: "month",
45
+ monthly: "month",
46
+ quarter: "quarter",
47
+ quarterly: "quarter",
48
+ week: "week",
49
+ weekly: "week",
50
+ year: "year",
51
+ yearly: "year"
52
+ };
53
+ /**
54
+ * Monthly share of one charge, as a fraction so the division happens once.
55
+ * A week is 52/12 of a month's worth per month: 52 charges a year, spread
56
+ * over twelve months.
57
+ */
58
+ const MONTHLY_FRACTION = {
59
+ month: {
60
+ denominator: 1,
61
+ numerator: 1
62
+ },
63
+ quarter: {
64
+ denominator: MONTHS_PER_QUARTER,
65
+ numerator: 1
66
+ },
67
+ week: {
68
+ denominator: MONTHS_PER_YEAR,
69
+ numerator: WEEKS_PER_YEAR
70
+ },
71
+ year: {
72
+ denominator: MONTHS_PER_YEAR,
73
+ numerator: 1
74
+ }
75
+ };
76
+ /**
77
+ * The billing interval a row names. `undefined` when no interval column is
78
+ * configured or mapped; `null` when it holds something unrecognised.
79
+ */
80
+ function readInterval(intervalField, fields, mappedFields) {
81
+ if (intervalField === void 0 || !mappedFields.has(intervalField)) return;
82
+ const raw = fields[intervalField]?.trim().toLowerCase();
83
+ if (!raw) return null;
84
+ return INTERVAL_SYNONYMS[raw] ?? null;
85
+ }
37
86
  /**
38
87
  * The value one deal should have, in cents, or null to leave it alone.
39
88
  *
@@ -45,15 +94,25 @@ const SEAT_COUNT_REGEX = /^\d+$/;
45
94
  */
46
95
  function computeDealValue(source, fields, mappedFields, stageType) {
47
96
  if (source.zeroInStageTypes?.includes(stageType)) return 0;
97
+ if (source.kind === "mapped_amount") return computeMappedAmount(source, fields, mappedFields);
98
+ return computePerSeat(source, fields, mappedFields);
99
+ }
100
+ function computePerSeat(source, fields, mappedFields) {
48
101
  if (!(mappedFields.has(source.seatField) && mappedFields.has(source.planField))) return null;
49
102
  const planKey = fields[source.planField];
50
103
  if (planKey == null || planKey === "") return null;
51
- const unitPriceCents = source.plans[planKey];
52
- if (unitPriceCents === void 0) return null;
53
104
  const rawSeats = fields[source.seatField];
54
105
  if (rawSeats == null || !SEAT_COUNT_REGEX.test(rawSeats)) return null;
55
106
  const seats = Number(rawSeats);
56
107
  if (!Number.isSafeInteger(seats)) return null;
108
+ const yearlyPrice = source.yearlyPlans?.[planKey];
109
+ if (yearlyPrice !== void 0 && readInterval(source.intervalField, fields, mappedFields) === "year") {
110
+ const yearly = (source.yearlyBaseFeeCents ?? (source.baseFeeCents ?? 0) * MONTHS_PER_YEAR) + seats * yearlyPrice;
111
+ if (!Number.isSafeInteger(yearly) || yearly < 0) return null;
112
+ return Math.round(yearly / MONTHS_PER_YEAR);
113
+ }
114
+ const unitPriceCents = source.plans[planKey];
115
+ if (unitPriceCents === void 0) return null;
57
116
  const monthly = (source.baseFeeCents ?? 0) + seats * unitPriceCents;
58
117
  if (!Number.isSafeInteger(monthly) || monthly < 0) return null;
59
118
  return normalizePrice(monthly, source, fields, mappedFields);
@@ -62,13 +121,43 @@ function computeDealValue(source, fields, mappedFields, stageType) {
62
121
  function normalizePrice(monthly, source, fields, mappedFields) {
63
122
  if (source.priceBasis === "monthly") return monthly;
64
123
  if (source.priceBasis === "billing_interval") {
65
- const interval = source.intervalField && mappedFields.has(source.intervalField) ? fields[source.intervalField]?.trim().toLowerCase() : null;
66
- if (interval === "month" || interval === "monthly") return monthly;
67
- if (interval === "year" || interval === "annual" || interval === "annually" || interval === "yearly") return Math.round(monthly / MONTHS_PER_YEAR);
124
+ const interval = readInterval(source.intervalField, fields, mappedFields);
125
+ if (interval === "month") return monthly;
126
+ if (interval === "year") return Math.round(monthly / MONTHS_PER_YEAR);
68
127
  return null;
69
128
  }
70
129
  return source.intervalField !== void 0 && mappedFields.has(source.intervalField) && fields[source.intervalField] === "year" ? Math.round(monthly / MONTHS_PER_YEAR) : monthly;
71
130
  }
131
+ /** A host amount in cents, or null when it is not one. */
132
+ function parseAmount(raw, unit) {
133
+ const text = raw?.trim();
134
+ if (!text) return null;
135
+ if (unit === "cents") return WHOLE_NUMBER_REGEX.test(text) ? Number(text) : null;
136
+ const match = DECIMAL_AMOUNT_REGEX.exec(text);
137
+ if (!match) return null;
138
+ const [, whole, fraction = ""] = match;
139
+ return Number(whole) * 100 + Number(fraction.padEnd(2, "0"));
140
+ }
141
+ function computeMappedAmount(source, fields, mappedFields) {
142
+ if (!mappedFields.has(source.amountField)) return null;
143
+ const amount = parseAmount(fields[source.amountField], source.amountUnit);
144
+ if (amount === null || !Number.isSafeInteger(amount)) return null;
145
+ const interval = source.intervalField === void 0 ? "month" : readInterval(source.intervalField, fields, mappedFields);
146
+ if (!interval) return null;
147
+ let count = 1;
148
+ if (source.intervalCountField !== void 0) {
149
+ if (!mappedFields.has(source.intervalCountField)) return null;
150
+ const rawCount = fields[source.intervalCountField]?.trim();
151
+ if (rawCount) {
152
+ if (!WHOLE_NUMBER_REGEX.test(rawCount) || Number(rawCount) < 1) return null;
153
+ count = Number(rawCount);
154
+ }
155
+ }
156
+ const { denominator, numerator } = MONTHLY_FRACTION[interval];
157
+ const scaled = amount * numerator;
158
+ if (!Number.isSafeInteger(scaled)) return null;
159
+ return Math.round(scaled / (denominator * count));
160
+ }
72
161
  // ../core/src/host-owned-fields.ts
73
162
  /**
74
163
  * Which fields a CRM record lets a user edit.
@@ -1,4 +1,4 @@
1
- import { L as ProjectionJoin, R as ProjectionMapping, h as FilterExpr, l as ConfigValidationError, m as DiscoveredSchemaTable, p as DiscoveredColumnMeta } from "./entity-config-dNclLyBM.cjs";
1
+ import "./index-Bh7o2J7K.mjs";
2
2
  /**
3
3
  * Value derived as a flat fee plus a per-seat price that depends on the plan.
4
4
  *
@@ -21,9 +21,52 @@ interface PerSeatValueSource {
21
21
  priceBasis?: "monthly" | "billing_interval";
22
22
  /** Mapped column holding the seat count. */
23
23
  seatField: string;
24
+ /**
25
+ * Annual flat fee in cents, for rows billed yearly at a yearly price. When
26
+ * absent, an annual row with a yearly plan price uses twelve times
27
+ * `baseFeeCents`, which is a monthly fee.
28
+ */
29
+ yearlyBaseFeeCents?: number;
30
+ /**
31
+ * Annual list price per seat in cents, keyed like `plans`. A row billed
32
+ * yearly whose plan has one is valued at (annual fee + seats × this) ÷ 12.
33
+ * One `plans` map cannot be both a monthly and a yearly price, which is why
34
+ * an annual plan that is not simply twelve months needs its own number.
35
+ */
36
+ yearlyPlans?: Record<string, number>;
24
37
  /** Stage types whose deals are worth nothing (usually `["lost"]`). */
25
38
  zeroInStageTypes?: string[];
26
39
  }
40
+ /**
41
+ * Value read from an amount the host's billing system already knows.
42
+ *
43
+ * The recommended source whenever the host has it: negotiated prices,
44
+ * discounts and multi-item subscriptions are all already in the billed
45
+ * amount, so Clivly does not have to model a price book to get them right.
46
+ */
47
+ interface MappedAmountValueSource {
48
+ /** Mapped column holding the amount charged each billing period. */
49
+ amountField: string;
50
+ /**
51
+ * How the amount is written: `cents` for minor units (Stripe's `amount`,
52
+ * `1250`), `units` for a decimal amount (`12.50`).
53
+ */
54
+ amountUnit: "cents" | "units";
55
+ /**
56
+ * Mapped column holding how many intervals one charge covers (Stripe's
57
+ * `interval_count`: 3 with `month` is quarterly). Absent means 1.
58
+ */
59
+ intervalCountField?: string;
60
+ /**
61
+ * Mapped column holding the billing interval: month, quarter, year or week.
62
+ * Absent means every amount is already monthly.
63
+ */
64
+ intervalField?: string;
65
+ kind: "mapped_amount";
66
+ /** Stage types whose deals are worth nothing (usually `["lost"]`). */
67
+ zeroInStageTypes?: string[];
68
+ }
69
+ type DealValueSource = PerSeatValueSource | MappedAmountValueSource;
27
70
  /**
28
71
  * The value one deal should have, in cents, or null to leave it alone.
29
72
  *
@@ -33,7 +76,7 @@ interface PerSeatValueSource {
33
76
  * unmapped case is surfaced through the rule-health warning surface instead of
34
77
  * being written into the data — the same fail-safe `matchesCondition` applies.
35
78
  */
36
- declare function computeDealValue(source: PerSeatValueSource, fields: Record<string, string | null>, mappedFields: Set<string>, stageType: string): number | null;
79
+ declare function computeDealValue(source: DealValueSource, fields: Record<string, string | null>, mappedFields: Set<string>, stageType: string): number | null;
37
80
  /**
38
81
  * Which fields a CRM record lets a user edit.
39
82
  *
@@ -99,135 +142,6 @@ declare function rejectedCompanyFields(company: SourcedRecord, patch: Readonly<R
99
142
  * they come from, so the reason is actionable rather than a bare "forbidden".
100
143
  */
101
144
  declare function hostOwnedFieldMessage(fields: readonly string[]): string;
102
- declare function joinFansOut(join: ProjectionJoin, joinTable: DiscoveredSchemaTable): boolean;
103
- /** Every join in the projection that can multiply rows. */
104
- declare function fanOutJoins(projection: ProjectionMapping, tablesByName: Map<string, DiscoveredSchemaTable>): ProjectionJoin[];
105
- /**
106
- * SQL generation for projection-backed entities.
107
- *
108
- * Base and joins are aliased by their ref key (`base`, then each join's `key`),
109
- * which is what allows the same table to be joined twice and keeps generated
110
- * SQL independent of host table names.
111
- *
112
- * Pure string generation — no DB access. Identifiers are escaped so output is
113
- * deterministic and injection-safe.
114
- */
115
- /** Quote a single identifier part, escaping embedded double-quotes. */
116
- declare function quoteIdent(name: string): string;
117
- /**
118
- * The identity expression. Composite identities concatenate their parts with
119
- * `::`; validation guarantees every part is NOT NULL and non-text, which is
120
- * what makes the concatenation collision-free.
121
- *
122
- * Exported unaliased because two paths need the same expression under different
123
- * names: the view compiler aliases it `id`, and the SDK's projection push source
124
- * also orders and keyset-paginates by it. Sharing one definition is what keeps
125
- * a pushed row's `id` identical to the one the view would have produced.
126
- */
127
- declare function compileProjectionIdentity(projection: ProjectionMapping, basePkColumn: string): string;
128
- declare function compileProjectionSelect(projection: ProjectionMapping, basePkColumn: string): {
129
- columns: string[];
130
- selectItems: string[];
131
- };
132
- declare function compileProjectionJoins(projection: ProjectionMapping): string[];
133
- /** `FROM <baseTable> AS "base"` — the alias every ref resolves against. */
134
- declare function compileProjectionFrom(projection: ProjectionMapping): string;
135
- /**
136
- * Hard ceiling on preview rows, regardless of what a caller asks for.
137
- *
138
- * A preview runs against a production database from a button a user can click
139
- * as often as they like, so the cap belongs beside the query rather than in
140
- * whichever caller happens to be passing a limit today.
141
- */
142
- declare const PREVIEW_MAX_ROWS = 50;
143
- /**
144
- * One SELECT reading a few rows through an UNSAVED projection, for the derived
145
- * object builder's preview.
146
- *
147
- * Lives here, beside the view compiler, because both sides of the round trip
148
- * need the identical statement: an embedded org runs it against its own
149
- * database from `@clivly.com/api`, and a cloud org's host app runs it from
150
- * `@clivly/sdk`. Two copies would be free to disagree about what the user is
151
- * being shown, which is the whole value of a preview.
152
- *
153
- * Columns are aliased by FIELD NAME, not by ref token. That is the deliberate
154
- * difference from the push source, which aliases by token because cloud ingest
155
- * reads `row[token]`; a preview is read by a person, in a table whose headers
156
- * are the field names they just typed.
157
- */
158
- declare function compileProjectionPreview(projection: ProjectionMapping, limit: number): string;
159
- /**
160
- * A derived object's filter is evaluated in the cloud against pushed rows, so
161
- * it can only name columns of the base table.
162
- *
163
- * Every rejected shape here fails *silently* today, which is the whole reason
164
- * the check exists — a filter that cannot be honoured must error, never quietly
165
- * return the wrong rows. The three shapes fail in different directions:
166
- *
167
- * - `$raw` is opaque SQL meant for the embedded model. The cloud path cannot
168
- * evaluate it and passes every row, so the filter is ignored and the object
169
- * syncs UNFILTERED.
170
- * - A joined-table column resolves to nothing on a pushed row, so under a
171
- * positive operator (`eq`, `in`) no row matches and the object syncs EMPTY.
172
- * - The same unresolvable column under a NEGATIVE operator (`ne`, `isNull`,
173
- * `notIn`) is the dangerous one: the missing cell reads as null, so the
174
- * predicate is true for every row and a filter meant to narrow the sync
175
- * ADMITS EVERYTHING. Nobody notices extra rows arriving.
176
- *
177
- * Rejecting an unresolvable column closes the last two together.
178
- */
179
- declare function validateProjectionFilter(filter: FilterExpr | undefined, projection: ProjectionMapping, schema: DiscoveredSchemaTable[], base: string): ConfigValidationError[];
180
- /**
181
- * Validate a projection against the discovered schema. Returns every error
182
- * found (not just the first) so a builder UI can show them all at once.
183
- */
184
- declare function validateProjection(projection: ProjectionMapping, schema: DiscoveredSchemaTable[], base: string): ConfigValidationError[];
185
- /**
186
- * Accessors over a discovered table's schema-v2 metadata.
187
- *
188
- * Every helper treats *absent* metadata as **unknown**, never as a negative
189
- * fact. `coversUniqueKey` returning false on a v1 payload is what makes
190
- * projection validation fail closed: we cannot prove a join is many-to-one, so
191
- * we refuse to compile it rather than guess.
192
- */
193
- declare function columnMetaFor(table: DiscoveredSchemaTable, column: string): DiscoveredColumnMeta | undefined;
194
- /**
195
- * Every primary-key column. More than one entry means a composite PK, which is
196
- * why `base_pk` identity is rejected for such tables.
197
- */
198
- declare function primaryKeyColumns(table: DiscoveredSchemaTable): string[];
199
- /**
200
- * Do `columns` contain every column of at least one unique key on `table`?
201
- *
202
- * This is the fan-out test. A join whose ON columns cover a unique key of the
203
- * joined table matches at most one row per base row; one that does not can
204
- * match many.
205
- */
206
- declare function coversUniqueKey(table: DiscoveredSchemaTable, columns: string[]): boolean;
207
- /**
208
- * A discovered table whose enrichment metadata is known to be present.
209
- *
210
- * This narrows only the *presence* of the two optional fields. It says nothing
211
- * about their contents — an empty `uniqueConstraints` is a known-empty fact
212
- * (the table genuinely has no unique keys), which is exactly the distinction
213
- * `hasRichMeta` has always drawn and must keep drawing.
214
- */
215
- type RichMetaTable = DiscoveredSchemaTable & {
216
- columnsMeta: DiscoveredColumnMeta[];
217
- uniqueConstraints: string[][];
218
- };
219
- /**
220
- * Is this table's payload rich enough to validate a projection against?
221
- *
222
- * A type predicate rather than a plain boolean so the narrowing is visible to
223
- * the compiler: callers that guard on this can iterate `columnsMeta` directly
224
- * instead of casting, and a cast that outlives its guard becomes a type error
225
- * rather than a silent walk over `undefined`.
226
- *
227
- * The invariant is unchanged: this reports whether the metadata is *known*,
228
- * never whether the table has keys. Absent metadata stays UNKNOWN.
229
- */
230
- declare function hasRichMeta(table: DiscoveredSchemaTable): table is RichMetaTable;
231
145
  /**
232
146
  * The one `slugify`.
233
147
  *
@@ -311,4 +225,4 @@ declare function matchesCondition(condition: Condition, fields: Record<string, s
311
225
  * a half-written rule should do.
312
226
  */
313
227
  declare function evaluateStage(rules: EvaluableRule[], fields: Record<string, string | null>, mappedFields: Set<string>): string | null;
314
- export { PerSeatValueSource as A, HostOwnedCompanyField as C, isHostOwned as D, hostOwnedFieldMessage as E, rejectedCompanyFields as O, joinFansOut as S, SourcedRecord as T, compileProjectionJoins as _, matchesCondition as a, quoteIdent as b, columnMetaFor as c, primaryKeyColumns as d, validateProjection as f, compileProjectionIdentity as g, compileProjectionFrom as h, evaluateStage as i, computeDealValue as j, rejectedContactFields as k, coversUniqueKey as l, PREVIEW_MAX_ROWS as m, ConditionOp as n, slugify as o, validateProjectionFilter as p, EvaluableRule as r, toObjectTypeSlug as s, Condition as t, hasRichMeta as u, compileProjectionPreview as v, HostOwnedContactField as w, fanOutJoins as x, compileProjectionSelect as y };
228
+ export { PerSeatValueSource as _, matchesCondition as a, HostOwnedCompanyField as c, hostOwnedFieldMessage as d, isHostOwned as f, MappedAmountValueSource as g, DealValueSource as h, evaluateStage as i, HostOwnedContactField as l, rejectedContactFields as m, ConditionOp as n, slugify as o, rejectedCompanyFields as p, EvaluableRule as r, toObjectTypeSlug as s, Condition as t, SourcedRecord as u, computeDealValue as v };