hinmil 0.0.0-stage → 0.2.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 (301) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +2306 -2
  3. package/dist/cli.d.ts +15 -0
  4. package/dist/cli.d.ts.map +1 -0
  5. package/dist/cli.js +338 -0
  6. package/dist/cli.js.map +1 -0
  7. package/dist/commentParser.d.ts +384 -0
  8. package/dist/commentParser.d.ts.map +1 -0
  9. package/dist/commentParser.js +2487 -0
  10. package/dist/commentParser.js.map +1 -0
  11. package/dist/config.d.ts +203 -0
  12. package/dist/config.d.ts.map +1 -0
  13. package/dist/config.js +375 -0
  14. package/dist/config.js.map +1 -0
  15. package/dist/debugLog.d.ts +13 -0
  16. package/dist/debugLog.d.ts.map +1 -0
  17. package/dist/debugLog.js +44 -0
  18. package/dist/debugLog.js.map +1 -0
  19. package/dist/estree.d.ts +100 -0
  20. package/dist/estree.d.ts.map +1 -0
  21. package/dist/estree.js +34 -0
  22. package/dist/estree.js.map +1 -0
  23. package/dist/hm/env.d.ts +134 -0
  24. package/dist/hm/env.d.ts.map +1 -0
  25. package/dist/hm/env.js +939 -0
  26. package/dist/hm/env.js.map +1 -0
  27. package/dist/hm/index.d.ts +7 -0
  28. package/dist/hm/index.d.ts.map +1 -0
  29. package/dist/hm/index.js +26 -0
  30. package/dist/hm/index.js.map +1 -0
  31. package/dist/hm/substitution.d.ts +57 -0
  32. package/dist/hm/substitution.d.ts.map +1 -0
  33. package/dist/hm/substitution.js +546 -0
  34. package/dist/hm/substitution.js.map +1 -0
  35. package/dist/hm/typeParser.d.ts +39 -0
  36. package/dist/hm/typeParser.d.ts.map +1 -0
  37. package/dist/hm/typeParser.js +1285 -0
  38. package/dist/hm/typeParser.js.map +1 -0
  39. package/dist/hm/typeUtils.d.ts +248 -0
  40. package/dist/hm/typeUtils.d.ts.map +1 -0
  41. package/dist/hm/typeUtils.js +905 -0
  42. package/dist/hm/typeUtils.js.map +1 -0
  43. package/dist/hm/types.d.ts +738 -0
  44. package/dist/hm/types.d.ts.map +1 -0
  45. package/dist/hm/types.js +1853 -0
  46. package/dist/hm/types.js.map +1 -0
  47. package/dist/hm/unify.d.ts +59 -0
  48. package/dist/hm/unify.d.ts.map +1 -0
  49. package/dist/hm/unify.js +1700 -0
  50. package/dist/hm/unify.js.map +1 -0
  51. package/dist/index.d.ts +20 -0
  52. package/dist/index.d.ts.map +1 -0
  53. package/dist/index.js +196 -0
  54. package/dist/index.js.map +1 -0
  55. package/dist/infer/annotation-rigid.d.ts +76 -0
  56. package/dist/infer/annotation-rigid.d.ts.map +1 -0
  57. package/dist/infer/annotation-rigid.js +542 -0
  58. package/dist/infer/annotation-rigid.js.map +1 -0
  59. package/dist/infer/annotation-validation.d.ts +109 -0
  60. package/dist/infer/annotation-validation.d.ts.map +1 -0
  61. package/dist/infer/annotation-validation.js +1078 -0
  62. package/dist/infer/annotation-validation.js.map +1 -0
  63. package/dist/infer/annotations.d.ts +277 -0
  64. package/dist/infer/annotations.d.ts.map +1 -0
  65. package/dist/infer/annotations.js +1343 -0
  66. package/dist/infer/annotations.js.map +1 -0
  67. package/dist/infer/call-overloads.d.ts +24 -0
  68. package/dist/infer/call-overloads.d.ts.map +1 -0
  69. package/dist/infer/call-overloads.js +900 -0
  70. package/dist/infer/call-overloads.js.map +1 -0
  71. package/dist/infer/call-rows.d.ts +154 -0
  72. package/dist/infer/call-rows.d.ts.map +1 -0
  73. package/dist/infer/call-rows.js +2162 -0
  74. package/dist/infer/call-rows.js.map +1 -0
  75. package/dist/infer/calls.d.ts +20 -0
  76. package/dist/infer/calls.d.ts.map +1 -0
  77. package/dist/infer/calls.js +1468 -0
  78. package/dist/infer/calls.js.map +1 -0
  79. package/dist/infer/constraints.d.ts +99 -0
  80. package/dist/infer/constraints.d.ts.map +1 -0
  81. package/dist/infer/constraints.js +1208 -0
  82. package/dist/infer/constraints.js.map +1 -0
  83. package/dist/infer/expr-assignment.d.ts +20 -0
  84. package/dist/infer/expr-assignment.d.ts.map +1 -0
  85. package/dist/infer/expr-assignment.js +620 -0
  86. package/dist/infer/expr-assignment.js.map +1 -0
  87. package/dist/infer/expr-constraint-lookup.d.ts +44 -0
  88. package/dist/infer/expr-constraint-lookup.d.ts.map +1 -0
  89. package/dist/infer/expr-constraint-lookup.js +207 -0
  90. package/dist/infer/expr-constraint-lookup.js.map +1 -0
  91. package/dist/infer/expr-functions.d.ts +20 -0
  92. package/dist/infer/expr-functions.d.ts.map +1 -0
  93. package/dist/infer/expr-functions.js +1359 -0
  94. package/dist/infer/expr-functions.js.map +1 -0
  95. package/dist/infer/expr-jsx.d.ts +19 -0
  96. package/dist/infer/expr-jsx.d.ts.map +1 -0
  97. package/dist/infer/expr-jsx.js +310 -0
  98. package/dist/infer/expr-jsx.js.map +1 -0
  99. package/dist/infer/expr-member.d.ts +40 -0
  100. package/dist/infer/expr-member.d.ts.map +1 -0
  101. package/dist/infer/expr-member.js +1154 -0
  102. package/dist/infer/expr-member.js.map +1 -0
  103. package/dist/infer/expr-prototype.d.ts +11 -0
  104. package/dist/infer/expr-prototype.d.ts.map +1 -0
  105. package/dist/infer/expr-prototype.js +202 -0
  106. package/dist/infer/expr-prototype.js.map +1 -0
  107. package/dist/infer/expressions.d.ts +40 -0
  108. package/dist/infer/expressions.d.ts.map +1 -0
  109. package/dist/infer/expressions.js +1497 -0
  110. package/dist/infer/expressions.js.map +1 -0
  111. package/dist/infer/functionPatterns.d.ts +229 -0
  112. package/dist/infer/functionPatterns.d.ts.map +1 -0
  113. package/dist/infer/functionPatterns.js +1035 -0
  114. package/dist/infer/functionPatterns.js.map +1 -0
  115. package/dist/infer/helpers.d.ts +73 -0
  116. package/dist/infer/helpers.d.ts.map +1 -0
  117. package/dist/infer/helpers.js +187 -0
  118. package/dist/infer/helpers.js.map +1 -0
  119. package/dist/infer/index.d.ts +551 -0
  120. package/dist/infer/index.d.ts.map +1 -0
  121. package/dist/infer/index.js +1127 -0
  122. package/dist/infer/index.js.map +1 -0
  123. package/dist/infer/jsx-dom.d.ts +26 -0
  124. package/dist/infer/jsx-dom.d.ts.map +1 -0
  125. package/dist/infer/jsx-dom.js +303 -0
  126. package/dist/infer/jsx-dom.js.map +1 -0
  127. package/dist/infer/moduleReps.d.ts +7 -0
  128. package/dist/infer/moduleReps.d.ts.map +1 -0
  129. package/dist/infer/moduleReps.js +48 -0
  130. package/dist/infer/moduleReps.js.map +1 -0
  131. package/dist/infer/modules.d.ts +10 -0
  132. package/dist/infer/modules.d.ts.map +1 -0
  133. package/dist/infer/modules.js +775 -0
  134. package/dist/infer/modules.js.map +1 -0
  135. package/dist/infer/narrowing.d.ts +199 -0
  136. package/dist/infer/narrowing.d.ts.map +1 -0
  137. package/dist/infer/narrowing.js +1428 -0
  138. package/dist/infer/narrowing.js.map +1 -0
  139. package/dist/infer/results.d.ts +24 -0
  140. package/dist/infer/results.d.ts.map +1 -0
  141. package/dist/infer/results.js +611 -0
  142. package/dist/infer/results.js.map +1 -0
  143. package/dist/infer/setupPass.d.ts +11 -0
  144. package/dist/infer/setupPass.d.ts.map +1 -0
  145. package/dist/infer/setupPass.js +524 -0
  146. package/dist/infer/setupPass.js.map +1 -0
  147. package/dist/infer/statements.d.ts +26 -0
  148. package/dist/infer/statements.d.ts.map +1 -0
  149. package/dist/infer/statements.js +750 -0
  150. package/dist/infer/statements.js.map +1 -0
  151. package/dist/infer/stmt-bindings.d.ts +22 -0
  152. package/dist/infer/stmt-bindings.d.ts.map +1 -0
  153. package/dist/infer/stmt-bindings.js +1482 -0
  154. package/dist/infer/stmt-bindings.js.map +1 -0
  155. package/dist/infer/stmt-destructure.d.ts +29 -0
  156. package/dist/infer/stmt-destructure.d.ts.map +1 -0
  157. package/dist/infer/stmt-destructure.js +490 -0
  158. package/dist/infer/stmt-destructure.js.map +1 -0
  159. package/dist/infer/types.d.ts +220 -0
  160. package/dist/infer/types.d.ts.map +1 -0
  161. package/dist/infer/types.js +46 -0
  162. package/dist/infer/types.js.map +1 -0
  163. package/dist/infer/unifyDiag.d.ts +46 -0
  164. package/dist/infer/unifyDiag.d.ts.map +1 -0
  165. package/dist/infer/unifyDiag.js +642 -0
  166. package/dist/infer/unifyDiag.js.map +1 -0
  167. package/dist/parsing-babel.d.ts +3 -0
  168. package/dist/parsing-babel.d.ts.map +1 -0
  169. package/dist/parsing-babel.js +353 -0
  170. package/dist/parsing-babel.js.map +1 -0
  171. package/dist/parsing.d.ts +69 -0
  172. package/dist/parsing.d.ts.map +1 -0
  173. package/dist/parsing.js +288 -0
  174. package/dist/parsing.js.map +1 -0
  175. package/dist/registries/constraintRegistry.d.ts +233 -0
  176. package/dist/registries/constraintRegistry.d.ts.map +1 -0
  177. package/dist/registries/constraintRegistry.js +803 -0
  178. package/dist/registries/constraintRegistry.js.map +1 -0
  179. package/dist/registries/dataTypeRegistry.d.ts +63 -0
  180. package/dist/registries/dataTypeRegistry.d.ts.map +1 -0
  181. package/dist/registries/dataTypeRegistry.js +180 -0
  182. package/dist/registries/dataTypeRegistry.js.map +1 -0
  183. package/dist/registries/domGlobals.d.ts +33 -0
  184. package/dist/registries/domGlobals.d.ts.map +1 -0
  185. package/dist/registries/domGlobals.js +309 -0
  186. package/dist/registries/domGlobals.js.map +1 -0
  187. package/dist/registries/methodRegistry.d.ts +277 -0
  188. package/dist/registries/methodRegistry.d.ts.map +1 -0
  189. package/dist/registries/methodRegistry.js +2074 -0
  190. package/dist/registries/methodRegistry.js.map +1 -0
  191. package/dist/registries/session.d.ts +38 -0
  192. package/dist/registries/session.d.ts.map +1 -0
  193. package/dist/registries/session.js +75 -0
  194. package/dist/registries/session.js.map +1 -0
  195. package/dist/server.d.ts +2 -0
  196. package/dist/server.d.ts.map +1 -0
  197. package/dist/server.js +1896 -0
  198. package/dist/server.js.map +1 -0
  199. package/dist/services/codeActions.d.ts +22 -0
  200. package/dist/services/codeActions.d.ts.map +1 -0
  201. package/dist/services/codeActions.js +465 -0
  202. package/dist/services/codeActions.js.map +1 -0
  203. package/dist/services/completion.d.ts +259 -0
  204. package/dist/services/completion.d.ts.map +1 -0
  205. package/dist/services/completion.js +2794 -0
  206. package/dist/services/completion.js.map +1 -0
  207. package/dist/services/definitions.d.ts +37 -0
  208. package/dist/services/definitions.d.ts.map +1 -0
  209. package/dist/services/definitions.js +605 -0
  210. package/dist/services/definitions.js.map +1 -0
  211. package/dist/services/diagnosticCodes.d.ts +70 -0
  212. package/dist/services/diagnosticCodes.d.ts.map +1 -0
  213. package/dist/services/diagnosticCodes.js +239 -0
  214. package/dist/services/diagnosticCodes.js.map +1 -0
  215. package/dist/services/diagnostics.d.ts +86 -0
  216. package/dist/services/diagnostics.d.ts.map +1 -0
  217. package/dist/services/diagnostics.js +665 -0
  218. package/dist/services/diagnostics.js.map +1 -0
  219. package/dist/services/documentCache.d.ts +88 -0
  220. package/dist/services/documentCache.d.ts.map +1 -0
  221. package/dist/services/documentCache.js +108 -0
  222. package/dist/services/documentCache.js.map +1 -0
  223. package/dist/services/documentSymbols.d.ts +20 -0
  224. package/dist/services/documentSymbols.d.ts.map +1 -0
  225. package/dist/services/documentSymbols.js +381 -0
  226. package/dist/services/documentSymbols.js.map +1 -0
  227. package/dist/services/fileSelection.d.ts +24 -0
  228. package/dist/services/fileSelection.d.ts.map +1 -0
  229. package/dist/services/fileSelection.js +154 -0
  230. package/dist/services/fileSelection.js.map +1 -0
  231. package/dist/services/fileSelectionRefresh.d.ts +26 -0
  232. package/dist/services/fileSelectionRefresh.d.ts.map +1 -0
  233. package/dist/services/fileSelectionRefresh.js +77 -0
  234. package/dist/services/fileSelectionRefresh.js.map +1 -0
  235. package/dist/services/files.d.ts +342 -0
  236. package/dist/services/files.d.ts.map +1 -0
  237. package/dist/services/files.js +1712 -0
  238. package/dist/services/files.js.map +1 -0
  239. package/dist/services/fsProbe.d.ts +14 -0
  240. package/dist/services/fsProbe.d.ts.map +1 -0
  241. package/dist/services/fsProbe.js +112 -0
  242. package/dist/services/fsProbe.js.map +1 -0
  243. package/dist/services/globalsLoader.d.ts +20 -0
  244. package/dist/services/globalsLoader.d.ts.map +1 -0
  245. package/dist/services/globalsLoader.js +122 -0
  246. package/dist/services/globalsLoader.js.map +1 -0
  247. package/dist/services/hmFileServices.d.ts +113 -0
  248. package/dist/services/hmFileServices.d.ts.map +1 -0
  249. package/dist/services/hmFileServices.js +686 -0
  250. package/dist/services/hmFileServices.js.map +1 -0
  251. package/dist/services/hover.d.ts +280 -0
  252. package/dist/services/hover.d.ts.map +1 -0
  253. package/dist/services/hover.js +1687 -0
  254. package/dist/services/hover.js.map +1 -0
  255. package/dist/services/importContext.d.ts +396 -0
  256. package/dist/services/importContext.d.ts.map +1 -0
  257. package/dist/services/importContext.js +1999 -0
  258. package/dist/services/importContext.js.map +1 -0
  259. package/dist/services/projectChecker.d.ts +50 -0
  260. package/dist/services/projectChecker.d.ts.map +1 -0
  261. package/dist/services/projectChecker.js +228 -0
  262. package/dist/services/projectChecker.js.map +1 -0
  263. package/dist/services/references.d.ts +41 -0
  264. package/dist/services/references.d.ts.map +1 -0
  265. package/dist/services/references.js +757 -0
  266. package/dist/services/references.js.map +1 -0
  267. package/dist/services/rename.d.ts +22 -0
  268. package/dist/services/rename.d.ts.map +1 -0
  269. package/dist/services/rename.js +101 -0
  270. package/dist/services/rename.js.map +1 -0
  271. package/dist/services/shortCircuit.d.ts +27 -0
  272. package/dist/services/shortCircuit.d.ts.map +1 -0
  273. package/dist/services/shortCircuit.js +28 -0
  274. package/dist/services/shortCircuit.js.map +1 -0
  275. package/dist/services/sidecarPerf.d.ts +19 -0
  276. package/dist/services/sidecarPerf.d.ts.map +1 -0
  277. package/dist/services/sidecarPerf.js +59 -0
  278. package/dist/services/sidecarPerf.js.map +1 -0
  279. package/dist/services/signatureHelp.d.ts +27 -0
  280. package/dist/services/signatureHelp.d.ts.map +1 -0
  281. package/dist/services/signatureHelp.js +984 -0
  282. package/dist/services/signatureHelp.js.map +1 -0
  283. package/dist/walking.d.ts +25 -0
  284. package/dist/walking.d.ts.map +1 -0
  285. package/dist/walking.js +107 -0
  286. package/dist/walking.js.map +1 -0
  287. package/hm-types-builtin/assert.hm +20 -0
  288. package/hm-types-builtin/buffer.hm +8 -0
  289. package/hm-types-builtin/child_process.hm +16 -0
  290. package/hm-types-builtin/crypto.hm +17 -0
  291. package/hm-types-builtin/fs.hm +15 -0
  292. package/hm-types-builtin/http.hm +14 -0
  293. package/hm-types-builtin/os.hm +19 -0
  294. package/hm-types-builtin/path.hm +18 -0
  295. package/hm-types-builtin/react-dom.hm +27 -0
  296. package/hm-types-builtin/react.hm +113 -0
  297. package/hm-types-builtin/url.hm +7 -0
  298. package/hm-types-builtin/zlib.hm +12 -0
  299. package/package.json +53 -4
  300. package/schemas/hinmil.config.schema.json +261 -0
  301. package/schemas/package-hinmil.schema.json +59 -0
