presubmit 0.1.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 (220) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +51 -0
  3. package/THIRD_PARTY_NOTICES.md +24 -0
  4. package/apps/web/dist/assets/FileCode-CZZH52o7.js +5 -0
  5. package/apps/web/dist/assets/FileCode-DovDO7Jh.css +1 -0
  6. package/apps/web/dist/assets/SettingsPage-CRvOwdjt.js +4 -0
  7. package/apps/web/dist/assets/SettingsPage-UbYSCwJj.css +1 -0
  8. package/apps/web/dist/assets/TerminalPanel-0sw-J6YS.css +1 -0
  9. package/apps/web/dist/assets/TerminalPanel-BqUjPWav.js +16 -0
  10. package/apps/web/dist/assets/index-BhqNNFja.js +54 -0
  11. package/apps/web/dist/assets/index-DD8VXy8H.css +1 -0
  12. package/apps/web/dist/assets/presubmit-mark-BBQ19Fmr.svg +7 -0
  13. package/apps/web/dist/assets/presubmit-mark-busy-CwBC-7on.svg +8 -0
  14. package/apps/web/dist/assets/react-vendor-wiHys0m2.js +9 -0
  15. package/apps/web/dist/assets/rolldown-runtime-hePW80VL.js +1 -0
  16. package/apps/web/dist/index.html +6 -0
  17. package/apps/web/dist/service-worker.js +11 -0
  18. package/dist/apps/server/src/agent-builder.js +204 -0
  19. package/dist/apps/server/src/attach.js +163 -0
  20. package/dist/apps/server/src/attachments.js +86 -0
  21. package/dist/apps/server/src/browser-access.js +131 -0
  22. package/dist/apps/server/src/check-provenance.js +95 -0
  23. package/dist/apps/server/src/check-supervisor.js +112 -0
  24. package/dist/apps/server/src/checks.js +402 -0
  25. package/dist/apps/server/src/child-collaboration-guidance.js +2 -0
  26. package/dist/apps/server/src/child-sessions.js +191 -0
  27. package/dist/apps/server/src/cli.js +162 -0
  28. package/dist/apps/server/src/conversation-search.js +12 -0
  29. package/dist/apps/server/src/coordinator-messages.js +72 -0
  30. package/dist/apps/server/src/dev-auth.js +54 -0
  31. package/dist/apps/server/src/dev-server.js +201 -0
  32. package/dist/apps/server/src/dev-worker.js +48 -0
  33. package/dist/apps/server/src/diagnostics.js +105 -0
  34. package/dist/apps/server/src/fast-mode.js +8 -0
  35. package/dist/apps/server/src/folder-picker.js +54 -0
  36. package/dist/apps/server/src/git-blobs.js +62 -0
  37. package/dist/apps/server/src/git-handoff.js +127 -0
  38. package/dist/apps/server/src/history-sources.js +59 -0
  39. package/dist/apps/server/src/hub.js +159 -0
  40. package/dist/apps/server/src/internal-transport.js +38 -0
  41. package/dist/apps/server/src/local-embeddings.js +70 -0
  42. package/dist/apps/server/src/ollama-setup.js +56 -0
  43. package/dist/apps/server/src/planning.js +30 -0
  44. package/dist/apps/server/src/project-agents.js +276 -0
  45. package/dist/apps/server/src/project-memory.js +94 -0
  46. package/dist/apps/server/src/projects.js +106 -0
  47. package/dist/apps/server/src/queued-launch.js +13 -0
  48. package/dist/apps/server/src/reply-search.js +172 -0
  49. package/dist/apps/server/src/review-context.js +60 -0
  50. package/dist/apps/server/src/review-refresh.js +14 -0
  51. package/dist/apps/server/src/reviewers.js +75 -0
  52. package/dist/apps/server/src/search-settings.js +22 -0
  53. package/dist/apps/server/src/semantic-history.js +186 -0
  54. package/dist/apps/server/src/server.js +4338 -0
  55. package/dist/apps/server/src/session-changes.js +181 -0
  56. package/dist/apps/server/src/session-router-settings.js +198 -0
  57. package/dist/apps/server/src/session-workspaces.js +135 -0
  58. package/dist/apps/server/src/sessions.js +579 -0
  59. package/dist/apps/server/src/shared-auth.js +70 -0
  60. package/dist/apps/server/src/shell-evaluator-settings.js +53 -0
  61. package/dist/apps/server/src/store.js +203 -0
  62. package/dist/apps/server/src/tailscale-process.js +115 -0
  63. package/dist/apps/server/src/tailscale-serve-worker.js +33 -0
  64. package/dist/apps/server/src/tailscale-serve.js +276 -0
  65. package/dist/apps/server/src/task-capacity.js +92 -0
  66. package/dist/apps/server/src/task-graph.js +190 -0
  67. package/dist/apps/server/src/task-logs.js +74 -0
  68. package/dist/apps/server/src/task-numbers.js +25 -0
  69. package/dist/apps/server/src/task-orchestrator.js +1088 -0
  70. package/dist/apps/server/src/terminal.js +182 -0
  71. package/dist/apps/server/src/terminals.js +80 -0
  72. package/dist/apps/server/src/tool-safety.js +2 -0
  73. package/dist/apps/server/src/workspace-lock.js +140 -0
  74. package/dist/apps/server/src/workspace-watcher.js +65 -0
  75. package/dist/apps/server/src/workspace.js +517 -0
  76. package/dist/packages/agent-pi/src/agent-builder-tool.js +32 -0
  77. package/dist/packages/agent-pi/src/agent-capabilities.js +44 -0
  78. package/dist/packages/agent-pi/src/ask-user.js +86 -0
  79. package/dist/packages/agent-pi/src/auth.js +510 -0
  80. package/dist/packages/agent-pi/src/check-tools.js +72 -0
  81. package/dist/packages/agent-pi/src/command-policy.js +246 -0
  82. package/dist/packages/agent-pi/src/coordinator-tools.js +122 -0
  83. package/dist/packages/agent-pi/src/fast-mode.js +67 -0
  84. package/dist/packages/agent-pi/src/file-tools.js +163 -0
  85. package/dist/packages/agent-pi/src/history-tool.js +40 -0
  86. package/dist/packages/agent-pi/src/history.js +34 -0
  87. package/dist/packages/agent-pi/src/index.js +177 -0
  88. package/dist/packages/agent-pi/src/ipc.js +314 -0
  89. package/dist/packages/agent-pi/src/jev-session-router.js +408 -0
  90. package/dist/packages/agent-pi/src/jev-tools.js +71 -0
  91. package/dist/packages/agent-pi/src/local-model.js +277 -0
  92. package/dist/packages/agent-pi/src/memory-tools.js +119 -0
  93. package/dist/packages/agent-pi/src/model.js +25 -0
  94. package/dist/packages/agent-pi/src/planning.js +206 -0
  95. package/dist/packages/agent-pi/src/resource-loader.js +23 -0
  96. package/dist/packages/agent-pi/src/review-tools.js +158 -0
  97. package/dist/packages/agent-pi/src/review-transition.js +73 -0
  98. package/dist/packages/agent-pi/src/review.js +40 -0
  99. package/dist/packages/agent-pi/src/routing.js +27 -0
  100. package/dist/packages/agent-pi/src/session-setup.js +118 -0
  101. package/dist/packages/agent-pi/src/shell-context.js +51 -0
  102. package/dist/packages/agent-pi/src/shell-policy.js +281 -0
  103. package/dist/packages/agent-pi/src/shell-safety.js +205 -0
  104. package/dist/packages/agent-pi/src/shell.js +121 -0
  105. package/dist/packages/agent-pi/src/snapshot-permissions.js +12 -0
  106. package/dist/packages/agent-pi/src/spike.js +41 -0
  107. package/dist/packages/agent-pi/src/task-tools.js +53 -0
  108. package/dist/packages/agent-pi/src/types.js +1 -0
  109. package/dist/packages/agent-pi/src/usage.js +30 -0
  110. package/dist/packages/agent-pi/src/worker.js +602 -0
  111. package/dist/packages/protocol/src/activity-summary.js +77 -0
  112. package/dist/packages/protocol/src/agents.js +301 -0
  113. package/dist/packages/protocol/src/browser-access.js +1 -0
  114. package/dist/packages/protocol/src/checks.js +40 -0
  115. package/dist/packages/protocol/src/child-sessions.js +28 -0
  116. package/dist/packages/protocol/src/command-policy.js +3 -0
  117. package/dist/packages/protocol/src/coordinator.js +135 -0
  118. package/dist/packages/protocol/src/delegation.js +40 -0
  119. package/dist/packages/protocol/src/git-diff.js +71 -0
  120. package/dist/packages/protocol/src/git-handoff.js +1 -0
  121. package/dist/packages/protocol/src/index.js +1 -0
  122. package/dist/packages/protocol/src/memory.js +46 -0
  123. package/dist/packages/protocol/src/metrics.js +70 -0
  124. package/dist/packages/protocol/src/planning.js +138 -0
  125. package/dist/packages/protocol/src/retrieval.js +36 -0
  126. package/dist/packages/protocol/src/reviewers.js +17 -0
  127. package/dist/packages/protocol/src/search.js +16 -0
  128. package/dist/packages/protocol/src/session-changes.js +29 -0
  129. package/dist/packages/protocol/src/session-router.js +123 -0
  130. package/dist/packages/protocol/src/shell-evaluator.js +43 -0
  131. package/dist/packages/protocol/src/task-graph.js +1 -0
  132. package/dist/packages/protocol/src/token-usage.js +17 -0
  133. package/dist/packages/protocol/src/user-questions.js +106 -0
  134. package/package.json +71 -0
  135. package/vendor/lancedb/NODEJS_THIRD_PARTY_LICENSES.md +668 -0
  136. package/vendor/lancedb/RUST_THIRD_PARTY_LICENSES.html +14607 -0
  137. package/vendor/lancedb/dist/arrow.d.ts +296 -0
  138. package/vendor/lancedb/dist/arrow.js +1145 -0
  139. package/vendor/lancedb/dist/arrow_type.d.ts +9 -0
  140. package/vendor/lancedb/dist/arrow_type.js +29 -0
  141. package/vendor/lancedb/dist/connection.d.ts +508 -0
  142. package/vendor/lancedb/dist/connection.js +298 -0
  143. package/vendor/lancedb/dist/embedding/embedding_function.d.ts +103 -0
  144. package/vendor/lancedb/dist/embedding/embedding_function.js +192 -0
  145. package/vendor/lancedb/dist/embedding/index.d.ts +37 -0
  146. package/vendor/lancedb/dist/embedding/index.js +108 -0
  147. package/vendor/lancedb/dist/embedding/openai.d.ts +16 -0
  148. package/vendor/lancedb/dist/embedding/openai.js +81 -0
  149. package/vendor/lancedb/dist/embedding/registry.d.ts +94 -0
  150. package/vendor/lancedb/dist/embedding/registry.js +221 -0
  151. package/vendor/lancedb/dist/embedding/transformers.d.ts +36 -0
  152. package/vendor/lancedb/dist/embedding/transformers.js +110 -0
  153. package/vendor/lancedb/dist/header.d.ts +162 -0
  154. package/vendor/lancedb/dist/header.js +217 -0
  155. package/vendor/lancedb/dist/index.d.ts +246 -0
  156. package/vendor/lancedb/dist/index.js +176 -0
  157. package/vendor/lancedb/dist/indices.d.ts +721 -0
  158. package/vendor/lancedb/dist/indices.js +166 -0
  159. package/vendor/lancedb/dist/materialized_view.d.ts +69 -0
  160. package/vendor/lancedb/dist/materialized_view.js +112 -0
  161. package/vendor/lancedb/dist/merge.d.ts +104 -0
  162. package/vendor/lancedb/dist/merge.js +120 -0
  163. package/vendor/lancedb/dist/native.d.ts +1193 -0
  164. package/vendor/lancedb/dist/native.js +688 -0
  165. package/vendor/lancedb/dist/oauth.d.ts +66 -0
  166. package/vendor/lancedb/dist/oauth.js +15 -0
  167. package/vendor/lancedb/dist/otel.d.ts +26 -0
  168. package/vendor/lancedb/dist/otel.js +114 -0
  169. package/vendor/lancedb/dist/permutation.d.ts +143 -0
  170. package/vendor/lancedb/dist/permutation.js +184 -0
  171. package/vendor/lancedb/dist/query.d.ts +663 -0
  172. package/vendor/lancedb/dist/query.js +966 -0
  173. package/vendor/lancedb/dist/rerankers/index.d.ts +5 -0
  174. package/vendor/lancedb/dist/rerankers/index.js +19 -0
  175. package/vendor/lancedb/dist/rerankers/rrf.d.ts +14 -0
  176. package/vendor/lancedb/dist/rerankers/rrf.js +28 -0
  177. package/vendor/lancedb/dist/sanitize.d.ts +32 -0
  178. package/vendor/lancedb/dist/sanitize.js +544 -0
  179. package/vendor/lancedb/dist/scannable.d.ts +92 -0
  180. package/vendor/lancedb/dist/scannable.js +200 -0
  181. package/vendor/lancedb/dist/schema.d.ts +16 -0
  182. package/vendor/lancedb/dist/schema.js +387 -0
  183. package/vendor/lancedb/dist/table.d.ts +1069 -0
  184. package/vendor/lancedb/dist/table.js +498 -0
  185. package/vendor/lancedb/dist/util.d.ts +14 -0
  186. package/vendor/lancedb/dist/util.js +77 -0
  187. package/vendor/lancedb/license_header.txt +2 -0
  188. package/vendor/lancedb/package.json +56 -0
  189. package/vendor/transformers/LICENSE +202 -0
  190. package/vendor/transformers/dist/transformers.cjs +30844 -0
  191. package/vendor/transformers/dist/transformers.mjs +31404 -0
  192. package/vendor/transformers/package.json +55 -0
  193. package/vendor/transformers/types/backends/onnx.d.ts +30 -0
  194. package/vendor/transformers/types/configs.d.ts +85 -0
  195. package/vendor/transformers/types/env.d.ts +110 -0
  196. package/vendor/transformers/types/generation/configuration_utils.d.ts +320 -0
  197. package/vendor/transformers/types/generation/logits_process.d.ts +354 -0
  198. package/vendor/transformers/types/generation/logits_sampler.d.ts +51 -0
  199. package/vendor/transformers/types/generation/parameters.d.ts +47 -0
  200. package/vendor/transformers/types/generation/stopping_criteria.d.ts +81 -0
  201. package/vendor/transformers/types/generation/streamers.d.ts +81 -0
  202. package/vendor/transformers/types/models/whisper/common_whisper.d.ts +8 -0
  203. package/vendor/transformers/types/models/whisper/generation_whisper.d.ts +76 -0
  204. package/vendor/transformers/types/models.d.ts +3684 -0
  205. package/vendor/transformers/types/ops/registry.d.ts +11 -0
  206. package/vendor/transformers/types/pipelines.d.ts +2402 -0
  207. package/vendor/transformers/types/processors.d.ts +924 -0
  208. package/vendor/transformers/types/tokenizers.d.ts +990 -0
  209. package/vendor/transformers/types/transformers.d.ts +13 -0
  210. package/vendor/transformers/types/utils/audio.d.ts +130 -0
  211. package/vendor/transformers/types/utils/constants.d.ts +2 -0
  212. package/vendor/transformers/types/utils/core.d.ts +98 -0
  213. package/vendor/transformers/types/utils/data-structures.d.ts +236 -0
  214. package/vendor/transformers/types/utils/devices.d.ts +18 -0
  215. package/vendor/transformers/types/utils/dtypes.d.ts +19 -0
  216. package/vendor/transformers/types/utils/generic.d.ts +11 -0
  217. package/vendor/transformers/types/utils/hub.d.ts +152 -0
  218. package/vendor/transformers/types/utils/image.d.ts +119 -0
  219. package/vendor/transformers/types/utils/maths.d.ts +280 -0
  220. package/vendor/transformers/types/utils/tensor.d.ts +418 -0