@@ -0,0 +1,2162 @@
1
+ "use strict";
2
+ // ============================================================================
3
+ // Row/record projection & expansion subsystem for call inference — extracted
4
+ // from calls.ts
5
+ //
6
+ // Plain language: some libraries build queries from column lists, e.g.
7
+ // `Person(['id', 'name'])` meaning "select these fields". This subsystem
8
+ // lets annotations describe that: a `Picked R sel` marker in a signature is
9
+ // replaced, at the call site, by a record built from the literal arguments
10
+ // ("project these fields out of row R"), and a `Merge a b` marker collapses
11
+ // two record shapes into one. It is the machinery behind precise types for
12
+ // query-builder style APIs.
13
+ // ============================================================================
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.tryExpandKeySetFromArrayArg = tryExpandKeySetFromArrayArg;
16
+ exports.tryExpandRowMap = tryExpandRowMap;
17
+ exports.findPickedInResultSides = findPickedInResultSides;
18
+ exports.applyPickedProjection = applyPickedProjection;
19
+ exports.harvestTaggedTemplateParams = harvestTaggedTemplateParams;
20
+ exports.applyMergeReduction = applyMergeReduction;
21
+ exports.maybeApplyRowOpening = maybeApplyRowOpening;
22
+ exports.findShadowKeyForChildRow = findShadowKeyForChildRow;
23
+ exports.applyAwaitedReduction = applyAwaitedReduction;
24
+ const types_1 = require("../hm/types");
25
+ const types_2 = require("../hm/types");
26
+ const env_1 = require("../hm/env");
27
+ const unify_1 = require("../hm/unify");
28
+ const typeUtils_1 = require("../hm/typeUtils");
29
+ const methodRegistry_1 = require("../registries/methodRegistry");
30
+ const constraintRegistry_1 = require("../registries/constraintRegistry");
31
+ /** The curried parameter-slot types of a resolved function type (the slots
32
+ * that line up with the supplied argument nodes). */
33
+ function curriedParamTypes(resolved) {
34
+ const argTypes = [];
35
+ if (resolved.tag === 'TFun' && resolved.param.tag === 'TCon' && resolved.param.name === types_2.T_TUPLE) {
36
+ for (const a of resolved.param.args)
37
+ argTypes.push(a);
38
+ }
39
+ else {
40
+ let cur = resolved;
41
+ while (cur.tag === 'TFun') {
42
+ argTypes.push(cur.param);
43
+ cur = cur.result;
44
+ }
45
+ }
46
+ return argTypes;
47
+ }
48
+ /** Pass 1 — classify every TVar / TLabel-var occurrence as living inside a
49
+ * label group (keyed by the group's label-var id) or outside every group. */
50
+ function classifyRowGroupVars(engine, resolved) {
51
+ const groupValueVars = new Map();
52
+ const outsideVars = new Set();
53
+ const noteInside = (kid, id) => {
54
+ let s = groupValueVars.get(kid);
55
+ if (!s) {
56
+ s = new Set();
57
+ groupValueVars.set(kid, s);
58
+ }
59
+ s.add(id);
60
+ };
61
+ // `resolved` is already substituted, so composite nodes need no re-apply
62
+ // (re-applying every subtree at every level was quadratic and showed up as
63
+ // ~5% of the FP-library lint). Leaves are still resolved — a cheap lookup.
64
+ const visit = (t, insideKid) => {
65
+ const r = t.tag === 'TVar' || t.tag === 'TLabel' ? engine.subst.apply(t) : t;
66
+ if (r.tag === 'TVar') {
67
+ if (insideKid === null)
68
+ outsideVars.add(r.id);
69
+ else
70
+ noteInside(insideKid, r.id);
71
+ return;
72
+ }
73
+ if (r.tag === 'TLabel') {
74
+ if (r.kind === 'var') {
75
+ if (insideKid === null)
76
+ outsideVars.add(r.id);
77
+ else
78
+ noteInside(insideKid, r.id);
79
+ }
80
+ return;
81
+ }
82
+ if (r.tag === 'TCon') {
83
+ for (const a of r.args)
84
+ visit(a, insideKid);
85
+ return;
86
+ }
87
+ if (r.tag === 'TFun') {
88
+ visit(r.param, insideKid);
89
+ visit(r.result, insideKid);
90
+ return;
91
+ }
92
+ if (r.tag === 'TRecord') {
93
+ for (const k in r.fields)
94
+ visit(r.fields[k], insideKid);
95
+ if (r.labelFields) {
96
+ for (const lf of r.labelFields) {
97
+ const lbl = engine.subst.apply(lf.label);
98
+ if (lbl.tag === 'TLabel' && lbl.kind === 'var')
99
+ visit(lf.type, lbl.id);
100
+ else
101
+ visit(lf.type, insideKid);
102
+ }
103
+ }
104
+ if (r.rest)
105
+ visit(r.rest, insideKid);
106
+ }
107
+ };
108
+ visit(resolved, null);
109
+ return { groupValueVars, outsideVars };
110
+ }
111
+ /** Pass 2 — build a fresh-var expansion plan for one group over `keys`.
112
+ *
113
+ * Internal vars (live only inside this group) get a fresh var per key. An
114
+ * "outside-union" var also appears outside any group (e.g. the return of
115
+ * `{ [k]::a } -> [a]`): each key gets its own fresh var so heterogeneous
116
+ * values are accepted, and the outside occurrence later becomes the union of
117
+ * those fresh vars (see {@link applyRowExpansionPlan}). */
118
+ function buildRowExpansionPlan(keys, kid, groupValueVars, outsideVars) {
119
+ const valueVars = groupValueVars.get(kid) ?? new Set();
120
+ const internalIds = new Set();
121
+ const outsideUnionIds = new Set();
122
+ for (const v of valueVars) {
123
+ let inOther = false;
124
+ for (const [otherKid, otherSet] of groupValueVars) {
125
+ if (otherKid !== kid && otherSet.has(v)) {
126
+ inOther = true;
127
+ break;
128
+ }
129
+ }
130
+ if (inOther)
131
+ continue; // shared across groups → leave for cross-group merge
132
+ if (outsideVars.has(v))
133
+ outsideUnionIds.add(v);
134
+ else
135
+ internalIds.add(v);
136
+ }
137
+ const allFreshIds = new Set([...internalIds, ...outsideUnionIds]);
138
+ const freshMaps = keys.map(() => {
139
+ const m = new Map();
140
+ for (const id of allFreshIds)
141
+ m.set(id, (0, types_2.tVar)());
142
+ return m;
143
+ });
144
+ return { keys, freshMaps, outsideUnionIds: [...outsideUnionIds] };
145
+ }
146
+ /** Pass 3 — rewrite the type, expanding every planned label group into
147
+ * concrete per-key fields (preserving any row tail), then collapse each
148
+ * group's outside-union vars into a union of their per-key fresh vars. */
149
+ function applyRowExpansionPlan(engine, resolved, planByKid) {
150
+ const applyFresh = (t, fresh) => (0, typeUtils_1.mapType)(t, n => {
151
+ if (n.tag === 'TVar' && fresh.has(n.id))
152
+ return fresh.get(n.id);
153
+ return undefined;
154
+ });
155
+ const rewrite = (t) => (0, typeUtils_1.mapType)(t, n => {
156
+ if (n.tag !== 'TRecord' || !n.labelFields || n.labelFields.length === 0)
157
+ return undefined;
158
+ const newFields = { ...n.fields };
159
+ const remainingLabel = [];
160
+ // Keys materialised by an EARLIER label group in this same record: when a
161
+ // later group expands to one of these keys, the contributions are
162
+ // DEEP-merged (deferred to `applyMergeReduction` via a `Merge` marker)
163
+ // rather than first-wins dropped.
164
+ const fromGroup = new Set();
165
+ let changed = false;
166
+ for (const lf of n.labelFields) {
167
+ const lbl = engine.subst.apply(lf.label);
168
+ if (lbl.tag === 'TLabel' && lbl.kind === 'var' && planByKid.has(lbl.id)) {
169
+ const plan = planByKid.get(lbl.id);
170
+ const innerRewritten = rewrite(lf.type);
171
+ for (let i = 0; i < plan.keys.length; i++) {
172
+ const k = plan.keys[i];
173
+ const expanded = applyFresh(innerRewritten, plan.freshMaps[i]);
174
+ if (fromGroup.has(k)) {
175
+ const prior = newFields[k];
176
+ newFields[k] = prior.tag === 'TCon' && prior.name === types_2.T_MERGE
177
+ ? (0, types_2.tCon)(types_2.T_MERGE, [...prior.args, expanded])
178
+ : (0, types_2.tCon)(types_2.T_MERGE, [prior, expanded]);
179
+ }
180
+ else if (k in newFields) {
181
+ continue; // overlap with a pre-existing static field → static wins
182
+ }
183
+ else {
184
+ newFields[k] = expanded;
185
+ fromGroup.add(k);
186
+ }
187
+ }
188
+ changed = true;
189
+ }
190
+ else {
191
+ remainingLabel.push({ label: lf.label, type: rewrite(lf.type) });
192
+ }
193
+ }
194
+ // Recurse into static fields too.
195
+ for (const k of Object.keys(newFields)) {
196
+ if (n.fields[k] === newFields[k])
197
+ newFields[k] = rewrite(newFields[k]);
198
+ }
199
+ if (!changed)
200
+ return undefined;
201
+ const out = { tag: 'TRecord', fields: newFields };
202
+ if (remainingLabel.length > 0)
203
+ out.labelFields = remainingLabel;
204
+ if (n.rest) {
205
+ out.rest = n.rest;
206
+ // An open label-group row must deep-merge the fields the row var later
207
+ // absorbs with the keys expanded here.
208
+ out.mergeRow = true;
209
+ }
210
+ if (n.alias)
211
+ out.alias = n.alias;
212
+ return out;
213
+ });
214
+ let rewritten = rewrite(resolved);
215
+ // Replace each group's outside-union var (the value var that also appears
216
+ // outside any label group, e.g. the result `[a]` of `{ [k]::a } -> [a]`)
217
+ // with the union of the per-key fresh vars it expanded to.
218
+ for (const [, plan] of planByKid) {
219
+ for (const uid of plan.outsideUnionIds) {
220
+ const members = plan.freshMaps.map(m => m.get(uid)).filter(Boolean);
221
+ if (members.length === 0)
222
+ continue;
223
+ const unionT = members.length === 1 ? members[0] : (0, types_2.tUnion)(members);
224
+ rewritten = (0, typeUtils_1.mapType)(rewritten, n => (n.tag === 'TVar' && n.id === uid) ? unionT : undefined);
225
+ }
226
+ }
227
+ return rewritten;
228
+ }
229
+ /**
230
+ * Static key-set removal for `omit`-style signatures applied to an inline
231
+ * array literal of string keys.
232
+ * A curried signature such as
233
+ * omit :: Array String k => k -> { [k] :: a, ...r } -> {r}
234
+ * (baked to `[String] -> { [k] :: a, ...r } -> {r}`) receives its two
235
+ * arguments at SEPARATE curried call sites — the key array at `omit([...])`
236
+ * and the record at the following `(obj)` — so ordinary row unification only
237
+ * ever sees one of them and can remove at most the single label `[k]`. That
238
+ * is why `omit(["name", "age"])({ name, age, country })` previously kept `age`
239
+ * (only the first key was dropped).
240
+ *
241
+ * When the argument supplied to a parameter typed `Array String` is an inline
242
+ * array literal of string literals, the key set is known statically. We then
243
+ * expand the label group `{ [k] :: a, ...r }` found in a LATER curried
244
+ * parameter into one concrete field per key (each with a fresh value var),
245
+ * keeping the row tail `...r`. Unifying the record argument afterwards binds
246
+ * every listed key and leaves the remainder in `...r`, so the result `{r}` is
247
+ * the record minus ALL listed keys.
248
+ *
249
+ * Only fires for inline array literals of string literals — a key array coming
250
+ * from a variable carries no type-level key information and is left to ordinary
251
+ * single-label row unification. Guarded to the `omit` shape: the label group's
252
+ * row tail must also flow to the function result (`… -> {r}`), and the group
253
+ * must hold exactly one label variable.
254
+ */
255
+ function tryExpandKeySetFromArrayArg(engine, calleeType, argNodes) {
256
+ const resolved = engine.subst.apply(calleeType);
257
+ if (resolved.tag !== 'TFun')
258
+ return calleeType;
259
+ const { groupValueVars, outsideVars } = classifyRowGroupVars(engine, resolved);
260
+ if (groupValueVars.size === 0)
261
+ return calleeType;
262
+ const argTypes = curriedParamTypes(resolved);
263
+ // 1. Find an inline array literal of string literals whose parameter slot is
264
+ // `Array String` — the statically-known key set.
265
+ let keys = null;
266
+ for (let i = 0; i < argNodes.length && i < argTypes.length; i++) {
267
+ const an = argNodes[i];
268
+ if (!an || an.type !== 'ArrayExpression')
269
+ continue;
270
+ const pt = engine.subst.apply(argTypes[i]);
271
+ const isStringArray = pt.tag === 'TCon' && pt.name === types_2.T_ARRAY && pt.args.length === 1 &&
272
+ pt.args[0].tag === 'TCon' && pt.args[0].name === 'String';
273
+ if (!isStringArray)
274
+ continue;
275
+ const ks = [];
276
+ let ok = true;
277
+ for (const el of an.elements) {
278
+ if (el && el.type === 'Literal' && typeof el.value === 'string') {
279
+ ks.push(el.value);
280
+ }
281
+ else {
282
+ ok = false;
283
+ break;
284
+ }
285
+ }
286
+ if (!ok || ks.length === 0)
287
+ continue;
288
+ keys = ks;
289
+ break;
290
+ }
291
+ if (!keys)
292
+ return calleeType;
293
+ // 2. Restrict to the `omit` shape: a label group `{ [k] :: a, ...r }` whose
294
+ // row tail also flows to the function result (`… -> {r}`) and that holds
295
+ // exactly one label variable. `restCount[id] >= 2` means the same row
296
+ // variable appears as a tail in two records (the parameter and `{r}`).
297
+ const restCount = new Map();
298
+ (0, typeUtils_1.eachType)(resolved, n => {
299
+ if (n.tag === 'TRecord' && n.rest && n.rest.tag === 'TRow') {
300
+ restCount.set(n.rest.id, (restCount.get(n.rest.id) ?? 0) + 1);
301
+ }
302
+ });
303
+ const groupIsOmitShape = (kid) => (0, typeUtils_1.someType)(resolved, n => {
304
+ if (n.tag !== 'TRecord' || !n.labelFields || !n.rest || n.rest.tag !== 'TRow')
305
+ return false;
306
+ if ((restCount.get(n.rest.id) ?? 0) < 2)
307
+ return false;
308
+ const varLabels = n.labelFields.filter(lf => {
309
+ const l = engine.subst.apply(lf.label);
310
+ return l.tag === 'TLabel' && l.kind === 'var';
311
+ });
312
+ if (varLabels.length !== 1)
313
+ return false;
314
+ const l = engine.subst.apply(varLabels[0].label);
315
+ return l.tag === 'TLabel' && l.kind === 'var' && l.id === kid;
316
+ });
317
+ // 3. Plan + rewrite via the shared row-expansion machinery, sourcing the
318
+ // keys from the array literal instead of an object literal.
319
+ const planByKid = new Map();
320
+ for (const [kid] of groupValueVars) {
321
+ if (!groupIsOmitShape(kid))
322
+ continue;
323
+ planByKid.set(kid, buildRowExpansionPlan(keys, kid, groupValueVars, outsideVars));
324
+ }
325
+ if (planByKid.size === 0)
326
+ return calleeType;
327
+ return applyRowExpansionPlan(engine, resolved, planByKid);
328
+ }
329
+ /**
330
+ * Row-map fan-out for label-polymorphic record parameters.
331
+ *
332
+ * When a function annotation has a single label-field `{ [k] :: T }` whose
333
+ * label variable `k` cannot be inferred from any other parameter (i.e. `k`
334
+ * is *closed over* by the label-field group only), expand it into concrete
335
+ * fields based on the keys of the corresponding argument's object literal.
336
+ *
337
+ * Example:
338
+ * unwrap :: { [k] :: Pair a b } -> { [k] :: b }
339
+ * unwrap({ a: Pair(1, "x"), b: Pair(2, 3) })
340
+ *
341
+ * The label group `{k}` has internal type vars `{a, b}` (used only inside
342
+ * label-field types). The argument literal has keys `[a, b]`. We rewrite
343
+ * the function type to:
344
+ * { a :: Pair a1 b1, b :: Pair a2 b2 } -> { a :: b1, b :: b2 }
345
+ * by freshening the internal vars per key. Subsequent unification then
346
+ * produces `{ a :: String, b :: Number }` for the result.
347
+ *
348
+ * Shares the variable classification, per-group planning and type rewrite with
349
+ * {@link tryExpandKeySetFromArrayArg}; the only difference is that the keys
350
+ * come from an object-literal argument here.
351
+ *
352
+ * Skipped when:
353
+ * • the label-var also appears outside any label-field (e.g. `pluck`'s
354
+ * `(k, [{ [k] :: v, ...r }]) -> [v]` where `k` is the first arg);
355
+ * • the matched parameter record has a row tail `{ [k] :: a, ...r }` (classic
356
+ * single-property row-polymorphism — expanding over every key would consume
357
+ * the whole object and leave `...r` empty);
358
+ * • the corresponding argument is not an object literal with static keys.
359
+ */
360
+ function tryExpandRowMap(engine, calleeType, argNodes) {
361
+ const resolved = engine.subst.apply(calleeType);
362
+ if (resolved.tag !== 'TFun')
363
+ return calleeType;
364
+ const { groupValueVars, outsideVars } = classifyRowGroupVars(engine, resolved);
365
+ if (groupValueVars.size === 0)
366
+ return calleeType;
367
+ const argTypes = curriedParamTypes(resolved);
368
+ const containsKid = (t, kid) => (0, typeUtils_1.someType)(t, n => {
369
+ if (n.tag !== 'TRecord' || !n.labelFields)
370
+ return false;
371
+ for (const lf of n.labelFields) {
372
+ const lbl = engine.subst.apply(lf.label);
373
+ if (lbl.tag === 'TLabel' && lbl.kind === 'var' && lbl.id === kid)
374
+ return true;
375
+ }
376
+ return false;
377
+ });
378
+ // True when the label group `kid` lives in a record that ALSO carries an
379
+ // explicit row tail (`{ [k] :: a, ...r }`) — classic single-property
380
+ // row-polymorphism. Only the matched PARAMETER record matters; a row tail in
381
+ // the RESULT (e.g. `({ [k]::a }, {...b}) -> { [k]::a, ...b }`) must NOT
382
+ // disable expansion.
383
+ const groupRecordHasRest = (t, kid) => (0, typeUtils_1.someType)(t, n => {
384
+ if (n.tag !== 'TRecord' || !n.rest || !n.labelFields)
385
+ return false;
386
+ for (const lf of n.labelFields) {
387
+ const lbl = engine.subst.apply(lf.label);
388
+ if (lbl.tag === 'TLabel' && lbl.kind === 'var' && lbl.id === kid)
389
+ return true;
390
+ }
391
+ return false;
392
+ });
393
+ const planByKid = new Map();
394
+ for (const [kid] of groupValueVars) {
395
+ if (outsideVars.has(kid))
396
+ continue; // label var bound elsewhere → skip
397
+ // Find argument index containing this group.
398
+ let argIndex = -1;
399
+ for (let i = 0; i < argTypes.length; i++) {
400
+ if (containsKid(argTypes[i], kid)) {
401
+ argIndex = i;
402
+ break;
403
+ }
404
+ }
405
+ if (argIndex < 0 || argIndex >= argNodes.length)
406
+ continue;
407
+ if (groupRecordHasRest(argTypes[argIndex], kid))
408
+ continue;
409
+ const argNode = argNodes[argIndex];
410
+ if (!argNode || argNode.type !== 'ObjectExpression')
411
+ continue;
412
+ const props = argNode.properties;
413
+ const keys = [];
414
+ let ok = true;
415
+ for (const prop of props) {
416
+ if (prop.type !== 'Property' || prop.computed) {
417
+ ok = false;
418
+ break;
419
+ }
420
+ const key = prop.key;
421
+ if (key.type === 'Identifier')
422
+ keys.push(key.name);
423
+ else if (key.type === 'Literal' && typeof key.value === 'string') {
424
+ keys.push(key.value);
425
+ }
426
+ else {
427
+ ok = false;
428
+ break;
429
+ }
430
+ }
431
+ if (!ok || keys.length === 0)
432
+ continue;
433
+ planByKid.set(kid, buildRowExpansionPlan(keys, kid, groupValueVars, outsideVars));
434
+ }
435
+ if (planByKid.size === 0)
436
+ return calleeType;
437
+ return applyRowExpansionPlan(engine, resolved, planByKid);
438
+ }
439
+ /** Walk a (possibly union-of-overloads) type, recursing only into TFun
440
+ * RESULT sides plus union members, and return the first `Picked R _`
441
+ * row name found. Skipping TFun param sides is essential: after
442
+ * unification with a parent's selector union, those params absorb
443
+ * unrelated rows that would otherwise mislead the relation check. */
444
+ function findPickedInResultSides(engine, t, depth = 0) {
445
+ if (depth > 20)
446
+ return null;
447
+ const a = engine.subst.apply(t);
448
+ if (a.tag === 'TFun') {
449
+ return findPickedInResultSides(engine, a.result, depth + 1);
450
+ }
451
+ if (a.tag === 'TCon') {
452
+ if (a.name === types_2.T_PICKED && a.args.length >= 1) {
453
+ const r = engine.subst.apply(a.args[0]);
454
+ if (r.tag === 'TCon')
455
+ return r.name;
456
+ if (r.tag === 'TRecord' && r.alias)
457
+ return r.alias;
458
+ }
459
+ if (a.name === types_2.T_UNION) {
460
+ for (const arg of a.args) {
461
+ const r = findPickedInResultSides(engine, arg, depth + 1);
462
+ if (r)
463
+ return r;
464
+ }
465
+ return null;
466
+ }
467
+ // Other TCons (e.g. Table FooRow, QueryTag (Picked …)): walk into
468
+ // their args — they're "result-shaped" wrappers.
469
+ for (const arg of a.args) {
470
+ const r = findPickedInResultSides(engine, arg, depth + 1);
471
+ if (r)
472
+ return r;
473
+ }
474
+ return null;
475
+ }
476
+ if (a.tag === 'TRecord' && a.pickedFrom)
477
+ return a.pickedFrom;
478
+ return null;
479
+ }
480
+ /**
481
+ * Walk the call's result type for `Picked R a` markers and replace each one
482
+ * with a record built from the call's literal-array argument.
483
+ *
484
+ * Element handling, in order:
485
+ * 1. String literal — looked up as a column in `R`; field gets the row's
486
+ * type for that column. Unknown column literals are silently dropped.
487
+ * 2. Identifier whose resolved type is `Prop T ...` — the identifier
488
+ * name becomes the field key, with value type `T`. When the name
489
+ * matches an `R` field, the row's type wins.
490
+ * 3. Expression of type `QueryTag X` / `Table X` (any unary TCon wrapping
491
+ * a row-shaped TRecord with an `alias`) — the parent row's
492
+ * method-shadow registry is searched for a method whose return type
493
+ * matches `[X]` (list-valued FK) or `X` (single-valued FK). The
494
+ * shadow's name becomes the field key; its return type the value.
495
+ * No fallback to a name-mangling convention: missing shadows mean
496
+ * the relation isn't modelled and the element is skipped.
497
+ * 4. Anything else (paging helpers, raw SQL fragments, …) is omitted.
498
+ *
499
+ * The projected record is intentionally *structural* (no `alias`) so that
500
+ * hovers display the picked columns rather than the row alias name.
501
+ *
502
+ * Returns `result` unchanged when no `Picked` markers are present or when
503
+ * the call has no literal-array argument.
504
+ */
505
+ function applyPickedProjection(engine, node, env, result) {
506
+ // Quick scan: any Picked node anywhere in the result tree?
507
+ let hasMarker = false;
508
+ const scan = (t) => {
509
+ if (hasMarker)
510
+ return;
511
+ if (t.tag === 'TCon') {
512
+ if (t.name === types_2.T_PICKED && t.args.length >= 1) {
513
+ hasMarker = true;
514
+ return;
515
+ }
516
+ for (const a of t.args)
517
+ scan(a);
518
+ }
519
+ else if (t.tag === 'TFun') {
520
+ scan(t.param);
521
+ scan(t.result);
522
+ }
523
+ else if (t.tag === 'TRecord') {
524
+ for (const k in t.fields)
525
+ scan(t.fields[k]);
526
+ if (t.rest)
527
+ scan(t.rest);
528
+ }
529
+ };
530
+ scan(result);
531
+ if (!hasMarker)
532
+ return result;
533
+ // Locate the literal array argument. Picked is a call-site primitive —
534
+ // when the caller binds the selector array to a variable we don't try to
535
+ // back-trace; the marker simply remains in the result type.
536
+ const arrayArg = node.arguments.find(a => a.type === 'ArrayExpression');
537
+ if (!arrayArg)
538
+ return result;
539
+ // Collect the row identifiers being projected at THIS call site so the
540
+ // substitution sweep below only touches Picked markers belonging to
541
+ // this call. Without this scoping a nested call's projection would
542
+ // greedily rewrite the parent call's `Picked OtherRow …` marker,
543
+ // applying the inner array against the wrong row.
544
+ //
545
+ // Skip union members: a `Picked R …` occurrence inside a `T_UNION`
546
+ // represents a slot expectation absorbed from a `*Selector` alias
547
+ // during unification with the parent call's selector union, NOT a
548
+ // value-result of THIS call. Treating those as projection targets
549
+ // would re-project this call's array against unrelated sibling rows
550
+ // (e.g. an `Employee([Department])` call's array being projected
551
+ // against `UserRow` because `EmployeeSelector` got unified through a
552
+ // `UserSelector` slot).
553
+ const projectedRows = new Set();
554
+ // Also remember the SOURCE row types (the `R` of each `Picked R …`)
555
+ // so we can recover full column information for params-record
556
+ // enrichment after `rewrite` has replaced the row with a (typically
557
+ // narrower) projected record.
558
+ const sourceRows = [];
559
+ const collectRows = (t) => {
560
+ if (t.tag === 'TCon') {
561
+ if (t.name === types_2.T_UNION)
562
+ return;
563
+ if (t.name === types_2.T_PICKED && t.args.length >= 1) {
564
+ const r = engine.subst.apply(t.args[0]);
565
+ if (r.tag === 'TCon')
566
+ projectedRows.add(r.name);
567
+ else if (r.tag === 'TRecord' && r.alias)
568
+ projectedRows.add(r.alias);
569
+ sourceRows.push(r);
570
+ }
571
+ for (const a of t.args)
572
+ collectRows(a);
573
+ }
574
+ else if (t.tag === 'TFun') {
575
+ collectRows(t.param);
576
+ collectRows(t.result);
577
+ }
578
+ else if (t.tag === 'TRecord') {
579
+ for (const k in t.fields)
580
+ collectRows(t.fields[k]);
581
+ if (t.rest)
582
+ collectRows(t.rest);
583
+ }
584
+ };
585
+ collectRows(result);
586
+ const rewrite = (t) => {
587
+ if (t.tag === 'TCon') {
588
+ if (t.name === types_2.T_UNION)
589
+ return t; // see scoping rationale on collectRows
590
+ if (t.name === types_2.T_PICKED && t.args.length >= 1) {
591
+ const r = engine.subst.apply(t.args[0]);
592
+ const rowName = r.tag === 'TCon' ? r.name
593
+ : r.tag === 'TRecord' ? r.alias
594
+ : undefined;
595
+ if (rowName && !projectedRows.has(rowName))
596
+ return t;
597
+ const projected = projectArrayAgainstRow(engine, arrayArg, t.args[0]);
598
+ return projected ?? t;
599
+ }
600
+ const newArgs = t.args.map(rewrite);
601
+ if (newArgs.every((a, i) => a === t.args[i]))
602
+ return t;
603
+ return { ...t, args: newArgs };
604
+ }
605
+ if (t.tag === 'TFun') {
606
+ const p = rewrite(t.param);
607
+ const r = rewrite(t.result);
608
+ if (p === t.param && r === t.result)
609
+ return t;
610
+ return { ...t, param: p, result: r };
611
+ }
612
+ if (t.tag === 'TRecord') {
613
+ const fields = {};
614
+ let changed = false;
615
+ for (const k in t.fields) {
616
+ const nv = rewrite(t.fields[k]);
617
+ if (nv !== t.fields[k])
618
+ changed = true;
619
+ fields[k] = nv;
620
+ }
621
+ if (!changed)
622
+ return t;
623
+ return { ...t, fields };
624
+ }
625
+ return t;
626
+ };
627
+ const rewritten = rewrite(result);
628
+ // Propagate the projection into the substitution. Earlier in this
629
+ // call's inference, the result tvar may have been unified against an
630
+ // outer parameter slot (e.g. `QueryTag b` of `one :: QueryTag b -> ...`),
631
+ // binding `b` to the *unprojected* `Picked R Sel` form. When the
632
+ // outer call later re-unifies its argument with that slot, it sees
633
+ // `QueryTag (Picked ...)` on one side and the now-projected record on
634
+ // the other, and emits a spurious "Cannot unify" diagnostic. Walk
635
+ // the substitution and rewrite every binding that still references
636
+ // `Picked R …` for the rows we just projected, so subsequent
637
+ // unifications observe the projected record instead.
638
+ //
639
+ // CAVEAT: Skip rewrites inside union types. Picked-occurrences inside
640
+ // a `T_UNION` represent slot-expectations from a `…Selector` alias
641
+ // (e.g. `QueryTag c (Picked LocationRow a)` as a branch of
642
+ // `OrganisationSelector`), NOT a value-result. Rewriting these
643
+ // poisons the parent call's expected slot and produces cascading
644
+ // "Cannot unify" diagnostics where one side has the Picked-branch and
645
+ // the other has the projected record.
646
+ if (rewritten !== result) {
647
+ const rewriteSubstBound = (t) => {
648
+ if (t.tag === 'TCon') {
649
+ if (t.name === types_2.T_UNION)
650
+ return t; // do not project into selector unions
651
+ if (t.name === types_2.T_PICKED && t.args.length >= 1) {
652
+ const r = engine.subst.apply(t.args[0]);
653
+ const rowName = r.tag === 'TCon' ? r.name
654
+ : r.tag === 'TRecord' ? r.alias
655
+ : undefined;
656
+ if (rowName && !projectedRows.has(rowName))
657
+ return t;
658
+ const projected = projectArrayAgainstRow(engine, arrayArg, t.args[0]);
659
+ return projected ?? t;
660
+ }
661
+ const newArgs = t.args.map(rewriteSubstBound);
662
+ if (newArgs.every((a, i) => a === t.args[i]))
663
+ return t;
664
+ return { ...t, args: newArgs };
665
+ }
666
+ if (t.tag === 'TFun') {
667
+ const p = rewriteSubstBound(t.param);
668
+ const r = rewriteSubstBound(t.result);
669
+ if (p === t.param && r === t.result)
670
+ return t;
671
+ return { ...t, param: p, result: r };
672
+ }
673
+ if (t.tag === 'TRecord') {
674
+ const fields = {};
675
+ let changed = false;
676
+ for (const k in t.fields) {
677
+ const nv = rewriteSubstBound(t.fields[k]);
678
+ if (nv !== t.fields[k])
679
+ changed = true;
680
+ fields[k] = nv;
681
+ }
682
+ if (!changed)
683
+ return t;
684
+ return { ...t, fields };
685
+ }
686
+ return t;
687
+ };
688
+ for (const [id, bound] of engine.subst.entries()) {
689
+ const updated = rewriteSubstBound(bound);
690
+ if (updated !== bound)
691
+ engine.subst.set(id, updated);
692
+ }
693
+ }
694
+ // Derive the parameter record `p` from helper calls in the selector
695
+ // array (e.g. `Limit(p => p.limit)`, `Offset(p => p.offset)`, nested
696
+ // sub-queries' own helpers) and bind it to the host TCon's parameter
697
+ // slot. This turns `QueryTag p {projected}` with `p` unbound into
698
+ // `QueryTag {limit::Number, offset::Number} {projected}`, so the second
699
+ // overload of `QueryTag()` displays the user's actual params record
700
+ // instead of a bare TVar.
701
+ const paramRec = gatherParamRecord(engine, env, arrayArg);
702
+ if (paramRec) {
703
+ // When a harvested param field has the same NAME as a column of the
704
+ // row being projected (e.g. outer `id.eq(p => p.id)` against
705
+ // `OrganisationRow { id :: Number, ... }`), unify the field's
706
+ // (typically unbound) TVar with the row column's known type so the
707
+ // params slot reflects the concrete column type instead of leaking a
708
+ // free `a`. This is purely an enrichment step — fields without a
709
+ // matching row column keep their inferred type unchanged.
710
+ enrichParamRecFromRow(engine, rewritten, paramRec);
711
+ for (const sr of sourceRows)
712
+ enrichParamRecFromRecord(engine, sr, paramRec);
713
+ bindParamSlot(engine, rewritten, paramRec);
714
+ }
715
+ return rewritten;
716
+ }
717
+ /** Walk a selector-array literal and gather a parameter record from any
718
+ * helper invocation whose argument is a function `({...record...}) -> _`.
719
+ * Recurses into nested sub-queries (calls whose own argument is an
720
+ * array literal), so a `Variable(p => p.x)` inside an inner table call
721
+ * contributes to the outer host's param record. Returns the merged
722
+ * TRecord (structural intersection — duplicate keys unify field types)
723
+ * or null when no helper contributed any field. */
724
+ function gatherParamRecord(engine, env, arrayNode) {
725
+ const fields = {};
726
+ let foundAny = false;
727
+ // Scalar contributions from helpers whose params are NOT a record
728
+ // (e.g. `Limit :: Runnable Number r => r -> Limit r` called as
729
+ // `Limit(p => p)` or `Limit(42)`). When the selector list contains
730
+ // only such helpers, the harvested "param record" is actually a
731
+ // bare scalar of the helper's Runnable-payload type. See Part 2 of
732
+ // the scalar-params plan.
733
+ const scalars = [];
734
+ let mixedShapeDiag = false;
735
+ // Track already-visited AST nodes so callee-chain recursion (e.g.
736
+ // `.iLike(...).or(.iLike(...))`) doesn't re-process the same call.
737
+ const visited = new WeakSet();
738
+ const consumeRecordType = (rec) => {
739
+ const expanded = engine.maybeExpandAlias(engine.subst.apply(rec));
740
+ if (expanded.tag !== 'TRecord')
741
+ return;
742
+ for (const k in expanded.fields) {
743
+ const incoming = engine.subst.apply(expanded.fields[k]);
744
+ if (k in fields) {
745
+ try {
746
+ engine.subst.mergeFrom((0, unify_1.unify)(fields[k], incoming));
747
+ }
748
+ catch { /* skip conflict */ }
749
+ }
750
+ else {
751
+ fields[k] = incoming;
752
+ foundAny = true;
753
+ }
754
+ }
755
+ };
756
+ const visit = (elem) => {
757
+ if (visited.has(elem))
758
+ return;
759
+ visited.add(elem);
760
+ // Identifier elements (e.g. `limit`, `offset` referenced as values
761
+ // already constructed by helpers like `Limit(p => p.limit)`).
762
+ // Their inferred type may be a wrapper TCon (`Limit r`) carrying
763
+ // the captured callback in an arg slot — walk those for any
764
+ // `({...record...}) -> _` shape.
765
+ if (elem.type === 'Identifier') {
766
+ const idName = elem.name;
767
+ // Prefer the env-resolved binding type — the per-node stored type
768
+ // can be overwritten by the call-arg unification. Use the scheme
769
+ // type directly (without `instantiate`'s TVar-freshening) so any
770
+ // `paramHint` carried on the bound TCon survives the lookup; then
771
+ // walk both the type's own carrier args AND the paramHint shape.
772
+ const envScheme = env.lookup(idName);
773
+ const idType = envScheme
774
+ ? envScheme.type
775
+ : engine.subst.apply(engine.getNodeType(elem) ?? (0, types_2.tVar)());
776
+ walkCarrierForRecords(engine, idType, consumeRecordType);
777
+ if (idType.tag === 'TCon' && idType.paramHint) {
778
+ const hint = engine.maybeExpandAlias(engine.subst.apply(idType.paramHint));
779
+ if (hint.tag === 'TRecord')
780
+ consumeRecordType(hint);
781
+ }
782
+ return;
783
+ }
784
+ if (elem.type !== 'CallExpression')
785
+ return;
786
+ const call = elem;
787
+ // Inspect the helper's callee type — its declared signature tells us
788
+ // (independently of how the user passed the argument) which record
789
+ // the parameter slot consumes. Two shapes are recognised:
790
+ // 1. `Helper :: ({...record...} -> X) -> Helper` — callback form
791
+ // (most common in query-builder: `Limit(p => p.limit)`).
792
+ // 2. `Helper :: {...record...} -> Helper` — direct form
793
+ // (when the caller is expected to pass the record literal).
794
+ // Union-typed helpers are walked branch-by-branch so the same name
795
+ // can be both callback- and direct-form.
796
+ const calleeNode = call.callee;
797
+ // Prefer the helper's *declared* signature (from local annotations
798
+ // or imported constructors) over its per-call instantiated type:
799
+ // call-site instantiation freshens the type's TVars, so even if the
800
+ // signature constrains the param slot to a concrete record, the
801
+ // node-stored type may still show bare TVars there. The declared
802
+ // scheme always carries the canonical record.
803
+ const calleeName = calleeNode.type === 'Identifier'
804
+ ? calleeNode.name : null;
805
+ let declaredScheme = calleeName
806
+ ? (engine.annotationMap.get(calleeName)?.scheme
807
+ ?? engine.importedConstructors.get(calleeName)
808
+ ?? null)
809
+ : null;
810
+ // Method-call form: when the callee is `obj.method(...)`, the
811
+ // method's declared scheme (with its `Runnable T r =>` prefix)
812
+ // lives in the MethodRegistry under the receiver TCon's name —
813
+ // not in `annotationMap`. Resolve the receiver type, find its
814
+ // TCon name, and look up the method scheme so the Runnable-payload
815
+ // propagation below also fires for chained method calls like
816
+ // `firstname.iLike(p => p.q)`.
817
+ if (!declaredScheme && calleeNode.type === 'MemberExpression') {
818
+ const memCallee = calleeNode;
819
+ const propNode = memCallee.property;
820
+ if (propNode?.type === 'Identifier' && !memCallee.computed) {
821
+ let recvType = engine.subst.apply(engine.getNodeType(memCallee.object) ?? (0, types_2.tVar)());
822
+ if (recvType.tag === 'TVar'
823
+ && memCallee.object.type === 'Identifier') {
824
+ const objName = memCallee.object.name;
825
+ const objScheme = env.lookup(objName);
826
+ if (objScheme)
827
+ recvType = engine.subst.apply((0, env_1.instantiate)(objScheme));
828
+ }
829
+ const recvCon = engine.maybeExpandAlias(recvType);
830
+ if (recvCon.tag === 'TCon') {
831
+ const entry = (0, methodRegistry_1.lookupMethod)(recvCon.name, propNode.name);
832
+ if (entry?.scheme)
833
+ declaredScheme = entry.scheme;
834
+ }
835
+ }
836
+ }
837
+ const declared = declaredScheme?.type ?? null;
838
+ const calleeType = declared
839
+ ?? engine.subst.apply(engine.getNodeType(calleeNode) ?? (0, types_2.tVar)());
840
+ extractParamFromCallee(engine, calleeType, consumeRecordType);
841
+ // Fix 3: when the declared scheme is `Runnable T r => r -> Result`
842
+ // (the query-builder pattern for callback-or-direct slots like `Limit`),
843
+ // the callback's expected return type is the constraint's payload
844
+ // `T`. Carry that payload (when concrete) so the body-walk below
845
+ // can type freshly-harvested `p.field` MemberExpressions as `T`
846
+ // instead of leaving them as opaque TVars.
847
+ let runnablePayload = null;
848
+ if (declaredScheme && declared && declared.tag === 'TFun'
849
+ && declared.param.tag === 'TVar' && declaredScheme.constraints) {
850
+ const paramName = declared.param.name;
851
+ for (const c of declaredScheme.constraints) {
852
+ if (!paramName || c.typeVarName !== paramName)
853
+ continue;
854
+ // Standard Runnable shape: `Runnable T r` — payload is the
855
+ // first positional arg. Skip if no positional args (e.g.
856
+ // nominal-only `Functor f`).
857
+ const args = c.positionalArgs;
858
+ if (!args || args.length < 1)
859
+ continue;
860
+ const payload = engine.maybeExpandAlias(engine.subst.apply(args[0]));
861
+ // Only use concrete payloads — a still-polymorphic `a` adds no
862
+ // information over the existing fresh-TVar default.
863
+ if (payload.tag === 'TCon' || payload.tag === 'TRecord') {
864
+ runnablePayload = payload;
865
+ break;
866
+ }
867
+ }
868
+ }
869
+ // Scalar-param contribution: when the helper consumes a non-record
870
+ // Runnable payload (e.g. `Limit :: Runnable Number r => r -> _`),
871
+ // detect the ONE user shape where the entire param IS the scalar:
872
+ // Bare-body callback: `Limit(p => p)` — the callback returns
873
+ // its own param identifier verbatim, so the tag's param-record
874
+ // slot must accept the Runnable payload at tag-call time.
875
+ //
876
+ // The direct-value form `Limit(42)` is intentionally NOT a
877
+ // contribution: the value is provided in-line at helper-call time,
878
+ // so the surrounding tag does NOT need a parameter for it later.
879
+ if (runnablePayload && declared && declared.tag === 'TFun') {
880
+ for (const arg of call.arguments) {
881
+ const argNode = arg;
882
+ if (argNode.type !== 'ArrowFunctionExpression'
883
+ && argNode.type !== 'FunctionExpression')
884
+ continue;
885
+ const fn = argNode;
886
+ const firstParam = fn.params?.[0];
887
+ if (!firstParam || firstParam.type !== 'Identifier')
888
+ continue;
889
+ const paramName = firstParam.name;
890
+ if (fn.body?.type === 'Identifier'
891
+ && fn.body.name === paramName) {
892
+ scalars.push(runnablePayload);
893
+ }
894
+ }
895
+ }
896
+ // Also walk the call's RESULT type for callback-carrier args (e.g.
897
+ // an inline `Limit(p => p.limit)` whose result is `Limit r` where
898
+ // `r` was unified with the callback's type at call-site).
899
+ const callType = engine.subst.apply(engine.getNodeType(call) ?? (0, types_2.tVar)());
900
+ walkCarrierForRecords(engine, callType, consumeRecordType);
901
+ // Inline-callback arguments: when the user passes `(p => p.x)`
902
+ // directly, the inferred parameter type of that arrow function
903
+ // captures the params shape implied by its body. This covers
904
+ // method-call helpers like `applicationId.eq(p => p.applicationId)`
905
+ // where the helper's callee union (`(p -> v) | v`) doesn't expose
906
+ // a record at the param slot — the record only exists on the
907
+ // user's callback.
908
+ //
909
+ // Inspect both the function-node's stored type AND its first
910
+ // parameter's stored type: depending on how unification with the
911
+ // helper's `Runnable` union proceeded, the engine may have stored
912
+ // a TFun on the function (param type recoverable from `.param`),
913
+ // a bare TRecord on the function (the param record was substituted
914
+ // for the function-node TVar), or just a TVar on the function with
915
+ // the actual record bound to the parameter Identifier's TVar.
916
+ const consumeRecordOrTFunParam = (t) => {
917
+ const a = engine.maybeExpandAlias(engine.subst.apply(t));
918
+ if (a.tag === 'TRecord')
919
+ consumeRecordType(a);
920
+ else if (a.tag === 'TFun') {
921
+ const fp = engine.maybeExpandAlias(engine.subst.apply(a.param));
922
+ if (fp.tag === 'TRecord')
923
+ consumeRecordType(fp);
924
+ }
925
+ };
926
+ for (const arg of call.arguments) {
927
+ const argNode = arg;
928
+ if (argNode.type !== 'ArrowFunctionExpression' && argNode.type !== 'FunctionExpression')
929
+ continue;
930
+ const fn = argNode;
931
+ const firstParam = fn.params?.[0];
932
+ if (firstParam) {
933
+ const pType = engine.getNodeType(firstParam);
934
+ if (pType)
935
+ consumeRecordOrTFunParam(pType);
936
+ }
937
+ const fnType = engine.getNodeType(fn);
938
+ if (fnType)
939
+ consumeRecordOrTFunParam(fnType);
940
+ // Body-syntactic fallback: when the helper's `Runnable` constraint
941
+ // unified the function value with `(a -> v) | v` without binding
942
+ // the param's TVar to a concrete record, walk the function's body
943
+ // for `paramName.fieldName` MemberExpressions and harvest a field
944
+ // for each. Field types come from each MemberExpression's
945
+ // inferred node type — when still unbound, default to a fresh
946
+ // TVar so the field name is at least surfaced in the params record.
947
+ if (firstParam && firstParam.type === 'Identifier') {
948
+ const paramName = firstParam.name;
949
+ // Runnable-payload sharpening is only valid when the field
950
+ // access IS the callback's return value (e.g. `p => p.q`).
951
+ // For bodies like `` `%${p.q}%` `` the template literal coerces
952
+ // `p.q` to String regardless of its actual type, so we cannot
953
+ // conclude `p.q :: payload` — fall back to a fresh TVar in
954
+ // that case. When the body is an Identifier-bodied arrow the
955
+ // payload is also unsafe (the body is not `p.field`).
956
+ const bodyIsDirectMemberOfParam = fn.body?.type === 'MemberExpression'
957
+ && fn.body.object?.type === 'Identifier'
958
+ && fn.body.object.name === paramName
959
+ && fn.body.property?.type === 'Identifier'
960
+ && !fn.body.computed;
961
+ const visitBody = (n) => {
962
+ if (!n || typeof n !== 'object' || !('type' in n))
963
+ return;
964
+ if (n.type === 'MemberExpression'
965
+ && n.object?.type === 'Identifier'
966
+ && n.object.name === paramName
967
+ && n.property?.type === 'Identifier'
968
+ && !n.computed) {
969
+ const fieldName = n.property.name;
970
+ // Prefer the PROPERTY node's recorded type: member access on an
971
+ // unresolved callback param records its result var on the
972
+ // property Identifier only (`recordSuppressedProperty`), while
973
+ // `getNodeType(member)` falls back to the *object* identifier's
974
+ // type (the member start offset is claimed by `p` itself).
975
+ // Harvesting that object var would bind the host's param slot to
976
+ // a record whose fields reference the slot itself (occurs cycle
977
+ // — `p := { limit :: p }`). The property var, by contrast, was
978
+ // threaded through the helper's callback signature by regular
979
+ // unification (e.g. bound to `Number` via
980
+ // `Limit :: ((p -> Number) | Number) -> Limit p`).
981
+ const propNode = n.property;
982
+ const memType = engine.getNodeType(propNode) ?? engine.getNodeType(n);
983
+ let applied = memType ? engine.subst.apply(memType) : null;
984
+ // Cycle guard: if the harvested type still resolves to the same
985
+ // TVar as the callback's own param, treat it as opaque.
986
+ if (applied && applied.tag === 'TVar' && firstParam) {
987
+ const pT = engine.getNodeType(firstParam);
988
+ const appliedP = pT ? engine.subst.apply(pT) : null;
989
+ if (appliedP && appliedP.tag === 'TVar' && appliedP.id === applied.id) {
990
+ applied = null;
991
+ }
992
+ }
993
+ // Only sharpen with the constraint payload when this very
994
+ // MemberExpression IS the function body — then the
995
+ // `Runnable T r` constraint pins the field to `T`. In
996
+ // any other context (template literals, binary ops,
997
+ // nested calls, multiple field uses) the field type is
998
+ // unconstrained — surface it as a fresh TVar.
999
+ const isOpaque = !applied || applied.tag === 'TVar';
1000
+ const isReturnedDirectly = bodyIsDirectMemberOfParam && n === fn.body;
1001
+ const inferredField = (isOpaque && runnablePayload && isReturnedDirectly)
1002
+ ? runnablePayload
1003
+ : (applied ?? (0, types_2.tVar)());
1004
+ const existing = fields[fieldName];
1005
+ if (!existing) {
1006
+ fields[fieldName] = inferredField;
1007
+ foundAny = true;
1008
+ }
1009
+ else {
1010
+ // Chain-order quirk: outer callee callbacks are visited
1011
+ // first, so an earlier opaque harvest (e.g. from a
1012
+ // template-literal body) can shadow a later concrete
1013
+ // harvest (e.g. `p => p.q` proving `String`). When the
1014
+ // stored field is still a bare TVar but a later harvest
1015
+ // produces a concrete type, upgrade in place.
1016
+ const existingApplied = engine.subst.apply(existing);
1017
+ const newApplied = engine.subst.apply(inferredField);
1018
+ if (existingApplied.tag === 'TVar' && newApplied.tag !== 'TVar') {
1019
+ fields[fieldName] = newApplied;
1020
+ }
1021
+ else {
1022
+ try {
1023
+ engine.subst.mergeFrom((0, unify_1.unify)(existingApplied, newApplied));
1024
+ }
1025
+ catch { /* skip conflict */ }
1026
+ }
1027
+ }
1028
+ }
1029
+ // Recurse into all child AST nodes generically.
1030
+ for (const k of Object.keys(n)) {
1031
+ if (k === 'type' || k === 'start' || k === 'end' || k === 'loc' || k === 'range')
1032
+ continue;
1033
+ const child = n[k];
1034
+ if (Array.isArray(child)) {
1035
+ for (const c of child)
1036
+ visitBody(c);
1037
+ }
1038
+ else if (child && typeof child === 'object') {
1039
+ visitBody(child);
1040
+ }
1041
+ }
1042
+ };
1043
+ visitBody(fn.body);
1044
+ }
1045
+ }
1046
+ // Recurse into nested array-literal arguments (sub-queries) and
1047
+ // into nested CallExpression arguments (e.g. when a helper is
1048
+ // passed another helper-call directly, no array wrapper).
1049
+ for (const arg of call.arguments) {
1050
+ const argNode = arg;
1051
+ if (argNode.type === 'ArrayExpression') {
1052
+ for (const e of argNode.elements) {
1053
+ if (e)
1054
+ visit(e);
1055
+ }
1056
+ }
1057
+ else if (argNode.type === 'CallExpression') {
1058
+ visit(argNode);
1059
+ }
1060
+ }
1061
+ // Recurse into the callee's own subtree for chained method calls
1062
+ // like `x.iLike(p => p.q).or(y.iLike(p => p.q))`: the outer `.or`
1063
+ // call has no callback args carrying `p.q`, but its callee chain
1064
+ // does. Walk `callee.object` to reach those inner callbacks.
1065
+ if (calleeNode.type === 'MemberExpression') {
1066
+ const obj = calleeNode.object;
1067
+ if (obj && (obj.type === 'CallExpression' || obj.type === 'Identifier'
1068
+ || obj.type === 'MemberExpression')) {
1069
+ visit(obj);
1070
+ }
1071
+ }
1072
+ };
1073
+ for (const elem of arrayNode.elements) {
1074
+ if (elem)
1075
+ visit(elem);
1076
+ }
1077
+ // Shape-decision:
1078
+ // - record fields only → TRecord (legacy behaviour)
1079
+ // - scalar contributions only → unify all scalars, return that
1080
+ // single Type (Number, String, …)
1081
+ // - both kinds present → ambiguous: emit a diagnostic and
1082
+ // prefer the record (annotation-
1083
+ // escape stays available)
1084
+ // - none → null
1085
+ if (scalars.length > 0 && !foundAny) {
1086
+ let acc = engine.subst.apply(scalars[0]);
1087
+ for (let i = 1; i < scalars.length; i++) {
1088
+ const next = engine.subst.apply(scalars[i]);
1089
+ try {
1090
+ engine.subst.mergeFrom((0, unify_1.unify)(acc, next));
1091
+ }
1092
+ catch { /* incompatible scalars — first one wins, diagnostic below if you extend */ }
1093
+ acc = engine.subst.apply(acc);
1094
+ }
1095
+ return acc;
1096
+ }
1097
+ if (scalars.length > 0 && foundAny && !mixedShapeDiag) {
1098
+ mixedShapeDiag = true;
1099
+ engine.addDiag(`Selector list mixes scalar and record parameters; annotate the tag explicitly`, arrayNode);
1100
+ }
1101
+ return foundAny ? (0, types_2.tRecord)(fields) : null;
1102
+ }
1103
+ /** Harvest params from a tagged-template's function interpolations
1104
+ * (`sql\`... ${p => p.riziv} ...\``) and bind them into the result's
1105
+ * parameter slot (`SQLTag p o` → `p`). The synthesized CallExpression
1106
+ * produced by `inferTaggedTemplateExpression` is wrapped in a fake
1107
+ * one-element array so `gatherParamRecord`'s call-visitor (declared-
1108
+ * signature extraction, callback body walk, nested-call recursion)
1109
+ * applies unchanged. No-op when the result carries no param slot or
1110
+ * the template has no function interpolations. */
1111
+ function harvestTaggedTemplateParams(engine, env, callNode, result) {
1112
+ const applied = engine.subst.apply(result);
1113
+ if (applied.tag !== 'TCon' || applied.args.length < 2)
1114
+ return;
1115
+ const hasFnInterp = callNode.arguments.some((a) => {
1116
+ const t = a.type;
1117
+ return t === 'ArrowFunctionExpression' || t === 'FunctionExpression';
1118
+ });
1119
+ if (!hasFnInterp)
1120
+ return;
1121
+ const fakeArray = {
1122
+ type: 'ArrayExpression',
1123
+ elements: [callNode],
1124
+ start: callNode.start,
1125
+ end: callNode.end,
1126
+ };
1127
+ const paramRec = gatherParamRecord(engine, env, fakeArray);
1128
+ if (!paramRec)
1129
+ return;
1130
+ bindParamSlot(engine, applied, paramRec);
1131
+ }
1132
+ /** From a helper callee's signature, pump any TRecord seen at depth 1
1133
+ * (direct form: `Helper :: {...} -> Helper`) or depth 2 inside a
1134
+ * callback (`Helper :: ({...} -> _) -> Helper`) into `consume`. Walks
1135
+ * Union branches transparently so a helper with multiple overload
1136
+ * shapes contributes from every branch that matches one of the two
1137
+ * recognised forms. */
1138
+ function extractParamFromCallee(engine, calleeType, consume) {
1139
+ const t = engine.subst.apply(calleeType);
1140
+ if (t.tag === 'TCon' && t.name === types_2.T_UNION) {
1141
+ for (const branch of t.args)
1142
+ extractParamFromCallee(engine, branch, consume);
1143
+ return;
1144
+ }
1145
+ if (t.tag !== 'TFun')
1146
+ return;
1147
+ const param = engine.maybeExpandAlias(engine.subst.apply(t.param));
1148
+ if (param.tag === 'TRecord') {
1149
+ consume(param);
1150
+ return;
1151
+ }
1152
+ if (param.tag === 'TFun') {
1153
+ const inner = engine.maybeExpandAlias(engine.subst.apply(param.param));
1154
+ if (inner.tag === 'TRecord')
1155
+ consume(inner);
1156
+ }
1157
+ }
1158
+ /** Walk a value's TCon args (recursively) and consume any TRecord found
1159
+ * at a `TFun.param` position. Used by `gatherParamRecord` to recover
1160
+ * the original callback record from helper values like `Limit r` or
1161
+ * `Offset r` whose `r` type slot was unified with the user's callback
1162
+ * `({...} -> Number)` at construction time. */
1163
+ function walkCarrierForRecords(engine, t, consume) {
1164
+ const rt = engine.subst.apply(t);
1165
+ if (rt.tag !== 'TCon')
1166
+ return;
1167
+ for (const arg of rt.args) {
1168
+ const a = engine.maybeExpandAlias(engine.subst.apply(arg));
1169
+ if (a.tag === 'TFun') {
1170
+ // Callback-form helper carrier: `Limit r` where `r` was unified
1171
+ // with `({...record...} -> Number)` at construction time. The
1172
+ // record at the callback's *param* position is the params shape.
1173
+ const p = engine.maybeExpandAlias(engine.subst.apply(a.param));
1174
+ if (p.tag === 'TRecord')
1175
+ consume(p);
1176
+ }
1177
+ else if (a.tag === 'TCon') {
1178
+ // Recurse through wrapper TCons (e.g. `Limit r` whose r is itself
1179
+ // a TCon wrapping a callback). Do NOT treat bare TRecord args as
1180
+ // params: nested sub-query carriers like `QueryTag p {projectedRow}`
1181
+ // expose their projected row as a TRecord arg, but that row is the
1182
+ // sub-query's RESULT, not a parameter contribution to the outer
1183
+ // host. Bare-TRecord consumption here would leak the projected
1184
+ // row into the outer host's params record.
1185
+ walkCarrierForRecords(engine, a, consume);
1186
+ }
1187
+ }
1188
+ }
1189
+ // ---------------------------------------------------------------------------
1190
+ // Merge reduction — structural union of two records
1191
+ // ---------------------------------------------------------------------------
1192
+ /**
1193
+ * Walk `result` and replace every `Merge a b` whose args resolve to two
1194
+ * TRecords with a single structural-union record (alias-stripped).
1195
+ * Conflicting field types are unified through the engine's substitution
1196
+ * — incompatibilities are surfaced via existing diagnostics elsewhere.
1197
+ *
1198
+ * `Merge` markers whose arguments aren't both records yet (e.g. an
1199
+ * unbound TVar from an earlier-stage call) are left in place so a later
1200
+ * pass can collapse them once the substitution catches up. Nested
1201
+ * `Merge` is handled by recursing first via `mapType`.
1202
+ */
1203
+ function applyMergeReduction(engine, result, node) {
1204
+ return (0, typeUtils_1.mapType)(result, n => {
1205
+ if (n.tag !== 'TCon' || n.name !== types_2.T_MERGE || n.args.length < 2)
1206
+ return undefined;
1207
+ // Recurse first so nested Merges collapse bottom-up.
1208
+ const reducedArgs = n.args.map(a => applyMergeReduction(engine, a, node));
1209
+ const expanded = reducedArgs.map(a => engine.maybeExpandAlias(engine.subst.apply(a)));
1210
+ // An `Any` operand (`Object.assign ({}, env, { querier })` with
1211
+ // `env :: Any`) has an unknown shape, so the merge has too: `Any`, not
1212
+ // a "non-record operand" error.
1213
+ if (expanded.some(types_1.isAnyType))
1214
+ return types_1.tAnyType;
1215
+ // Dictionary merge: `Object k a` operands (an FP library's `Object String Any`)
1216
+ // plus closed record literals — `Object.assign ({}, dictA, dictB)`,
1217
+ // `Object.assign (withoutNulls (row), { id }, { at })` — merge to
1218
+ // `Object k (a ∪ fields)`. A record's keys are strings, so a non-empty
1219
+ // record needs `k ≡ String`; its field types join the value (an `Any`
1220
+ // value absorbs them). Without this the dictionaries counted as
1221
+ // non-record operands and the marker never reduced.
1222
+ {
1223
+ const dicts = expanded.filter(types_1.isAppliedObject);
1224
+ const closedRecord = (e) => e.tag === 'TRecord' && !(e.labelFields && e.labelFields.length) && !e.rest;
1225
+ // A record of computed keys (`{ [k] :: v }`, see inferObjectExpression)
1226
+ // is dictionary content too, and an operand of a type not known yet
1227
+ // (the accumulator of a `reduce`) takes the dictionary's type.
1228
+ const labelRecord = (e) => e.tag === 'TRecord' && !!(e.labelFields && e.labelFields.length) && !e.rest;
1229
+ const restAreRecords = expanded.every(e => (0, types_1.isAppliedObject)(e) || closedRecord(e) || labelRecord(e) || e.tag === 'TVar' || e.tag === 'TRow');
1230
+ if (dicts.length > 0 && restAreRecords) {
1231
+ let key = dicts[0].args[0];
1232
+ let value = dicts[0].args[1];
1233
+ let ok = true;
1234
+ for (let i = 1; i < dicts.length && ok; i++) {
1235
+ try {
1236
+ engine.subst.mergeFrom((0, unify_1.unify)(engine.subst.apply(key), engine.subst.apply(dicts[i].args[0])));
1237
+ }
1238
+ catch {
1239
+ ok = false;
1240
+ break;
1241
+ }
1242
+ value = (0, types_2.deepMergeTypes)(engine.subst.apply(value), engine.subst.apply(dicts[i].args[1]));
1243
+ }
1244
+ for (const e of expanded) {
1245
+ if (!ok || !(closedRecord(e) || labelRecord(e)))
1246
+ continue;
1247
+ const entries = Object.values(e.fields).concat((e.labelFields ?? []).map(lf => lf.type));
1248
+ if (entries.length === 0)
1249
+ continue;
1250
+ if (Object.keys(e.fields).length > 0) {
1251
+ try {
1252
+ engine.subst.mergeFrom((0, unify_1.unify)(engine.subst.apply(key), types_1.tString));
1253
+ }
1254
+ catch {
1255
+ ok = false;
1256
+ break;
1257
+ }
1258
+ }
1259
+ for (const entry of entries) {
1260
+ const v = engine.subst.apply(value);
1261
+ value = (0, types_1.isAnyType)(v) ? v : (0, types_2.deepMergeTypes)(v, engine.subst.apply(entry));
1262
+ }
1263
+ }
1264
+ if (ok) {
1265
+ key = engine.subst.apply(key);
1266
+ return (0, types_2.tCon)(types_1.T_OBJECT, [key, value]);
1267
+ }
1268
+ }
1269
+ }
1270
+ const tvars = [];
1271
+ const records = [];
1272
+ const others = [];
1273
+ for (const e of expanded) {
1274
+ // A bare row-variable (`TRow`) is an *open row* — i.e. record-like, not
1275
+ // a concrete non-record operand. Treat it like an unresolved `TVar`:
1276
+ // defer the merge (keep the marker) until the row binds to a record at
1277
+ // a later position (e.g. once the call argument supplying `...b` is
1278
+ // unified). Classifying it as `others` previously produced a spurious
1279
+ // "contains a non-record operand" error for `Merge { …a } b`.
1280
+ if (e.tag === 'TVar' || e.tag === 'TRow')
1281
+ tvars.push(e);
1282
+ else if (e.tag === 'TRecord')
1283
+ records.push(e);
1284
+ else
1285
+ others.push(e);
1286
+ }
1287
+ // A default projection ("all columns" because nothing was selected) is
1288
+ // the identity next to records that DID select fields: drop it. Its
1289
+ // relation fields (nested queries) are kept.
1290
+ if (records.some(r => r.defaultProjection) && records.some(r => !r.defaultProjection)) {
1291
+ for (let i = records.length - 1; i >= 0; i--) {
1292
+ const r = records[i];
1293
+ if (!r.defaultProjection)
1294
+ continue;
1295
+ const relations = {};
1296
+ const rowName = r.pickedFrom;
1297
+ const columns = rowName ? engine.maybeExpandAlias((0, types_2.tCon)(rowName, [])) : null;
1298
+ for (const k in r.fields) {
1299
+ if (!(columns && columns.tag === 'TRecord' && k in columns.fields))
1300
+ relations[k] = r.fields[k];
1301
+ }
1302
+ if (Object.keys(relations).length === 0)
1303
+ records.splice(i, 1);
1304
+ else
1305
+ records[i] = { tag: 'TRecord', fields: relations };
1306
+ }
1307
+ if (records.length === 1 && tvars.length === 0 && others.length === 0)
1308
+ return records[0];
1309
+ }
1310
+ // Hard structural conflict: a concrete record alongside a concrete
1311
+ // non-record (e.g. `Merge {a::Number} Number` after Phase D
1312
+ // row-opening met a scalar at a polymorphic position).
1313
+ if (records.length > 0 && others.length > 0) {
1314
+ if (node) {
1315
+ engine.addDiag(`Cannot merge: '${(0, types_2.prettyTypeToString)(n)}' contains a non-record operand`, node);
1316
+ }
1317
+ return { ...n, args: reducedArgs };
1318
+ }
1319
+ // All TVars (no concrete operands yet) — keep the marker so a later
1320
+ // projection pass can finish the job once the substitution catches up.
1321
+ if (records.length === 0 && others.length === 0) {
1322
+ return { ...n, args: reducedArgs };
1323
+ }
1324
+ // Scalar / container merge: TVars + one-or-more concrete non-record
1325
+ // operands. These arise from deferred field-level `Merge` markers
1326
+ // emitted by `tryExpandRowMap` for label-group rows whose keys overlap
1327
+ // (`{ [k] :: a, [i] :: b }` where both cover `likedTypes`). Combine the
1328
+ // concretes with the shared deep-merge primitive so `Merge [String]
1329
+ // [Number]` becomes `[String | Number]` and `Merge [{..}] [{..}]` deep-
1330
+ // merges element-wise, then bind any TVar siblings to the result.
1331
+ if (records.length === 0) {
1332
+ let target = others[0];
1333
+ for (let i = 1; i < others.length; i++) {
1334
+ target = (0, types_2.deepMergeTypes)(engine.subst.apply(target), others[i]);
1335
+ }
1336
+ for (const tv of tvars) {
1337
+ // Only bind genuine type-vars to the scalar/container result. A
1338
+ // deferred row-variable must not be unified with a scalar target.
1339
+ if (tv.tag !== 'TVar')
1340
+ continue;
1341
+ try {
1342
+ engine.subst.mergeFrom((0, unify_1.unify)(tv, target));
1343
+ }
1344
+ catch { /* leave unbound */ }
1345
+ }
1346
+ return engine.subst.apply(target);
1347
+ }
1348
+ // Record-bearing merge with TVar siblings: keep the marker. The
1349
+ // TVars may yet be unified with concrete records downstream, and
1350
+ // prematurely binding them to the partial record-merge result would
1351
+ // close their shape too early (breaking structural row-opening of
1352
+ // sibling records via separate row-variables).
1353
+ if (records.length > 0 && tvars.length > 0) {
1354
+ return { ...n, args: reducedArgs };
1355
+ }
1356
+ // Record-only merge: structurally union the records.
1357
+ // Index signatures (`labelFields`, e.g. `Object String Any` →
1358
+ // `{ [String] :: Any }`) are carried over too; the same label from two
1359
+ // operands is combined once. Dropping them turned
1360
+ // `Object.assign ({}, dictA, dictB)` into `{}`.
1361
+ const labelAcc = [];
1362
+ const sameLabel = (x, y) => x.kind === 'lit' ? (y.kind === 'lit' && x.value === y.value) : (y.kind === 'var' && x.id === y.id);
1363
+ for (const e of records) {
1364
+ for (const lf of e.labelFields ?? []) {
1365
+ const label = engine.subst.apply(lf.label);
1366
+ const prior = labelAcc.find((l) => sameLabel(l.label, label));
1367
+ if (prior)
1368
+ prior.type = (0, types_2.deepMergeTypes)(engine.subst.apply(prior.type), engine.subst.apply(lf.type));
1369
+ else
1370
+ labelAcc.push({ label, type: engine.subst.apply(lf.type) });
1371
+ }
1372
+ }
1373
+ let acc = null;
1374
+ for (const e of records) {
1375
+ if (acc === null) {
1376
+ acc = { tag: 'TRecord', fields: { ...e.fields }, rest: e.rest, alias: undefined };
1377
+ continue;
1378
+ }
1379
+ const merged = { ...acc.fields };
1380
+ for (const k in e.fields) {
1381
+ const incoming = engine.subst.apply(e.fields[k]);
1382
+ if (k in merged) {
1383
+ // Overlapping field: combine the two types rather than unifying
1384
+ // them. Two records deep-merge; same-constructor containers merge
1385
+ // arg-wise (`[String]` ⊕ `[Number]` → `[String | Number]`); anything
1386
+ // else unions (deduped), so `{a::Number}` ⊕ `{a::String}` becomes
1387
+ // `{ a :: Number | String }` instead of a "conflicting types" diag.
1388
+ const prior = engine.subst.apply(merged[k]);
1389
+ merged[k] = (0, types_2.deepMergeTypes)(prior, incoming);
1390
+ }
1391
+ else {
1392
+ merged[k] = incoming;
1393
+ }
1394
+ }
1395
+ // Preserve the row-var tail when both operands share the same
1396
+ // rest TVar (common after Phase D row-opening of the same source
1397
+ // variable). When tails disagree we drop them.
1398
+ let rest = undefined;
1399
+ if (acc.rest && e.rest) {
1400
+ if (acc.rest.tag === 'TVar' && e.rest.tag === 'TVar' && acc.rest.id === e.rest.id) {
1401
+ rest = acc.rest;
1402
+ }
1403
+ }
1404
+ else {
1405
+ rest = acc.rest ?? e.rest;
1406
+ }
1407
+ acc = { tag: 'TRecord', fields: merged, rest };
1408
+ }
1409
+ if (acc && labelAcc.length > 0)
1410
+ acc = { ...acc, labelFields: labelAcc };
1411
+ return acc ?? n;
1412
+ });
1413
+ }
1414
+ /**
1415
+ * Plan v6.3 Phase D — structural row-opening at the call site.
1416
+ *
1417
+ * Looks at the (resolved) curried callee type and detects polymorphic
1418
+ * type-vars that occur at **two or more top-level positions** of the
1419
+ * TFun chain. When at least one of the arguments supplied at THIS
1420
+ * call site lands on such a position AND its AST is a record literal
1421
+ * (`ObjectExpression`), the callee is rewritten so:
1422
+ * - every top-level input occurrence of that TVar becomes a fresh
1423
+ * independent TVar `αᵢ`;
1424
+ * - the top-level result occurrence (if any) becomes `Merge α₁ … αₙ`
1425
+ * (collapsed to `α₁` when n == 1).
1426
+ *
1427
+ * Any pending constraint on the original TVar is replicated to every
1428
+ * fresh `αᵢ`. Phase C maps TRecord → 'Object' so user-declared
1429
+ * Object#method annotations satisfy these constraints uniformly,
1430
+ * without any class-name hardcoding in the core.
1431
+ *
1432
+ * The transform is intentionally restricted to top-level positions —
1433
+ * nested positions (`[a]`, `Maybe a`, …) keep classical rigid HM.
1434
+ */
1435
+ function maybeApplyRowOpening(engine, calleeType, args) {
1436
+ const resolved = engine.subst.apply(calleeType);
1437
+ if (resolved.tag !== 'TFun')
1438
+ return calleeType;
1439
+ // Flatten the curried TFun chain into [inputPositions..., finalResult].
1440
+ const inputPositions = [];
1441
+ let cur = resolved;
1442
+ while (cur.tag === 'TFun') {
1443
+ inputPositions.push(cur.param);
1444
+ cur = cur.result;
1445
+ }
1446
+ const finalResult = cur;
1447
+ // Count top-level TVar id occurrences across inputs + final result.
1448
+ const idCount = new Map();
1449
+ const bump = (t) => {
1450
+ if (t.tag === 'TVar')
1451
+ idCount.set(t.id, (idCount.get(t.id) ?? 0) + 1);
1452
+ };
1453
+ for (const p of inputPositions)
1454
+ bump(p);
1455
+ bump(finalResult);
1456
+ const polyIds = new Set();
1457
+ for (const [id, n] of idCount)
1458
+ if (n >= 2)
1459
+ polyIds.add(id);
1460
+ if (polyIds.size === 0)
1461
+ return calleeType;
1462
+ // Trigger: at least one provided arg sits on a top-level polyId input
1463
+ // position AND its AST is a structural literal we know how to row-open
1464
+ // (ObjectExpression → record-merge, ArrayExpression → array-element union).
1465
+ let trigger = false;
1466
+ for (let i = 0; i < args.length && i < inputPositions.length; i++) {
1467
+ const slot = inputPositions[i];
1468
+ if (slot.tag !== 'TVar' || !polyIds.has(slot.id))
1469
+ continue;
1470
+ const a = args[i];
1471
+ if (a && (a.type === 'ObjectExpression' || a.type === 'ArrayExpression')) {
1472
+ trigger = true;
1473
+ break;
1474
+ }
1475
+ }
1476
+ if (!trigger)
1477
+ return calleeType;
1478
+ const polyKinds = new Map();
1479
+ for (let i = 0; i < args.length && i < inputPositions.length; i++) {
1480
+ const slot = inputPositions[i];
1481
+ if (slot.tag !== 'TVar' || !polyIds.has(slot.id))
1482
+ continue;
1483
+ const a = args[i];
1484
+ if (!a)
1485
+ continue;
1486
+ if (a.type !== 'ObjectExpression' && a.type !== 'ArrayExpression')
1487
+ continue;
1488
+ if (!polyKinds.has(slot.id))
1489
+ polyKinds.set(slot.id, new Set());
1490
+ polyKinds.get(slot.id).add(a.type);
1491
+ }
1492
+ const polyMode = new Map();
1493
+ for (const id of polyIds) {
1494
+ const kinds = polyKinds.get(id);
1495
+ if (!kinds || kinds.size !== 1) {
1496
+ polyMode.set(id, null);
1497
+ continue;
1498
+ }
1499
+ if (kinds.has('ObjectExpression'))
1500
+ polyMode.set(id, 'merge');
1501
+ else if (kinds.has('ArrayExpression'))
1502
+ polyMode.set(id, 'arrayUnion');
1503
+ else
1504
+ polyMode.set(id, null);
1505
+ }
1506
+ // Plan v6.3 opt-in gate: row-opening only fires when the user has
1507
+ // explicitly declared a polymorphic combinator signature on some
1508
+ // `<Container>#<method>` required by one of the constraints attached
1509
+ // to the polymorphic TVars. Without that annotation, structural args
1510
+ // keep classical rigid HM. Per-container representative type ('Object'
1511
+ // for record literals, 'Array' for array literals) is derived from AST.
1512
+ const constraintNames = new Set();
1513
+ for (const pc of engine.pendingConstraints) {
1514
+ if (polyIds.has(pc.varId))
1515
+ constraintNames.add(pc.constraintName);
1516
+ }
1517
+ if (constraintNames.size === 0)
1518
+ return calleeType;
1519
+ const containsMerge = (t) => (0, typeUtils_1.someType)(t, (n) => n.tag === 'TCon' && n.name === types_2.T_MERGE);
1520
+ // Detect `[Union ...]` (an Array whose element type contains a Union):
1521
+ // the signature shape that signals array-element widening at the call site.
1522
+ const containsArrayUnion = (t) => (0, typeUtils_1.someType)(t, (n) => n.tag === 'TCon' && n.name === types_2.T_ARRAY && n.args.length === 1 &&
1523
+ (0, typeUtils_1.someType)(n.args[0], (inner) => inner.tag === 'TCon' && inner.name === types_2.T_UNION));
1524
+ const requiredMethodNames = (cdef) => {
1525
+ const names = [];
1526
+ for (const m of cdef.methods ?? [])
1527
+ names.push(m.name);
1528
+ for (const clause of cdef.selfClauses ?? []) {
1529
+ const body = clause.body;
1530
+ if (body.tag === 'TRecord') {
1531
+ for (const fname of Object.keys(body.fields)) {
1532
+ if (fname !== 'constructor')
1533
+ names.push(fname);
1534
+ }
1535
+ }
1536
+ }
1537
+ return names;
1538
+ };
1539
+ let optedInObject = false;
1540
+ let optedInArray = false;
1541
+ for (const cname of constraintNames) {
1542
+ const cdef = (0, constraintRegistry_1.lookupConstraint)(cname);
1543
+ if (!cdef)
1544
+ continue;
1545
+ for (const mname of requiredMethodNames(cdef)) {
1546
+ if (!optedInObject) {
1547
+ const oe = (0, methodRegistry_1.lookupMethod)('Object', mname);
1548
+ if (oe) {
1549
+ try {
1550
+ if (containsMerge(oe.factory([])))
1551
+ optedInObject = true;
1552
+ }
1553
+ catch { /* keep scanning */ }
1554
+ }
1555
+ }
1556
+ if (!optedInArray) {
1557
+ const ae = (0, methodRegistry_1.lookupMethod)('Array', mname);
1558
+ if (ae) {
1559
+ try {
1560
+ if (containsArrayUnion(ae.factory([])))
1561
+ optedInArray = true;
1562
+ }
1563
+ catch { /* keep scanning */ }
1564
+ }
1565
+ }
1566
+ if (optedInObject && optedInArray)
1567
+ break;
1568
+ }
1569
+ if (optedInObject && optedInArray)
1570
+ break;
1571
+ }
1572
+ // Strip modes that aren't opted-in via a registered instance method.
1573
+ for (const [id, m] of polyMode) {
1574
+ if (m === 'merge' && !optedInObject)
1575
+ polyMode.set(id, null);
1576
+ if (m === 'arrayUnion' && !optedInArray)
1577
+ polyMode.set(id, null);
1578
+ }
1579
+ let anyMode = false;
1580
+ for (const m of polyMode.values())
1581
+ if (m) {
1582
+ anyMode = true;
1583
+ break;
1584
+ }
1585
+ if (!anyMode)
1586
+ return calleeType;
1587
+ // Allocate fresh TVars per (polyId, input position). For arrayUnion
1588
+ // mode each αᵢ is immediately bound to `[γᵢ]` via the substitution so
1589
+ // Phase C sees TCon('Array', …) and dispatches to the Array instance,
1590
+ // while the result position becomes `[Union γ₁ … γₙ]`.
1591
+ const freshByOrigId = new Map();
1592
+ const elemByOrigId = new Map();
1593
+ for (const id of polyIds) {
1594
+ if (!polyMode.get(id))
1595
+ continue;
1596
+ freshByOrigId.set(id, []);
1597
+ if (polyMode.get(id) === 'arrayUnion')
1598
+ elemByOrigId.set(id, []);
1599
+ }
1600
+ const newInputs = inputPositions.map((p, i) => {
1601
+ if (p.tag === 'TVar' && polyIds.has(p.id) && polyMode.get(p.id)) {
1602
+ const mode = polyMode.get(p.id);
1603
+ const fv = (0, types_2.tVar)();
1604
+ freshByOrigId.get(p.id).push(fv);
1605
+ if (mode === 'arrayUnion') {
1606
+ const gv = (0, types_2.tVar)();
1607
+ elemByOrigId.get(p.id).push(gv);
1608
+ if (fv.tag === 'TVar')
1609
+ engine.subst.set(fv.id, (0, types_2.tArray)(gv));
1610
+ // Return the concrete Array type for this input slot so the arg
1611
+ // unifies directly with `[γᵢ]`.
1612
+ void i;
1613
+ return (0, types_2.tArray)(gv);
1614
+ }
1615
+ return fv;
1616
+ }
1617
+ return p;
1618
+ });
1619
+ // Rewrite top-level result occurrence (if any) into the appropriate
1620
+ // combinator for the polyId's mode.
1621
+ let newResult = finalResult;
1622
+ if (finalResult.tag === 'TVar' && polyIds.has(finalResult.id) && polyMode.get(finalResult.id)) {
1623
+ const id = finalResult.id;
1624
+ const mode = polyMode.get(id);
1625
+ if (mode === 'merge') {
1626
+ const fresh = freshByOrigId.get(id) ?? [];
1627
+ if (fresh.length === 0)
1628
+ newResult = finalResult;
1629
+ else if (fresh.length === 1)
1630
+ newResult = fresh[0];
1631
+ else
1632
+ newResult = (0, types_2.tCon)(types_2.T_MERGE, fresh);
1633
+ }
1634
+ else if (mode === 'arrayUnion') {
1635
+ const elems = elemByOrigId.get(id) ?? [];
1636
+ if (elems.length === 0)
1637
+ newResult = finalResult;
1638
+ else if (elems.length === 1)
1639
+ newResult = (0, types_2.tArray)(elems[0]);
1640
+ else
1641
+ newResult = (0, types_2.tArray)((0, types_2.tUnion)(elems));
1642
+ }
1643
+ }
1644
+ // Replicate pending constraints from each original poly TVar onto its
1645
+ // fresh αᵢ children so Phase C drives per-row container-instance lookup.
1646
+ // For arrayUnion mode the αᵢ already resolve to TCon('Array', …) via
1647
+ // the substitution above, so Phase C maps typeToCheck='Array'.
1648
+ const originalPending = engine.pendingConstraints.slice();
1649
+ for (const pc of originalPending) {
1650
+ if (!polyIds.has(pc.varId))
1651
+ continue;
1652
+ const freshList = freshByOrigId.get(pc.varId) ?? [];
1653
+ for (const fv of freshList) {
1654
+ if (fv.tag !== 'TVar')
1655
+ continue;
1656
+ engine.pendingConstraints.push({
1657
+ varId: fv.id,
1658
+ constraintName: pc.constraintName,
1659
+ node: pc.node,
1660
+ reps: pc.reps,
1661
+ });
1662
+ }
1663
+ }
1664
+ // Rebuild the curried TFun chain right-to-left.
1665
+ let rebuilt = newResult;
1666
+ for (let i = newInputs.length - 1; i >= 0; i--) {
1667
+ rebuilt = (0, types_2.tFun)(newInputs[i], rebuilt);
1668
+ }
1669
+ return rebuilt;
1670
+ }
1671
+ /** Bind the parameter-position arg of the host TCon to `paramRec`. Uses
1672
+ * `findHostSlots` to identify the slot — for a 2-arg `QueryTag p row` the
1673
+ * slot is index 0; for the legacy 1-arg form there is no parameter slot
1674
+ * and this is a no-op. When the slot is already a concrete record we
1675
+ * unify (so user-annotated forms still match); when it is a TVar we
1676
+ * bind it directly via the engine's substitution.
1677
+ *
1678
+ * When the host TCon's declared arity does NOT include a parameter arg
1679
+ * (e.g. `QueryTag :: a -> QueryTag a` carries only the row), the record is
1680
+ * instead attached as `hostType.paramHint` so hover and signature help
1681
+ * can still substitute the parameter slot of any instance-callable
1682
+ * overload (`QueryTag() :: p -> Promise [o]`) at display time. */
1683
+ function bindParamSlot(engine, hostType, paramRec) {
1684
+ const { paramArg } = (0, typeUtils_1.findHostSlots)(hostType);
1685
+ if (!paramArg) {
1686
+ if (hostType.tag === 'TCon')
1687
+ hostType.paramHint = paramRec;
1688
+ return;
1689
+ }
1690
+ const applied = engine.subst.apply(paramArg);
1691
+ if (applied.tag === 'TVar') {
1692
+ engine.subst.set(applied.id, paramRec);
1693
+ return;
1694
+ }
1695
+ // Slot already bound (e.g. a nested sub-query's own params threaded
1696
+ // through a shared `p` in the selector union, or a prior harvest).
1697
+ // Merge the harvested fields in FIELD-WISE — two closed records with
1698
+ // disjoint fields do not unify, so a plain record unify would silently
1699
+ // drop the new fields. Write the merged record back through the slot's
1700
+ // TVar when there is one, otherwise directly into the host's arg slot.
1701
+ if (applied.tag === 'TRecord' && paramRec.tag === 'TRecord') {
1702
+ const fields = { ...applied.fields };
1703
+ let changed = false;
1704
+ for (const k in paramRec.fields) {
1705
+ const incoming = engine.subst.apply(paramRec.fields[k]);
1706
+ if (k in fields) {
1707
+ try {
1708
+ engine.subst.mergeFrom((0, unify_1.unify)(fields[k], incoming));
1709
+ }
1710
+ catch { /* skip conflict */ }
1711
+ }
1712
+ else {
1713
+ fields[k] = incoming;
1714
+ changed = true;
1715
+ }
1716
+ }
1717
+ if (changed) {
1718
+ const merged = { ...applied, fields };
1719
+ if (paramArg.tag === 'TVar') {
1720
+ engine.subst.set(paramArg.id, merged);
1721
+ }
1722
+ else if (hostType.tag === 'TCon' && hostType.args.length >= 2) {
1723
+ hostType.args[hostType.args.length - 2] = merged;
1724
+ // The in-place write above only updates THIS host object. Other
1725
+ // type-vars may already be bound to the stale pre-merge record —
1726
+ // e.g. a shared `p` pinned through the selector union, or an
1727
+ // outer combinator's slot (`QueryTag#concat`'s `p2`) unified
1728
+ // against it while this call was inferred as an inline argument.
1729
+ // Sweep the substitution and upgrade every binding that is
1730
+ // structurally the stale record so all aliases observe the merge
1731
+ // (same precedent as the Picked-projection subst sweep above).
1732
+ for (const [id, bound] of engine.subst.entries()) {
1733
+ const b = engine.subst.apply(bound);
1734
+ if (b.tag === 'TRecord' && (0, types_2.structuralEquals)(b, applied)) {
1735
+ engine.subst.set(id, merged);
1736
+ }
1737
+ }
1738
+ }
1739
+ }
1740
+ return;
1741
+ }
1742
+ try {
1743
+ engine.subst.mergeFrom((0, unify_1.unify)(applied, paramRec));
1744
+ }
1745
+ catch { /* incompatible — surface via existing unification diagnostics elsewhere */ }
1746
+ }
1747
+ /** Unify each field of `paramRec` whose name matches a column of the
1748
+ * host's row record with that column's type. Skips fields that are
1749
+ * already bound to a concrete (non-TVar) type — those came from a
1750
+ * helper's declared signature and must take precedence over the row.
1751
+ * Used after `gatherParamRecord` so that, e.g., the body
1752
+ * `p => p.id` against an `OrganisationRow { id :: Number }` projection
1753
+ * yields `id :: Number` in the params slot instead of a free TVar. */
1754
+ function enrichParamRecFromRow(engine, hostType, paramRec) {
1755
+ if (paramRec.tag !== 'TRecord')
1756
+ return;
1757
+ const { rowArg } = (0, typeUtils_1.findHostSlots)(hostType);
1758
+ if (!rowArg)
1759
+ return;
1760
+ enrichParamRecFromRecord(engine, rowArg, paramRec);
1761
+ }
1762
+ /** Lower-level helper: unify each field of `paramRec` whose name matches
1763
+ * a field in `rowSource` with that field's type, when the param field
1764
+ * is still an unbound TVar. `rowSource` may be a TRecord, a TCon
1765
+ * alias, or anything that expands via `maybeExpandAlias`. */
1766
+ function enrichParamRecFromRecord(engine, rowSource, paramRec) {
1767
+ if (paramRec.tag !== 'TRecord')
1768
+ return;
1769
+ const row = engine.maybeExpandAlias(engine.subst.apply(rowSource));
1770
+ if (row.tag !== 'TRecord')
1771
+ return;
1772
+ for (const k in paramRec.fields) {
1773
+ if (!(k in row.fields))
1774
+ continue;
1775
+ const v = engine.subst.apply(paramRec.fields[k]);
1776
+ if (v.tag !== 'TVar')
1777
+ continue;
1778
+ const colType = engine.subst.apply(row.fields[k]);
1779
+ try {
1780
+ engine.subst.mergeFrom((0, unify_1.unify)(v, colType));
1781
+ }
1782
+ catch { /* skip conflict */ }
1783
+ }
1784
+ }
1785
+ /** Project an array-literal AST against a row type, building a structural
1786
+ * TRecord. Returns null when the row argument cannot be resolved to a
1787
+ * TRecord with field information. */
1788
+ function projectArrayAgainstRow(engine, arrayNode, rowArg) {
1789
+ const expanded = engine.maybeExpandAlias(engine.subst.apply(rowArg));
1790
+ if (expanded.tag !== 'TRecord')
1791
+ return null;
1792
+ const rowFields = expanded.fields;
1793
+ const rowAlias = expanded.alias;
1794
+ const projected = {};
1795
+ let sawColumnSelector = false;
1796
+ for (const elem of arrayNode.elements) {
1797
+ if (!elem)
1798
+ continue;
1799
+ const elemNode = elem;
1800
+ // 1. String literal — column reference into the row.
1801
+ if (elemNode.type === 'Literal' && typeof elemNode.value === 'string') {
1802
+ const key = elemNode.value;
1803
+ if (key in rowFields) {
1804
+ projected[key] = engine.subst.apply(rowFields[key]);
1805
+ sawColumnSelector = true;
1806
+ }
1807
+ continue;
1808
+ }
1809
+ const elemType = engine.subst.apply(engine.getNodeType(elemNode) ?? (0, types_2.tVar)());
1810
+ // 2. Identifier of `Prop T` type — name becomes the field key.
1811
+ if (elemNode.type === 'Identifier') {
1812
+ const idName = elemNode.name;
1813
+ if (idName in rowFields) {
1814
+ projected[idName] = engine.subst.apply(rowFields[idName]);
1815
+ sawColumnSelector = true;
1816
+ continue;
1817
+ }
1818
+ // The query-builder convention is `Prop t v` (tag, value): the VALUE
1819
+ // type lives at the LAST arg slot. Older single-arg `Prop v`
1820
+ // declarations also work because we still pick the last arg.
1821
+ if (elemType.tag === 'TCon' && elemType.name === 'Prop' && elemType.args.length >= 1) {
1822
+ projected[idName] = engine.subst.apply(elemType.args[elemType.args.length - 1]);
1823
+ continue;
1824
+ }
1825
+ }
1826
+ // 3. Nested call returning a related row — resolve the FK key via
1827
+ // the parent row's method-shadows. Try to recover the *source*
1828
+ // row name from the callee's pre-projection signature (its
1829
+ // Picked marker), since the call's stored result has already
1830
+ // been projected and lost its alias.
1831
+ //
1832
+ // Also handles bare identifier references to row constructors
1833
+ // (e.g. `LocationType` listed without parentheses). In that
1834
+ // case `elemType` is the constructor's TFun signature; we
1835
+ // extract the row name from its Picked marker and apply with
1836
+ // no inner projection — meaning all of the child row's columns
1837
+ // are selected (the query-builder convention for an unparenthesised
1838
+ // relation).
1839
+ if (rowAlias) {
1840
+ const childRowName = extractChildRowName(engine, elemNode, elemType);
1841
+ if (childRowName) {
1842
+ // Bare-identifier vs nested-call paths use different sources
1843
+ // for the inner record:
1844
+ //
1845
+ // - Bare identifier (e.g. `LocationType` without parens): the
1846
+ // element type is the constructor itself — typically a
1847
+ // value-as-callable Union of `{ props :: {…} } | Table R |
1848
+ // ([Sel] -> QueryTag p (Picked R Sel))`. Walking that union
1849
+ // for a TRecord would grab the `{ props :: {…} }` branch,
1850
+ // which is the constructor's method-shadow surface, NOT the
1851
+ // row's columns. For a bare relation reference the query-builder
1852
+ // convention is "select every column of the child row", so
1853
+ // expand the row alias directly and skip
1854
+ // `extractInnerProjectedRecord` entirely.
1855
+ //
1856
+ // - Nested call (e.g. `LocationType(["id"])`): the call's
1857
+ // stored result type IS the projected row — recover it via
1858
+ // `extractInnerProjectedRecord`.
1859
+ let innerProjected;
1860
+ if (elemNode.type === 'Identifier') {
1861
+ innerProjected = expandRowAliasToRecord(engine, childRowName);
1862
+ }
1863
+ else {
1864
+ innerProjected = extractInnerProjectedRecord(engine, elemType);
1865
+ }
1866
+ const shape = nestedResultShape(engine, elemType);
1867
+ // A nested element whose call result does not carry its row (a
1868
+ // filter such as a query builder's `exists`) adds no field.
1869
+ if (shape === 'omit')
1870
+ continue;
1871
+ const match = findShadowKeyForChildRow(rowAlias, childRowName, innerProjected);
1872
+ if (match) {
1873
+ projected[match.key] = shape === null || shape === 'list'
1874
+ ? match.fieldType
1875
+ : singleFieldType(match.fieldType, shape === 'nullable');
1876
+ continue;
1877
+ }
1878
+ // No shadow found — element is silently dropped from the
1879
+ // projection. An earlier attempt at emitting `'<X>' is not a
1880
+ // relation of '<Y>'` here proved unreliable (false positives on
1881
+ // valid relations whose shadow factory had been alias-expanded
1882
+ // beyond simple TCon recognition, plus duplicate diagnostics from
1883
+ // the rewrite-walker visiting each Picked occurrence). Wrong-
1884
+ // relation cases must instead be caught upstream by unifying
1885
+ // each array element against the parent's `<Table>Selector`
1886
+ // union before the projection runs.
1887
+ }
1888
+ }
1889
+ // Anything else — skipped silently.
1890
+ }
1891
+ // query-builder convention: an array with no explicit column selectors
1892
+ // (only relations / calculated fields / paging helpers) implicitly
1893
+ // selects every column of the row. Existing keys (e.g. relations
1894
+ // sharing a column name) are preserved and not overwritten.
1895
+ let defaultProjection = false;
1896
+ if (!sawColumnSelector) {
1897
+ for (const k in rowFields) {
1898
+ if (!(k in projected)) {
1899
+ projected[k] = engine.subst.apply(rowFields[k]);
1900
+ defaultProjection = true;
1901
+ }
1902
+ }
1903
+ }
1904
+ const out = (0, types_2.tRecord)(projected);
1905
+ if (defaultProjection)
1906
+ out.defaultProjection = true;
1907
+ // Tag the projected record with its source row name so downstream
1908
+ // unification against a `Picked R _` slot can match by row identity
1909
+ // (see `unifyPickedAgainstRecord` in src/hm/unify.ts). This is the
1910
+ // generic Picked-projection bookkeeping — independent of any
1911
+ // particular library.
1912
+ if (rowAlias)
1913
+ out.pickedFrom = rowAlias;
1914
+ return out;
1915
+ }
1916
+ /**
1917
+ * How a nested element contributes to its parent's projection, read off the
1918
+ * element type's instance-callable annotation (`Name() :: p -> …`): a nested
1919
+ * query contributes what calling it would return.
1920
+ * - `'list'`: the row sits in an array (`p -> Promise e [o]`);
1921
+ * - `'single'` / `'nullable'`: the row itself (`p -> Promise e o`,
1922
+ * `p -> RTask r e (o | Null)`);
1923
+ * - `'omit'`: the row does not occur in the result (`p -> Promise e
1924
+ * Boolean`): a filter, no field;
1925
+ * - `null`: no callable annotation — keep the parent's relation shadow.
1926
+ * Library-agnostic: query-builder uses it for `one` (`QueryOne`) and `exists`
1927
+ * (`QueryExists`), any query builder can annotate its tags the same way.
1928
+ */
1929
+ function nestedResultShape(engine, elemType) {
1930
+ const t = engine.subst.apply(elemType);
1931
+ if (t.tag !== 'TCon')
1932
+ return null;
1933
+ const callables = engine.instanceCallables.get(t.name);
1934
+ if (!callables || callables.length === 0)
1935
+ return null;
1936
+ const branch = (0, env_1.instantiate)(callables[0]);
1937
+ if (branch.tag !== 'TFun')
1938
+ return null;
1939
+ const { carrierTVarId } = (0, typeUtils_1.findOverloadSlots)(branch);
1940
+ if (carrierTVarId === null)
1941
+ return 'omit';
1942
+ let inArray = false;
1943
+ let nullable = false;
1944
+ const walk = (x, underArray, underUnion) => {
1945
+ if (x.tag === 'TVar' && x.id === carrierTVarId) {
1946
+ if (underArray)
1947
+ inArray = true;
1948
+ return;
1949
+ }
1950
+ if (x.tag === 'TCon') {
1951
+ const isArray = x.name === types_2.T_ARRAY;
1952
+ const isUnion = x.name === 'Union';
1953
+ if (isUnion && x.args.some(a => a.tag === 'TVar' && a.id === carrierTVarId)
1954
+ && x.args.some(a => a.tag === 'TCon' && (a.name === 'Null' || a.name === 'Undefined'))) {
1955
+ nullable = true;
1956
+ }
1957
+ for (const a of x.args)
1958
+ walk(a, underArray || isArray, underUnion || isUnion);
1959
+ }
1960
+ };
1961
+ walk(branch.result, false, false);
1962
+ if (inArray)
1963
+ return 'list';
1964
+ return nullable ? 'nullable' : 'single';
1965
+ }
1966
+ /** The single-valued field type for a relation whose shadow may be a list:
1967
+ * `[X]` → `X`, optionally `| Null`. */
1968
+ function singleFieldType(fieldType, nullable) {
1969
+ const one = fieldType.tag === 'TCon' && fieldType.name === types_2.T_ARRAY && fieldType.args.length === 1
1970
+ ? fieldType.args[0]
1971
+ : fieldType;
1972
+ return nullable ? (0, types_2.tUnion)([one, (0, types_2.tCon)('Null', [])]) : one;
1973
+ }
1974
+ /** Recover the source row name for a projected element. We can't read
1975
+ * it off `elemType.args[0]` directly when the element is a nested call,
1976
+ * because by the time the outer projection runs the inner call's
1977
+ * stored result has already been projected — its alias has been
1978
+ * stripped on purpose. Instead, when the element is a CallExpression
1979
+ * inspect the callee Identifier's TFun signature for a `Picked R _`
1980
+ * marker. Falls back to reading the alias off `elemType` for the
1981
+ * non-call (already-aliased value) case. */
1982
+ function extractChildRowName(engine, elemNode, elemType) {
1983
+ if (elemNode.type === 'CallExpression') {
1984
+ const callee = elemNode.callee;
1985
+ const calleeType = engine.subst.apply(engine.getNodeType(callee) ?? (0, types_2.tVar)());
1986
+ const found = findPickedRowInType(engine, calleeType);
1987
+ if (found)
1988
+ return found;
1989
+ }
1990
+ // Bare identifier referencing a row constructor — e.g. `LocationType`
1991
+ // listed inside another selector array. Its type is a TFun whose
1992
+ // result carries the `Picked R _` marker, or (for a query builder's value-as-
1993
+ // callable overloads) a Union containing such a TFun alongside a
1994
+ // `Table R` / `QueryTag R` branch. Either way `findPickedRowInType`
1995
+ // recurses into the structure and surfaces the row alias.
1996
+ if (elemNode.type === 'Identifier') {
1997
+ const found = findPickedRowInType(engine, elemType);
1998
+ if (found)
1999
+ return found;
2000
+ }
2001
+ if (elemType.tag === 'TCon' && elemType.args.length >= 1) {
2002
+ for (const arg of elemType.args) {
2003
+ const inner = engine.maybeExpandAlias(engine.subst.apply(arg));
2004
+ if (inner.tag === 'TRecord' && inner.alias)
2005
+ return inner.alias;
2006
+ // Only treat a bare TCon as a row reference when it names a RECORD
2007
+ // alias (`DepartmentsRow :: { … }`, or `Department :: { … }` — no naming
2008
+ // convention required). Without this guard the fallback misfires on
2009
+ // generic helpers like `Limit Number` or `Table SomeRecord`,
2010
+ // returning `Number` / `Table` as a "row" and triggering bogus
2011
+ // shadow lookups (and worse, sometimes successful matches).
2012
+ if (inner.tag === 'TCon' && inner.args.length === 0
2013
+ && engine.typeAliases.has(inner.name)
2014
+ && engine.maybeExpandAlias(inner).tag === 'TRecord')
2015
+ return inner.name;
2016
+ }
2017
+ }
2018
+ return null;
2019
+ }
2020
+ function findPickedRowInType(engine, t) {
2021
+ // Collect every distinct row name appearing in a `Picked R _` marker
2022
+ // anywhere in `t`. When the type contains multiple different row
2023
+ // names (typical of a `*Selector` union branching across many related
2024
+ // tables) the element is ambiguous — returning any of them risks
2025
+ // mis-classifying e.g. an SQL fragment as a relation, so we surface
2026
+ // null and let the caller drop the element. The caller only needs a
2027
+ // row name when the type unambiguously commits to a single one.
2028
+ const found = new Set();
2029
+ const seen = new Set();
2030
+ const go = (x) => {
2031
+ if (seen.has(x))
2032
+ return;
2033
+ seen.add(x);
2034
+ const a = engine.subst.apply(x);
2035
+ if (a.tag === 'TCon' && a.name === types_2.T_PICKED && a.args.length >= 1) {
2036
+ const r = engine.subst.apply(a.args[0]);
2037
+ if (r.tag === 'TCon') {
2038
+ found.add(r.name);
2039
+ return;
2040
+ }
2041
+ if (r.tag === 'TRecord' && r.alias) {
2042
+ found.add(r.alias);
2043
+ return;
2044
+ }
2045
+ }
2046
+ if (a.tag === 'TCon') {
2047
+ for (const arg of a.args)
2048
+ go(arg);
2049
+ return;
2050
+ }
2051
+ if (a.tag === 'TFun') {
2052
+ // Only walk the result side: a value-as-callable constructor
2053
+ // signature `[ChildSelector] -> QueryTag p (Picked ChildRow a)` has a
2054
+ // selector union in its param that legitimately mentions many
2055
+ // Picked rows from sibling tables. Treating those as candidate
2056
+ // child rows would falsely flag the constructor as ambiguous.
2057
+ go(a.result);
2058
+ return;
2059
+ }
2060
+ };
2061
+ go(t);
2062
+ if (found.size === 1)
2063
+ return [...found][0];
2064
+ return null;
2065
+ }
2066
+ /** Extract the inner projected record from a nested call's element type.
2067
+ * When the inner Picked projection has run, `elemType` is typically a
2068
+ * callable wrapper (e.g. `QueryTag <record>`, `Table <record>`, or in
2069
+ * multi-arg form `QueryTag <param> <record>`) wrapping the projected row
2070
+ * TRecord. Targets the ROW slot specifically via `findHostSlots` —
2071
+ * for `QueryTag p row` the row lives at the last arg, and the param
2072
+ * slot may itself have been substituted to a TRecord by an earlier
2073
+ * `bindParamSlot` call. Falling back to "first TRecord arg" would
2074
+ * return the params record, conflating the projected row with the
2075
+ * call's parameter shape. */
2076
+ function extractInnerProjectedRecord(engine, elemType) {
2077
+ const t = engine.subst.apply(elemType);
2078
+ if (t.tag !== 'TCon' || t.args.length === 0)
2079
+ return null;
2080
+ const { rowArg } = (0, typeUtils_1.findHostSlots)(t);
2081
+ const candidates = rowArg ? [rowArg] : t.args;
2082
+ for (const arg of candidates) {
2083
+ const inner = engine.maybeExpandAlias(engine.subst.apply(arg));
2084
+ if (inner.tag === 'TRecord') {
2085
+ return inner.alias ? { ...inner, alias: undefined } : inner;
2086
+ }
2087
+ }
2088
+ return null;
2089
+ }
2090
+ /** Expand a row alias name (e.g. `LocationTypeRow`) to its structural
2091
+ * TRecord, with the alias stripped so it inlines in hover output rather
2092
+ * than showing as the bare alias. Returns null when no alias is
2093
+ * registered or when expansion doesn't yield a TRecord. */
2094
+ function expandRowAliasToRecord(engine, rowName) {
2095
+ const expanded = engine.maybeExpandAlias({ tag: 'TCon', name: rowName, args: [] });
2096
+ if (expanded.tag !== 'TRecord')
2097
+ return null;
2098
+ if (!expanded.alias)
2099
+ return expanded;
2100
+ return { ...expanded, alias: undefined };
2101
+ }
2102
+ /** Search the parent row's registered method-shadows for one whose return
2103
+ * type matches `[ChildRow]` (list-valued relation) or `ChildRow` (single).
2104
+ * Returns the shadow's name as the projected key plus its return type.
2105
+ * When `innerProjected` is supplied (the projected record from a nested
2106
+ * call), the field type substitutes that record for the bare row alias. */
2107
+ function findShadowKeyForChildRow(parentRowName, childRowName, innerProjected = null) {
2108
+ const names = (0, methodRegistry_1.getMethodNames)(parentRowName);
2109
+ for (const name of names) {
2110
+ const entry = (0, methodRegistry_1.lookupMethod)(parentRowName, name);
2111
+ if (!entry)
2112
+ continue;
2113
+ let returnType;
2114
+ try {
2115
+ returnType = entry.factory([]);
2116
+ }
2117
+ catch {
2118
+ continue;
2119
+ }
2120
+ // List-valued: [ChildRow]
2121
+ if (returnType.tag === 'TCon' && returnType.name === types_2.T_ARRAY && returnType.args.length === 1) {
2122
+ const inner = returnType.args[0];
2123
+ if (inner.tag === 'TCon' && inner.name === childRowName) {
2124
+ const fieldType = innerProjected ? { ...returnType, args: [innerProjected] } : returnType;
2125
+ return { key: name, fieldType };
2126
+ }
2127
+ if (inner.tag === 'TRecord' && inner.alias === childRowName) {
2128
+ const fieldType = innerProjected ? { ...returnType, args: [innerProjected] } : returnType;
2129
+ return { key: name, fieldType };
2130
+ }
2131
+ }
2132
+ // Single-valued: ChildRow directly.
2133
+ if (returnType.tag === 'TCon' && returnType.name === childRowName) {
2134
+ return { key: name, fieldType: innerProjected ?? returnType };
2135
+ }
2136
+ if (returnType.tag === 'TRecord' && returnType.alias === childRowName) {
2137
+ return { key: name, fieldType: innerProjected ?? returnType };
2138
+ }
2139
+ }
2140
+ return null;
2141
+ }
2142
+ /**
2143
+ * Reduce `Awaited a` markers in a call result: `Awaited (Promise e x)` → `x`
2144
+ * (repeatedly, a Promise never holds a Promise), anything else → itself.
2145
+ * Used by `Promise#then` so a callback that returns a Promise flattens.
2146
+ */
2147
+ function applyAwaitedReduction(engine, result) {
2148
+ // `Awaited` only appears in a Promise result (Promise#then); skip the walk
2149
+ // for everything else.
2150
+ if (!(result.tag === 'TCon' && result.name === 'Promise'))
2151
+ return result;
2152
+ return (0, typeUtils_1.mapType)(result, n => {
2153
+ if (n.tag !== 'TCon' || n.name !== 'Awaited' || n.args.length !== 1)
2154
+ return undefined;
2155
+ let inner = engine.subst.apply(applyAwaitedReduction(engine, n.args[0]));
2156
+ while (inner.tag === 'TCon' && inner.name === 'Promise' && inner.args.length === 2) {
2157
+ inner = engine.subst.apply(inner.args[1]);
2158
+ }
2159
+ return inner;
2160
+ });
2161
+ }
2162
+ //# sourceMappingURL=call-rows.js.map