@@ -0,0 +1,1145 @@
1
+ "use strict";
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ // SPDX-FileCopyrightText: Copyright The LanceDB Authors
4
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
5
+ if (k2 === undefined) k2 = k;
6
+ var desc = Object.getOwnPropertyDescriptor(m, k);
7
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
8
+ desc = { enumerable: true, get: function() { return m[k]; } };
9
+ }
10
+ Object.defineProperty(o, k2, desc);
11
+ }) : (function(o, m, k, k2) {
12
+ if (k2 === undefined) k2 = k;
13
+ o[k2] = m[k];
14
+ }));
15
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
16
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
17
+ };
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.MakeArrowTableOptions = exports.VectorColumnOptions = void 0;
20
+ exports.isMultiVector = isMultiVector;
21
+ exports.isIntoVector = isIntoVector;
22
+ exports.extractVectorBuffer = extractVectorBuffer;
23
+ exports.isArrowTable = isArrowTable;
24
+ exports.isNull = isNull;
25
+ exports.isInt = isInt;
26
+ exports.isFloat = isFloat;
27
+ exports.isBinary = isBinary;
28
+ exports.isLargeBinary = isLargeBinary;
29
+ exports.isUtf8 = isUtf8;
30
+ exports.isLargeUtf8 = isLargeUtf8;
31
+ exports.isBool = isBool;
32
+ exports.isDecimal = isDecimal;
33
+ exports.isDate = isDate;
34
+ exports.isTime = isTime;
35
+ exports.isTimestamp = isTimestamp;
36
+ exports.isInterval = isInterval;
37
+ exports.isDuration = isDuration;
38
+ exports.isList = isList;
39
+ exports.isStruct = isStruct;
40
+ exports.isUnion = isUnion;
41
+ exports.isFixedSizeBinary = isFixedSizeBinary;
42
+ exports.isFixedSizeList = isFixedSizeList;
43
+ exports.makeArrowTable = makeArrowTable;
44
+ exports.makeEmptyTable = makeEmptyTable;
45
+ exports.convertToTable = convertToTable;
46
+ exports.newVectorType = newVectorType;
47
+ exports.fromRecordsToBuffer = fromRecordsToBuffer;
48
+ exports.fromRecordsToStreamBuffer = fromRecordsToStreamBuffer;
49
+ exports.fromTableToBuffer = fromTableToBuffer;
50
+ exports.fromDataToBuffer = fromDataToBuffer;
51
+ exports.fromBufferToRecordBatch = fromBufferToRecordBatch;
52
+ exports.fromRecordBatchToBuffer = fromRecordBatchToBuffer;
53
+ exports.fromRecordBatchToStreamBuffer = fromRecordBatchToStreamBuffer;
54
+ exports.fromTableToStreamBuffer = fromTableToStreamBuffer;
55
+ exports.createEmptyTable = createEmptyTable;
56
+ exports.ensureNestedFieldsExist = ensureNestedFieldsExist;
57
+ exports.dataTypeToJson = dataTypeToJson;
58
+ const apache_arrow_1 = require("apache-arrow");
59
+ const arrow_type_1 = require("./arrow_type");
60
+ const registry_1 = require("./embedding/registry");
61
+ const sanitize_1 = require("./sanitize");
62
+ const schema_1 = require("./schema");
63
+ __exportStar(require("apache-arrow"), exports);
64
+ function isMultiVector(value) {
65
+ return Array.isArray(value) && isIntoVector(value[0]);
66
+ }
67
+ const float16ArrayCtor = globalThis
68
+ .Float16Array;
69
+ function isIntoVector(value) {
70
+ return (value instanceof Float32Array ||
71
+ value instanceof Float64Array ||
72
+ value instanceof Uint8Array ||
73
+ (float16ArrayCtor !== undefined && value instanceof float16ArrayCtor) ||
74
+ (Array.isArray(value) && !Array.isArray(value[0])));
75
+ }
76
+ /**
77
+ * Extract the underlying byte buffer and data type from a typed array
78
+ * for passing to the Rust NAPI layer without precision loss.
79
+ */
80
+ function extractVectorBuffer(vector) {
81
+ if (float16ArrayCtor !== undefined && vector instanceof float16ArrayCtor) {
82
+ return {
83
+ data: new Uint8Array(vector.buffer, vector.byteOffset, vector.byteLength),
84
+ dtype: "float16",
85
+ };
86
+ }
87
+ if (vector instanceof Float64Array) {
88
+ return {
89
+ data: new Uint8Array(vector.buffer, vector.byteOffset, vector.byteLength),
90
+ dtype: "float64",
91
+ };
92
+ }
93
+ if (vector instanceof Uint8Array && !(vector instanceof Float32Array)) {
94
+ return { data: vector, dtype: "uint8" };
95
+ }
96
+ return null;
97
+ }
98
+ function isArrowTable(value) {
99
+ if (value instanceof apache_arrow_1.Table)
100
+ return true;
101
+ return "schema" in value && "batches" in value;
102
+ }
103
+ function isNull(value) {
104
+ return value instanceof apache_arrow_1.Null || apache_arrow_1.DataType.isNull(value);
105
+ }
106
+ function isInt(value) {
107
+ return value instanceof apache_arrow_1.Int || apache_arrow_1.DataType.isInt(value);
108
+ }
109
+ function isFloat(value) {
110
+ return value instanceof apache_arrow_1.Float || apache_arrow_1.DataType.isFloat(value);
111
+ }
112
+ function isBinary(value) {
113
+ return value instanceof apache_arrow_1.Binary || apache_arrow_1.DataType.isBinary(value);
114
+ }
115
+ function isLargeBinary(value) {
116
+ return value instanceof apache_arrow_1.LargeBinary || apache_arrow_1.DataType.isLargeBinary(value);
117
+ }
118
+ function isUtf8(value) {
119
+ return value instanceof apache_arrow_1.Utf8 || apache_arrow_1.DataType.isUtf8(value);
120
+ }
121
+ function isLargeUtf8(value) {
122
+ return value instanceof apache_arrow_1.Utf8 || apache_arrow_1.DataType.isLargeUtf8(value);
123
+ }
124
+ function isBool(value) {
125
+ return value instanceof apache_arrow_1.Utf8 || apache_arrow_1.DataType.isBool(value);
126
+ }
127
+ function isDecimal(value) {
128
+ return value instanceof apache_arrow_1.Utf8 || apache_arrow_1.DataType.isDecimal(value);
129
+ }
130
+ function isDate(value) {
131
+ return value instanceof apache_arrow_1.Utf8 || apache_arrow_1.DataType.isDate(value);
132
+ }
133
+ function isTime(value) {
134
+ return value instanceof apache_arrow_1.Utf8 || apache_arrow_1.DataType.isTime(value);
135
+ }
136
+ function isTimestamp(value) {
137
+ return value instanceof apache_arrow_1.Utf8 || apache_arrow_1.DataType.isTimestamp(value);
138
+ }
139
+ function isInterval(value) {
140
+ return value instanceof apache_arrow_1.Utf8 || apache_arrow_1.DataType.isInterval(value);
141
+ }
142
+ function isDuration(value) {
143
+ return value instanceof apache_arrow_1.Utf8 || apache_arrow_1.DataType.isDuration(value);
144
+ }
145
+ function isList(value) {
146
+ return value instanceof apache_arrow_1.List || apache_arrow_1.DataType.isList(value);
147
+ }
148
+ function isStruct(value) {
149
+ return value instanceof apache_arrow_1.Struct || apache_arrow_1.DataType.isStruct(value);
150
+ }
151
+ function isUnion(value) {
152
+ return value instanceof apache_arrow_1.Struct || apache_arrow_1.DataType.isUnion(value);
153
+ }
154
+ function isFixedSizeBinary(value) {
155
+ return value instanceof apache_arrow_1.FixedSizeBinary || apache_arrow_1.DataType.isFixedSizeBinary(value);
156
+ }
157
+ function isFixedSizeList(value) {
158
+ return value instanceof apache_arrow_1.FixedSizeList || apache_arrow_1.DataType.isFixedSizeList(value);
159
+ }
160
+ /*
161
+ * Options to control how a column should be converted to a vector array
162
+ */
163
+ class VectorColumnOptions {
164
+ /** Vector column type. */
165
+ type = new apache_arrow_1.Float32();
166
+ constructor(values) {
167
+ Object.assign(this, values);
168
+ }
169
+ }
170
+ exports.VectorColumnOptions = VectorColumnOptions;
171
+ // biome-ignore lint/suspicious/noExplicitAny: skip
172
+ function vectorFromArray(data, type) {
173
+ // Workaround for: https://github.com/apache/arrow/issues/45862
174
+ // If FSL type with float
175
+ if (apache_arrow_1.DataType.isFixedSizeList(type) && apache_arrow_1.DataType.isFloat(type.valueType)) {
176
+ const extendedData = [...data, new Array(type.listSize).fill(0.0)];
177
+ const array = (0, apache_arrow_1.vectorFromArray)(extendedData, type);
178
+ return array.slice(0, data.length);
179
+ }
180
+ else if (type === undefined) {
181
+ return (0, apache_arrow_1.vectorFromArray)(data);
182
+ }
183
+ else {
184
+ return (0, apache_arrow_1.vectorFromArray)(data, type);
185
+ }
186
+ }
187
+ /** Options to control the makeArrowTable call. */
188
+ class MakeArrowTableOptions {
189
+ /*
190
+ * Schema of the data.
191
+ *
192
+ * If this is not provided then the data type will be inferred from the
193
+ * JS type. Integer numbers will become int64, floating point numbers
194
+ * will become float64 and arrays will become variable sized lists with
195
+ * the data type inferred from the first element in the array.
196
+ *
197
+ * The schema must be specified if there are no records (e.g. to make
198
+ * an empty table)
199
+ */
200
+ schema;
201
+ /*
202
+ * Mapping from vector column name to expected type
203
+ *
204
+ * Lance expects vector columns to be fixed size list arrays (i.e. tensors)
205
+ * However, `makeArrowTable` will not infer this by default (it creates
206
+ * variable size list arrays). This field can be used to indicate that a column
207
+ * should be treated as a vector column and converted to a fixed size list.
208
+ *
209
+ * The keys should be the names of the vector columns. The value specifies the
210
+ * expected data type of the vector columns.
211
+ *
212
+ * If `schema` is provided then this field is ignored.
213
+ *
214
+ * By default, the column named "vector" will be assumed to be a float32
215
+ * vector column.
216
+ */
217
+ vectorColumns = {
218
+ vector: new VectorColumnOptions(),
219
+ };
220
+ embeddings;
221
+ embeddingFunction;
222
+ /**
223
+ * If true then string columns will be encoded with dictionary encoding
224
+ *
225
+ * Set this to true if your string columns tend to repeat the same values
226
+ * often. For more precise control use the `schema` property to specify the
227
+ * data type for individual columns.
228
+ *
229
+ * If `schema` is provided then this property is ignored.
230
+ */
231
+ dictionaryEncodeStrings = false;
232
+ constructor(values) {
233
+ Object.assign(this, values);
234
+ }
235
+ }
236
+ exports.MakeArrowTableOptions = MakeArrowTableOptions;
237
+ /**
238
+ * An enhanced version of the apache-arrow makeTable function from Apache Arrow
239
+ * that supports nested fields and embeddings columns.
240
+ *
241
+ * (typically you do not need to call this function. It will be called automatically
242
+ * when creating a table or adding data to it)
243
+ *
244
+ * This function converts an array of Record<String, any> (row-major JS objects)
245
+ * to an Arrow Table (a columnar structure)
246
+ *
247
+ * If a schema is provided then it will be used to determine the resulting array
248
+ * types. Fields will also be reordered to fit the order defined by the schema.
249
+ *
250
+ * If a schema is not provided then the types will be inferred and the field order
251
+ * will be controlled by the order of properties in the first record. If a type
252
+ * is inferred it will always be nullable.
253
+ *
254
+ * If not all fields are found in the data, then a subset of the schema will be
255
+ * returned.
256
+ *
257
+ * If the input is empty then a schema must be provided to create an empty table.
258
+ *
259
+ * When a schema is not specified then data types will be inferred. The inference
260
+ * rules are as follows:
261
+ *
262
+ * - boolean => Bool
263
+ * - number => Float64
264
+ * - bigint => Int64
265
+ * - String => Utf8
266
+ * - Buffer => Binary
267
+ * - Record<String, any> => Struct
268
+ * - Array<any> => List
269
+ * @example
270
+ * ```ts
271
+ * import { fromTableToBuffer, makeArrowTable } from "../arrow";
272
+ * import { Field, FixedSizeList, Float16, Float32, Int32, Schema } from "apache-arrow";
273
+ *
274
+ * const schema = new Schema([
275
+ * new Field("a", new Int32()),
276
+ * new Field("b", new Float32()),
277
+ * new Field("c", new FixedSizeList(3, new Field("item", new Float16()))),
278
+ * ]);
279
+ * const table = makeArrowTable([
280
+ * { a: 1, b: 2, c: [1, 2, 3] },
281
+ * { a: 4, b: 5, c: [4, 5, 6] },
282
+ * { a: 7, b: 8, c: [7, 8, 9] },
283
+ * ], { schema });
284
+ * ```
285
+ *
286
+ * By default it assumes that the column named `vector` is a vector column
287
+ * and it will be converted into a fixed size list array of type float32.
288
+ * The `vectorColumns` option can be used to support other vector column
289
+ * names and data types.
290
+ *
291
+ * ```ts
292
+ * const schema = new Schema([
293
+ * new Field("a", new Float64()),
294
+ * new Field("b", new Float64()),
295
+ * new Field(
296
+ * "vector",
297
+ * new FixedSizeList(3, new Field("item", new Float32()))
298
+ * ),
299
+ * ]);
300
+ * const table = makeArrowTable([
301
+ * { a: 1, b: 2, vector: [1, 2, 3] },
302
+ * { a: 4, b: 5, vector: [4, 5, 6] },
303
+ * { a: 7, b: 8, vector: [7, 8, 9] },
304
+ * ]);
305
+ * assert.deepEqual(table.schema, schema);
306
+ * ```
307
+ *
308
+ * You can specify the vector column types and names using the options as well
309
+ *
310
+ * ```ts
311
+ * const schema = new Schema([
312
+ * new Field('a', new Float64()),
313
+ * new Field('b', new Float64()),
314
+ * new Field('vec1', new FixedSizeList(3, new Field('item', new Float16()))),
315
+ * new Field('vec2', new FixedSizeList(3, new Field('item', new Float16())))
316
+ * ]);
317
+ * const table = makeArrowTable([
318
+ * { a: 1, b: 2, vec1: [1, 2, 3], vec2: [2, 4, 6] },
319
+ * { a: 4, b: 5, vec1: [4, 5, 6], vec2: [8, 10, 12] },
320
+ * { a: 7, b: 8, vec1: [7, 8, 9], vec2: [14, 16, 18] }
321
+ * ], {
322
+ * vectorColumns: {
323
+ * vec1: { type: new Float16() },
324
+ * vec2: { type: new Float16() }
325
+ * }
326
+ * }
327
+ * assert.deepEqual(table.schema, schema)
328
+ * ```
329
+ */
330
+ function makeArrowTable(data, options, metadata) {
331
+ const opt = new MakeArrowTableOptions(options !== undefined ? options : {});
332
+ let schema = undefined;
333
+ if (opt.schema !== undefined && opt.schema !== null) {
334
+ schema = (0, sanitize_1.sanitizeSchema)(opt.schema);
335
+ schema = validateSchemaEmbeddings(schema, data, options?.embeddingFunction);
336
+ }
337
+ let schemaMetadata = schema?.metadata || new Map();
338
+ if (metadata !== undefined) {
339
+ schemaMetadata = new Map([...schemaMetadata, ...metadata]);
340
+ }
341
+ if (data.length === 0 &&
342
+ (options?.schema === undefined || options?.schema === null)) {
343
+ throw new Error("At least one record or a schema needs to be provided");
344
+ }
345
+ else if (data.length === 0) {
346
+ if (schema === undefined) {
347
+ throw new Error("A schema must be provided if data is empty");
348
+ }
349
+ else {
350
+ schema = new apache_arrow_1.Schema(schema.fields, schemaMetadata);
351
+ return new apache_arrow_1.Table(schema);
352
+ }
353
+ }
354
+ let inferredSchema = (0, schema_1.inferSchema)(data, schema, opt);
355
+ inferredSchema = new apache_arrow_1.Schema(inferredSchema.fields, schemaMetadata);
356
+ const finalColumns = {};
357
+ for (const field of inferredSchema.fields) {
358
+ finalColumns[field.name] = transposeData(data, field);
359
+ }
360
+ return new apache_arrow_1.Table(inferredSchema, finalColumns);
361
+ }
362
+ function isObject(value) {
363
+ return (typeof value === "object" &&
364
+ value !== null &&
365
+ !Array.isArray(value) &&
366
+ !(value instanceof RegExp) &&
367
+ !(value instanceof Date) &&
368
+ !(value instanceof Set) &&
369
+ !(value instanceof Map) &&
370
+ !(value instanceof Buffer) &&
371
+ !ArrayBuffer.isView(value));
372
+ }
373
+ function valueAtPath(datum, path) {
374
+ let current = datum;
375
+ for (const key of path) {
376
+ if (current == null) {
377
+ return null;
378
+ }
379
+ if (isObject(current) && (Object.hasOwn(current, key) || key in current)) {
380
+ current = current[key];
381
+ }
382
+ else {
383
+ return undefined;
384
+ }
385
+ }
386
+ return current;
387
+ }
388
+ function transposeData(data, field, path = []) {
389
+ const valuesPath = [...path, field.name];
390
+ const values = data.map((datum) => valueAtPath(datum, valuesPath));
391
+ if (field.type instanceof apache_arrow_1.Struct) {
392
+ const childFields = field.type.children;
393
+ const childVectors = childFields.map((child) => {
394
+ return transposeData(data, child, valuesPath);
395
+ });
396
+ const nullCount = values.filter((value) => value === null).length;
397
+ const structData = (0, apache_arrow_1.makeData)({
398
+ type: field.type,
399
+ length: values.length,
400
+ nullCount,
401
+ nullBitmap: nullCount > 0
402
+ ? apache_arrow_1.util.packBools(values.map((value) => value !== null))
403
+ : undefined,
404
+ children: childVectors,
405
+ });
406
+ return (0, apache_arrow_1.makeVector)(structData);
407
+ }
408
+ else {
409
+ return makeVector(values, field.type, undefined, field.nullable);
410
+ }
411
+ }
412
+ /**
413
+ * Create an empty Arrow table with the provided schema
414
+ */
415
+ function makeEmptyTable(schema, metadata) {
416
+ return makeArrowTable([], { schema }, metadata);
417
+ }
418
+ /**
419
+ * Helper function to convert Array<Array<any>> to a variable sized list array
420
+ */
421
+ // @ts-expect-error (Vector<unknown> is not assignable to Vector<any>)
422
+ function makeListVector(lists) {
423
+ if (lists.length === 0 || lists[0].length === 0) {
424
+ throw Error("Cannot infer list vector from empty array or empty list");
425
+ }
426
+ const sampleList = lists[0];
427
+ // biome-ignore lint/suspicious/noExplicitAny: skip
428
+ let inferredType;
429
+ try {
430
+ const sampleVector = makeVector(sampleList);
431
+ inferredType = sampleVector.type;
432
+ }
433
+ catch (error) {
434
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
435
+ throw Error(`Cannot infer list vector. Cannot infer inner type: ${error}`);
436
+ }
437
+ const listBuilder = (0, apache_arrow_1.makeBuilder)({
438
+ type: new apache_arrow_1.List(new apache_arrow_1.Field("item", inferredType, true)),
439
+ });
440
+ for (const list of lists) {
441
+ listBuilder.append(list);
442
+ }
443
+ return listBuilder.finish().toVector();
444
+ }
445
+ /** Helper function to convert an Array of JS values to an Arrow Vector */
446
+ function makeVector(values, type, stringAsDictionary, nullable) {
447
+ if (type !== undefined) {
448
+ // Convert undefined values to null for nullable fields
449
+ if (nullable) {
450
+ values = values.map((v) => (v === undefined ? null : v));
451
+ }
452
+ // workaround for: https://github.com/apache/arrow-js/issues/68
453
+ if (apache_arrow_1.DataType.isBool(type)) {
454
+ const hasNonNullValue = values.some((v) => v !== null && v !== undefined);
455
+ if (!hasNonNullValue) {
456
+ const nullBitmap = new Uint8Array(Math.ceil(values.length / 8));
457
+ const data = (0, apache_arrow_1.makeData)({
458
+ type: type,
459
+ length: values.length,
460
+ nullCount: values.length,
461
+ nullBitmap,
462
+ });
463
+ return (0, apache_arrow_1.makeVector)(data);
464
+ }
465
+ }
466
+ // No need for inference, let Arrow create it
467
+ if (type instanceof apache_arrow_1.Int) {
468
+ if (apache_arrow_1.DataType.isInt(type) && type.bitWidth === 64) {
469
+ // wrap in BigInt to avoid bug: https://github.com/apache/arrow/issues/40051
470
+ values = values.map((v) => {
471
+ if (v === null) {
472
+ return v;
473
+ }
474
+ else if (typeof v === "bigint") {
475
+ return v;
476
+ }
477
+ else if (typeof v === "number") {
478
+ return BigInt(v);
479
+ }
480
+ else {
481
+ return v;
482
+ }
483
+ });
484
+ }
485
+ else {
486
+ // Similarly, bigint isn't supported for 16 or 32-bit ints.
487
+ values = values.map((v) => {
488
+ if (typeof v == "bigint") {
489
+ return Number(v);
490
+ }
491
+ else {
492
+ return v;
493
+ }
494
+ });
495
+ }
496
+ }
497
+ return vectorFromArray(values, type);
498
+ }
499
+ if (values.length === 0) {
500
+ throw Error("makeVector requires at least one value or the type must be specfied");
501
+ }
502
+ const sampleValue = values.find((val) => val !== null && val !== undefined);
503
+ if (sampleValue === undefined) {
504
+ throw Error("makeVector cannot infer the type if all values are null or undefined");
505
+ }
506
+ if (ArrayBuffer.isView(sampleValue) && !(sampleValue instanceof DataView)) {
507
+ const info = (0, arrow_type_1.typedArrayToArrowType)(sampleValue);
508
+ if (info !== undefined) {
509
+ const fslType = new apache_arrow_1.FixedSizeList(info.length, new apache_arrow_1.Field("item", info.elementType, true));
510
+ return vectorFromArray(values, fslType);
511
+ }
512
+ }
513
+ if (Array.isArray(sampleValue)) {
514
+ // Default Arrow inference doesn't handle list types
515
+ return makeListVector(values);
516
+ }
517
+ else if (Buffer.isBuffer(sampleValue)) {
518
+ // Default Arrow inference doesn't handle Buffer
519
+ return vectorFromArray(values, new apache_arrow_1.Binary());
520
+ }
521
+ else if (!(stringAsDictionary ?? false) &&
522
+ (typeof sampleValue === "string" || sampleValue instanceof String)) {
523
+ // If the type is string then don't use Arrow's default inference unless dictionaries are requested
524
+ // because it will always use dictionary encoding for strings
525
+ return vectorFromArray(values, new apache_arrow_1.Utf8());
526
+ }
527
+ else {
528
+ // Convert a JS array of values to an arrow vector
529
+ return vectorFromArray(values);
530
+ }
531
+ }
532
+ /** Helper function to apply embeddings from metadata to an input table */
533
+ async function applyEmbeddingsFromMetadata(table, schema) {
534
+ const registry = (0, registry_1.getRegistry)();
535
+ const functions = await registry.parseFunctions(schema.metadata);
536
+ const columns = Object.fromEntries(table.schema.fields.map((field) => [
537
+ field.name,
538
+ table.getChild(field.name),
539
+ ]));
540
+ for (const functionEntry of functions.values()) {
541
+ const sourceColumn = columns[functionEntry.sourceColumn];
542
+ const destColumn = functionEntry.vectorColumn;
543
+ if (sourceColumn === undefined) {
544
+ throw new Error(`Cannot apply embedding function because the source column '${functionEntry.sourceColumn}' was not present in the data`);
545
+ }
546
+ // Check if destination column exists and handle accordingly
547
+ if (columns[destColumn] !== undefined) {
548
+ const existingColumn = columns[destColumn];
549
+ // If the column exists but is all null, we can fill it with embeddings
550
+ if (existingColumn.nullCount !== existingColumn.length) {
551
+ // Column has non-null values, skip embedding application
552
+ continue;
553
+ }
554
+ }
555
+ if (table.batches.length > 1) {
556
+ throw new Error("Internal error: `makeArrowTable` unexpectedly created a table with more than one batch");
557
+ }
558
+ const values = sourceColumn.toArray();
559
+ const vectors = await functionEntry.function.computeSourceEmbeddings(values);
560
+ if (vectors.length !== values.length) {
561
+ throw new Error("Embedding function did not return an embedding for each input element");
562
+ }
563
+ let destType;
564
+ const dtype = schema.fields.find((f) => f.name === destColumn).type;
565
+ if (isFixedSizeList(dtype)) {
566
+ destType = (0, sanitize_1.sanitizeType)(dtype);
567
+ }
568
+ else {
569
+ throw new Error("Expected FixedSizeList as datatype for vector field, instead got: " +
570
+ dtype);
571
+ }
572
+ const vector = makeVector(vectors, destType);
573
+ columns[destColumn] = vector;
574
+ }
575
+ // Add any missing columns from the schema as null vectors
576
+ for (const field of schema.fields) {
577
+ if (!(field.name in columns)) {
578
+ const nullValues = new Array(table.numRows).fill(null);
579
+ columns[field.name] = makeVector(nullValues, field.type, undefined, field.nullable);
580
+ }
581
+ }
582
+ const newTable = new apache_arrow_1.Table(columns);
583
+ return alignTable(newTable, schema);
584
+ }
585
+ /** Helper function to apply embeddings to an input table */
586
+ async function applyEmbeddings(table, embeddings, schema) {
587
+ if (schema !== undefined && schema !== null) {
588
+ schema = (0, sanitize_1.sanitizeSchema)(schema);
589
+ }
590
+ if (schema?.metadata.has("embedding_functions")) {
591
+ return applyEmbeddingsFromMetadata(table, schema);
592
+ }
593
+ else if (embeddings == null || embeddings === undefined) {
594
+ return table;
595
+ }
596
+ let schemaMetadata = schema?.metadata || new Map();
597
+ if (!(embeddings == null || embeddings === undefined)) {
598
+ const registry = (0, registry_1.getRegistry)();
599
+ const embeddingMetadata = registry.getTableMetadata([embeddings]);
600
+ schemaMetadata = new Map([...schemaMetadata, ...embeddingMetadata]);
601
+ }
602
+ // Convert from ArrowTable to Record<String, Vector>
603
+ const colEntries = [...Array(table.numCols).keys()].map((_, idx) => {
604
+ const name = table.schema.fields[idx].name;
605
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
606
+ const vec = table.getChildAt(idx);
607
+ return [name, vec];
608
+ });
609
+ const newColumns = Object.fromEntries(colEntries);
610
+ const sourceColumn = newColumns[embeddings.sourceColumn];
611
+ const destColumn = embeddings.vectorColumn ?? "vector";
612
+ const innerDestType = embeddings.function.embeddingDataType() ?? new apache_arrow_1.Float32();
613
+ if (sourceColumn === undefined) {
614
+ throw new Error(`Cannot apply embedding function because the source column '${embeddings.sourceColumn}' was not present in the data`);
615
+ }
616
+ if (table.numRows === 0) {
617
+ if (Object.prototype.hasOwnProperty.call(newColumns, destColumn)) {
618
+ // We have an empty table and it already has the embedding column so no work needs to be done
619
+ // Note: we don't return an error like we did below because this is a common occurrence. For example,
620
+ // if we call convertToTable with 0 records and a schema that includes the embedding
621
+ return table;
622
+ }
623
+ const dimensions = embeddings.function.ndims();
624
+ if (dimensions !== undefined) {
625
+ const destType = newVectorType(dimensions, innerDestType);
626
+ newColumns[destColumn] = makeVector([], destType);
627
+ }
628
+ else if (schema != null) {
629
+ const destField = schema.fields.find((f) => f.name === destColumn);
630
+ if (destField != null) {
631
+ newColumns[destColumn] = makeVector([], destField.type, undefined, destField.nullable);
632
+ }
633
+ else {
634
+ throw new Error(`Attempt to apply embeddings to an empty table failed because schema was missing embedding column '${destColumn}'`);
635
+ }
636
+ }
637
+ else {
638
+ throw new Error("Attempt to apply embeddings to an empty table when the embeddings function does not specify `embeddingDimension`");
639
+ }
640
+ }
641
+ else {
642
+ // Check if destination column exists and handle accordingly
643
+ if (Object.prototype.hasOwnProperty.call(newColumns, destColumn)) {
644
+ const existingColumn = newColumns[destColumn];
645
+ // If the column exists but is all null, we can fill it with embeddings
646
+ if (existingColumn.nullCount !== existingColumn.length) {
647
+ // Column has non-null values, skip embedding application and return table as-is
648
+ let newTable = new apache_arrow_1.Table(newColumns);
649
+ if (schema != null) {
650
+ newTable = alignTable(newTable, schema);
651
+ }
652
+ return new apache_arrow_1.Table(new apache_arrow_1.Schema(newTable.schema.fields, schemaMetadata), newTable.batches);
653
+ }
654
+ }
655
+ if (table.batches.length > 1) {
656
+ throw new Error("Internal error: `makeArrowTable` unexpectedly created a table with more than one batch");
657
+ }
658
+ const values = sourceColumn.toArray();
659
+ const vectors = await embeddings.function.computeSourceEmbeddings(values);
660
+ if (vectors.length !== values.length) {
661
+ throw new Error("Embedding function did not return an embedding for each input element");
662
+ }
663
+ const destType = newVectorType(vectors[0].length, innerDestType);
664
+ newColumns[destColumn] = makeVector(vectors, destType);
665
+ }
666
+ let newTable = new apache_arrow_1.Table(newColumns);
667
+ if (schema != null) {
668
+ if (schema.fields.find((f) => f.name === destColumn) === undefined) {
669
+ throw new Error(`When using embedding functions and specifying a schema the schema should include the embedding column but the column ${destColumn} was missing`);
670
+ }
671
+ newTable = alignTable(newTable, schema);
672
+ }
673
+ newTable = new apache_arrow_1.Table(new apache_arrow_1.Schema(newTable.schema.fields, schemaMetadata), newTable.batches);
674
+ return newTable;
675
+ }
676
+ /**
677
+ * Convert an Array of records into an Arrow Table, optionally applying an
678
+ * embeddings function to it.
679
+ *
680
+ * This function calls `makeArrowTable` first to create the Arrow Table.
681
+ * Any provided `makeTableOptions` (e.g. a schema) will be passed on to
682
+ * that call.
683
+ *
684
+ * The embedding function will be passed a column of values (based on the
685
+ * `sourceColumn` of the embedding function) and expects to receive back
686
+ * number[][] which will be converted into a fixed size list column. By
687
+ * default this will be a fixed size list of Float32 but that can be
688
+ * customized by the `embeddingDataType` property of the embedding function.
689
+ *
690
+ * If a schema is provided in `makeTableOptions` then it should include the
691
+ * embedding columns. If no schema is provded then embedding columns will
692
+ * be placed at the end of the table, after all of the input columns.
693
+ */
694
+ async function convertToTable(data, embeddings, makeTableOptions) {
695
+ let processedData = data;
696
+ // If we have a schema with embedding metadata, we need to preprocess the data
697
+ // to ensure all nested fields are present
698
+ if (makeTableOptions?.schema &&
699
+ makeTableOptions.schema.metadata?.has("embedding_functions")) {
700
+ processedData = ensureNestedFieldsExist(data, makeTableOptions.schema);
701
+ }
702
+ const table = makeArrowTable(processedData, makeTableOptions);
703
+ return await applyEmbeddings(table, embeddings, makeTableOptions?.schema);
704
+ }
705
+ /** Creates the Arrow Type for a Vector column with dimension `dim` */
706
+ function newVectorType(dim, innerType) {
707
+ // in Lance we always default to have the elements nullable, so we need to set it to true
708
+ // otherwise we often get schema mismatches because the stored data always has schema with nullable elements
709
+ const children = new apache_arrow_1.Field("item", (0, sanitize_1.sanitizeType)(innerType), true);
710
+ return new apache_arrow_1.FixedSizeList(dim, children);
711
+ }
712
+ /**
713
+ * Serialize an Array of records into a buffer using the Arrow IPC File serialization
714
+ *
715
+ * This function will call `convertToTable` and pass on `embeddings` and `schema`
716
+ *
717
+ * `schema` is required if data is empty
718
+ */
719
+ async function fromRecordsToBuffer(data, embeddings, schema) {
720
+ if (schema !== undefined && schema !== null) {
721
+ schema = (0, sanitize_1.sanitizeSchema)(schema);
722
+ }
723
+ const table = await convertToTable(data, embeddings, { schema });
724
+ const writer = apache_arrow_1.RecordBatchFileWriter.writeAll(table);
725
+ return Buffer.from(await writer.toUint8Array());
726
+ }
727
+ /**
728
+ * Serialize an Array of records into a buffer using the Arrow IPC Stream serialization
729
+ *
730
+ * This function will call `convertToTable` and pass on `embeddings` and `schema`
731
+ *
732
+ * `schema` is required if data is empty
733
+ */
734
+ async function fromRecordsToStreamBuffer(data, embeddings, schema) {
735
+ if (schema !== undefined && schema !== null) {
736
+ schema = (0, sanitize_1.sanitizeSchema)(schema);
737
+ }
738
+ const table = await convertToTable(data, embeddings, { schema });
739
+ const writer = apache_arrow_1.RecordBatchStreamWriter.writeAll(table);
740
+ return Buffer.from(await writer.toUint8Array());
741
+ }
742
+ /**
743
+ * Serialize an Arrow Table into a buffer using the Arrow IPC File serialization
744
+ *
745
+ * This function will apply `embeddings` to the table in a manner similar to
746
+ * `convertToTable`.
747
+ *
748
+ * `schema` is required if the table is empty
749
+ */
750
+ async function fromTableToBuffer(table, embeddings, schema) {
751
+ if (schema !== undefined && schema !== null) {
752
+ schema = (0, sanitize_1.sanitizeSchema)(schema);
753
+ }
754
+ const tableWithEmbeddings = await applyEmbeddings(table, embeddings, schema);
755
+ const writer = apache_arrow_1.RecordBatchFileWriter.writeAll(tableWithEmbeddings);
756
+ return Buffer.from(await writer.toUint8Array());
757
+ }
758
+ /**
759
+ * Serialize an Arrow Table into a buffer using the Arrow IPC File serialization
760
+ *
761
+ * This function will apply `embeddings` to the table in a manner similar to
762
+ * `convertToTable`.
763
+ *
764
+ * `schema` is required if the table is empty
765
+ */
766
+ async function fromDataToBuffer(data, embeddings, schema) {
767
+ if (schema !== undefined && schema !== null) {
768
+ schema = (0, sanitize_1.sanitizeSchema)(schema);
769
+ }
770
+ if (isArrowTable(data)) {
771
+ const table = (0, sanitize_1.sanitizeTable)(data);
772
+ // If we have a schema with embedding functions, we need to ensure all columns exist
773
+ // before applying embeddings, since applyEmbeddingsFromMetadata expects all columns
774
+ // to be present in the table
775
+ if (schema && schema.metadata?.has("embedding_functions")) {
776
+ const alignedTable = alignTableToSchema(table, schema);
777
+ return fromTableToBuffer(alignedTable, embeddings, schema);
778
+ }
779
+ else {
780
+ return fromTableToBuffer(table, embeddings, schema);
781
+ }
782
+ }
783
+ else {
784
+ const table = await convertToTable(data, embeddings, { schema });
785
+ return fromTableToBuffer(table);
786
+ }
787
+ }
788
+ /**
789
+ * Read a single record batch from a buffer.
790
+ *
791
+ * Returns null if the buffer does not contain a record batch
792
+ */
793
+ async function fromBufferToRecordBatch(data) {
794
+ const iter = await apache_arrow_1.RecordBatchFileReader.readAll(Buffer.from(data)).next()
795
+ .value;
796
+ const recordBatch = iter?.next().value;
797
+ return recordBatch || null;
798
+ }
799
+ /**
800
+ * Create a buffer containing a single record batch
801
+ */
802
+ async function fromRecordBatchToBuffer(batch) {
803
+ const writer = new apache_arrow_1.RecordBatchFileWriter().writeAll([batch]);
804
+ return Buffer.from(await writer.toUint8Array());
805
+ }
806
+ /**
807
+ * Create a buffer containing a single record batch using the Arrow IPC Stream
808
+ * serialization. Each call produces a self-contained Stream message (schema +
809
+ * batch + EOS) suitable for incremental decode by `arrow_ipc::reader::StreamReader`.
810
+ */
811
+ async function fromRecordBatchToStreamBuffer(batch) {
812
+ const writer = apache_arrow_1.RecordBatchStreamWriter.writeAll([batch]);
813
+ return Buffer.from(await writer.toUint8Array());
814
+ }
815
+ /**
816
+ * Serialize an Arrow Table into a buffer using the Arrow IPC Stream serialization
817
+ *
818
+ * This function will apply `embeddings` to the table in a manner similar to
819
+ * `convertToTable`.
820
+ *
821
+ * `schema` is required if the table is empty
822
+ */
823
+ async function fromTableToStreamBuffer(table, embeddings, schema) {
824
+ const tableWithEmbeddings = await applyEmbeddings(table, embeddings, schema);
825
+ const writer = apache_arrow_1.RecordBatchStreamWriter.writeAll(tableWithEmbeddings);
826
+ return Buffer.from(await writer.toUint8Array());
827
+ }
828
+ /**
829
+ * Reorder the columns in `batch` so that they agree with the field order in `schema`
830
+ */
831
+ function alignBatch(batch, schema) {
832
+ const alignedChildren = [];
833
+ for (const field of schema.fields) {
834
+ const indexInBatch = batch.schema.fields?.findIndex((f) => f.name === field.name);
835
+ if (indexInBatch < 0) {
836
+ throw new Error(`The column ${field.name} was not found in the Arrow Table`);
837
+ }
838
+ alignedChildren.push(batch.data.children[indexInBatch]);
839
+ }
840
+ const newData = (0, apache_arrow_1.makeData)({
841
+ type: new apache_arrow_1.Struct(schema.fields),
842
+ length: batch.numRows,
843
+ nullCount: batch.nullCount,
844
+ children: alignedChildren,
845
+ });
846
+ return new apache_arrow_1.RecordBatch(schema, newData);
847
+ }
848
+ /**
849
+ * Reorder the columns in `table` so that they agree with the field order in `schema`
850
+ */
851
+ function alignTable(table, schema) {
852
+ const alignedBatches = table.batches.map((batch) => alignBatch(batch, schema));
853
+ return new apache_arrow_1.Table(schema, alignedBatches);
854
+ }
855
+ /**
856
+ * Create an empty table with the given schema
857
+ */
858
+ function createEmptyTable(schema) {
859
+ return new apache_arrow_1.Table((0, sanitize_1.sanitizeSchema)(schema));
860
+ }
861
+ function validateSchemaEmbeddings(schema, data, embeddings) {
862
+ const fields = [];
863
+ const missingEmbeddingFields = [];
864
+ // First we check if the field is a `FixedSizeList`
865
+ // Then we check if the data contains the field
866
+ // if it does not, we add it to the list of missing embedding fields
867
+ // Finally, we check if those missing embedding fields are `this._embeddings`
868
+ // if they are not, we throw an error
869
+ for (let field of schema.fields) {
870
+ if (isFixedSizeList(field.type)) {
871
+ field = (0, sanitize_1.sanitizeField)(field);
872
+ if (data.length !== 0 && data?.[0]?.[field.name] === undefined) {
873
+ // Check if there's an embedding function registered for this field
874
+ let hasEmbeddingFunction = false;
875
+ // Check schema metadata for embedding functions
876
+ if (schema.metadata.has("embedding_functions")) {
877
+ const entries = (0, registry_1.parseEmbeddingMetadata)(schema.metadata.get("embedding_functions"));
878
+ if (entries.some((f) => f.vectorColumn === field.name)) {
879
+ hasEmbeddingFunction = true;
880
+ }
881
+ }
882
+ // Check passed embedding function parameter
883
+ if (embeddings && embeddings.vectorColumn === field.name) {
884
+ hasEmbeddingFunction = true;
885
+ }
886
+ // If the field is nullable AND there's no embedding function, allow undefined/omitted values
887
+ if (field.nullable && !hasEmbeddingFunction) {
888
+ fields.push(field);
889
+ }
890
+ else {
891
+ // Either not nullable OR has embedding function - require explicit values
892
+ if (hasEmbeddingFunction) {
893
+ // Don't add to missingEmbeddingFields since this is expected to be filled by embedding function
894
+ fields.push(field);
895
+ }
896
+ else {
897
+ missingEmbeddingFields.push(field);
898
+ }
899
+ }
900
+ }
901
+ else {
902
+ fields.push(field);
903
+ }
904
+ }
905
+ else {
906
+ fields.push(field);
907
+ }
908
+ }
909
+ if (missingEmbeddingFields.length > 0 && embeddings === undefined) {
910
+ throw new Error(`Table has embeddings: "${missingEmbeddingFields
911
+ .map((f) => f.name)
912
+ .join(",")}", but no embedding function was provided`);
913
+ }
914
+ return new apache_arrow_1.Schema(fields, schema.metadata);
915
+ }
916
+ /**
917
+ * Ensures that all nested fields defined in the schema exist in the data,
918
+ * filling missing fields with null values.
919
+ */
920
+ function ensureNestedFieldsExist(data, schema) {
921
+ return data.map((row) => {
922
+ const completeRow = {};
923
+ for (const field of schema.fields) {
924
+ if (field.name in row) {
925
+ if (field.type.constructor.name === "Struct" &&
926
+ row[field.name] !== null &&
927
+ row[field.name] !== undefined) {
928
+ // Handle nested struct
929
+ const nestedValue = row[field.name];
930
+ completeRow[field.name] = ensureStructFieldsExist(nestedValue, field.type);
931
+ }
932
+ else {
933
+ // Non-struct field or null struct value
934
+ completeRow[field.name] = row[field.name];
935
+ }
936
+ }
937
+ else {
938
+ // Keep a missing struct valid while filling each of its children with
939
+ // null. This is distinct from an explicitly null struct value.
940
+ completeRow[field.name] =
941
+ field.type.constructor.name === "Struct"
942
+ ? ensureStructFieldsExist({}, field.type)
943
+ : null;
944
+ }
945
+ }
946
+ return completeRow;
947
+ });
948
+ }
949
+ /**
950
+ * Recursively ensures that all fields in a struct type exist in the data,
951
+ * filling missing fields with null values.
952
+ */
953
+ function ensureStructFieldsExist(data, structType) {
954
+ const completeStruct = {};
955
+ for (const childField of structType.children) {
956
+ if (childField.name in data) {
957
+ if (childField.type.constructor.name === "Struct" &&
958
+ data[childField.name] !== null &&
959
+ data[childField.name] !== undefined) {
960
+ // Recursively handle nested struct
961
+ completeStruct[childField.name] = ensureStructFieldsExist(data[childField.name], childField.type);
962
+ }
963
+ else {
964
+ // Non-struct field or null struct value
965
+ completeStruct[childField.name] = data[childField.name];
966
+ }
967
+ }
968
+ else {
969
+ // Keep a missing struct valid while filling each of its children with
970
+ // null. This is distinct from an explicitly null struct value.
971
+ completeStruct[childField.name] =
972
+ childField.type.constructor.name === "Struct"
973
+ ? ensureStructFieldsExist({}, childField.type)
974
+ : null;
975
+ }
976
+ }
977
+ return completeStruct;
978
+ }
979
+ // Matches format of https://github.com/lancedb/lance/blob/main/rust/lance/src/arrow/json.rs
980
+ function dataTypeToJson(dataType) {
981
+ switch (dataType.typeId) {
982
+ // For primitives, matches https://github.com/lancedb/lance/blob/e12bb9eff2a52f753668d4b62c52e4d72b10d294/rust/lance-core/src/datatypes.rs#L185
983
+ case apache_arrow_1.Type.Null:
984
+ return { type: "null" };
985
+ case apache_arrow_1.Type.Bool:
986
+ return { type: "bool" };
987
+ case apache_arrow_1.Type.Int8:
988
+ return { type: "int8" };
989
+ case apache_arrow_1.Type.Int16:
990
+ return { type: "int16" };
991
+ case apache_arrow_1.Type.Int32:
992
+ return { type: "int32" };
993
+ case apache_arrow_1.Type.Int64:
994
+ return { type: "int64" };
995
+ case apache_arrow_1.Type.Uint8:
996
+ return { type: "uint8" };
997
+ case apache_arrow_1.Type.Uint16:
998
+ return { type: "uint16" };
999
+ case apache_arrow_1.Type.Uint32:
1000
+ return { type: "uint32" };
1001
+ case apache_arrow_1.Type.Uint64:
1002
+ return { type: "uint64" };
1003
+ case apache_arrow_1.Type.Int: {
1004
+ const bitWidth = dataType.bitWidth;
1005
+ const signed = dataType.isSigned;
1006
+ const prefix = signed ? "" : "u";
1007
+ return { type: `${prefix}int${bitWidth}` };
1008
+ }
1009
+ case apache_arrow_1.Type.Float: {
1010
+ switch (dataType.precision) {
1011
+ case apache_arrow_1.Precision.HALF:
1012
+ return { type: "halffloat" };
1013
+ case apache_arrow_1.Precision.SINGLE:
1014
+ return { type: "float" };
1015
+ case apache_arrow_1.Precision.DOUBLE:
1016
+ return { type: "double" };
1017
+ }
1018
+ throw Error("Unsupported float precision");
1019
+ }
1020
+ case apache_arrow_1.Type.Float16:
1021
+ return { type: "halffloat" };
1022
+ case apache_arrow_1.Type.Float32:
1023
+ return { type: "float" };
1024
+ case apache_arrow_1.Type.Float64:
1025
+ return { type: "double" };
1026
+ case apache_arrow_1.Type.Utf8:
1027
+ return { type: "string" };
1028
+ case apache_arrow_1.Type.Binary:
1029
+ return { type: "binary" };
1030
+ case apache_arrow_1.Type.LargeUtf8:
1031
+ return { type: "large_string" };
1032
+ case apache_arrow_1.Type.LargeBinary:
1033
+ return { type: "large_binary" };
1034
+ case apache_arrow_1.Type.List:
1035
+ return {
1036
+ type: "list",
1037
+ fields: [fieldToJson(dataType.children[0])],
1038
+ };
1039
+ case apache_arrow_1.Type.FixedSizeList: {
1040
+ const fixedSizeList = dataType;
1041
+ return {
1042
+ type: "fixed_size_list",
1043
+ fields: [fieldToJson(fixedSizeList.children[0])],
1044
+ length: fixedSizeList.listSize,
1045
+ };
1046
+ }
1047
+ case apache_arrow_1.Type.Struct:
1048
+ return {
1049
+ type: "struct",
1050
+ fields: dataType.children.map(fieldToJson),
1051
+ };
1052
+ case apache_arrow_1.Type.Date: {
1053
+ const unit = dataType.unit;
1054
+ return {
1055
+ type: unit === apache_arrow_1.DateUnit.DAY ? "date32:day" : "date64:ms",
1056
+ };
1057
+ }
1058
+ case apache_arrow_1.Type.Timestamp: {
1059
+ const timestamp = dataType;
1060
+ const timezone = timestamp.timezone || "-";
1061
+ return {
1062
+ type: `timestamp:${timestamp.unit}:${timezone}`,
1063
+ };
1064
+ }
1065
+ case apache_arrow_1.Type.Decimal: {
1066
+ const decimal = dataType;
1067
+ return {
1068
+ type: `decimal:${decimal.bitWidth}:${decimal.precision}:${decimal.scale}`,
1069
+ };
1070
+ }
1071
+ case apache_arrow_1.Type.Duration: {
1072
+ const duration = dataType;
1073
+ return { type: `duration:${duration.unit}` };
1074
+ }
1075
+ case apache_arrow_1.Type.FixedSizeBinary: {
1076
+ const byteWidth = dataType.byteWidth;
1077
+ return { type: `fixed_size_binary:${byteWidth}` };
1078
+ }
1079
+ case apache_arrow_1.Type.Dictionary: {
1080
+ const dict = dataType;
1081
+ const indexType = dataTypeToJson(dict.indices);
1082
+ const valueType = dataTypeToJson(dict.valueType);
1083
+ return {
1084
+ type: `dict:${valueType.type}:${indexType.type}:false`,
1085
+ };
1086
+ }
1087
+ }
1088
+ throw new Error("Unsupported data type");
1089
+ }
1090
+ function fieldToJson(field) {
1091
+ return {
1092
+ name: field.name,
1093
+ type: dataTypeToJson(field.type),
1094
+ nullable: field.nullable,
1095
+ metadata: field.metadata,
1096
+ };
1097
+ }
1098
+ function alignTableToSchema(table, targetSchema) {
1099
+ const existingColumns = new Map();
1100
+ // Map existing columns
1101
+ for (const field of table.schema.fields) {
1102
+ existingColumns.set(field.name, table.getChild(field.name));
1103
+ }
1104
+ // Create vectors for all fields in target schema
1105
+ const alignedColumns = {};
1106
+ for (const field of targetSchema.fields) {
1107
+ if (existingColumns.has(field.name)) {
1108
+ // Column exists, use it
1109
+ alignedColumns[field.name] = existingColumns.get(field.name);
1110
+ }
1111
+ else {
1112
+ // Column missing, create null vector
1113
+ alignedColumns[field.name] = createNullVector(field, table.numRows);
1114
+ }
1115
+ }
1116
+ // Create new table with aligned schema and columns
1117
+ return new apache_arrow_1.Table(targetSchema, alignedColumns);
1118
+ }
1119
+ function createNullVector(field, numRows) {
1120
+ if (field.type.constructor.name === "Struct") {
1121
+ // For struct types, create a struct with null fields
1122
+ const structType = field.type;
1123
+ const childVectors = structType.children.map((childField) => createNullVector(childField, numRows));
1124
+ // Create struct data
1125
+ const structData = (0, apache_arrow_1.makeData)({
1126
+ type: structType,
1127
+ length: numRows,
1128
+ nullCount: 0,
1129
+ children: childVectors.map((v) => v.data[0]),
1130
+ });
1131
+ return (0, apache_arrow_1.makeVector)(structData);
1132
+ }
1133
+ else {
1134
+ // For other types, create a vector of nulls
1135
+ const nullBitmap = new Uint8Array(Math.ceil(numRows / 8));
1136
+ // All bits are 0, meaning all values are null
1137
+ const data = (0, apache_arrow_1.makeData)({
1138
+ type: field.type,
1139
+ length: numRows,
1140
+ nullCount: numRows,
1141
+ nullBitmap,
1142
+ });
1143
+ return (0, apache_arrow_1.makeVector)(data);
1144
+ }
1145
+ }