@modernrelay/orbit-data 0.19.0 → 0.20.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +157 -0
- package/dist/arrow.d.ts +3 -1
- package/dist/arrow.js +8 -6
- package/dist/arrow.js.map +1 -1
- package/dist/{chunk-XXC2CUXZ.js → chunk-5RVIGNTM.js} +438 -191
- package/dist/chunk-5RVIGNTM.js.map +1 -0
- package/dist/index.d.ts +22 -3
- package/dist/index.js +67 -18
- package/dist/index.js.map +1 -1
- package/dist/parquet.d.ts +3 -1
- package/dist/parquet.js +13 -7
- package/dist/parquet.js.map +1 -1
- package/dist/{types-D4HC4ECy.d.ts → types-BABAI5c3.d.ts} +29 -8
- package/package.json +2 -2
- package/dist/chunk-XXC2CUXZ.js.map +0 -1
package/README.md
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
# @modernrelay/orbit-data
|
|
2
|
+
|
|
3
|
+
Prepare supplied rows, CSV, JSON, Arrow, or Parquet for Orbit. This package does
|
|
4
|
+
not fetch URLs or touch the DOM. The root entry includes rows/CSV/JSON; optional
|
|
5
|
+
Arrow and Parquet parsers stay in their own entry points.
|
|
6
|
+
|
|
7
|
+
## Import a graph
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { prepareGraphData } from '@modernrelay/orbit-data';
|
|
11
|
+
|
|
12
|
+
const controller = new AbortController();
|
|
13
|
+
const prepared = await prepareGraphData(
|
|
14
|
+
{ nodes: nodeFile, edges: edgeFile }, // Blob/File, ArrayBuffer, or async byte streams
|
|
15
|
+
{
|
|
16
|
+
nodes: { id: 'person_id', includeFields: ['name', 'team'] },
|
|
17
|
+
edges: { id: 'relationship_id', source: 'from', target: 'to' },
|
|
18
|
+
},
|
|
19
|
+
{
|
|
20
|
+
datasetKey: 'relationships',
|
|
21
|
+
sourceRevision: 'upload-1', // change when the data changes
|
|
22
|
+
format: 'csv',
|
|
23
|
+
signal: controller.signal,
|
|
24
|
+
maxBytes: 128 * 1024 * 1024,
|
|
25
|
+
maxNodes: 100_000,
|
|
26
|
+
maxEdges: 250_000,
|
|
27
|
+
onProgress: ({ phase, bytes, nodes, edges }) => {
|
|
28
|
+
console.log(phase, bytes, nodes, edges);
|
|
29
|
+
},
|
|
30
|
+
},
|
|
31
|
+
);
|
|
32
|
+
// Pass prepared.snapshot to <Graph data={...}> or instance.applyHostUpdate.
|
|
33
|
+
// prepared.summaries contains column profiles; mappingFingerprint identifies the mapping.
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Use `{ edges, deriveNodes: true }` when only an edge table exists. Node IDs are
|
|
37
|
+
derived in first endpoint occurrence order. Separate node/edge arrays and async
|
|
38
|
+
row iterables use the same mappings with `format: 'rows'`. A JSON byte source uses
|
|
39
|
+
`{ document }`, `format: 'json'`, and `mapping.documentPaths: { nodes: 'graph.nodes',
|
|
40
|
+
edges: 'graph.edges' }`.
|
|
41
|
+
|
|
42
|
+
Identity columns remain strings in CSV, preserving IDs such as `001`. Other
|
|
43
|
+
CSV columns infer numeric values from the first 1,000 records; empty cells are
|
|
44
|
+
absent. Explicit `includeFields` is an exact attribute allowlist; by default,
|
|
45
|
+
all non-identity columns become attributes. Missing IDs and invalid mappings
|
|
46
|
+
reject with row/column context. Duplicate IDs and dangling endpoints in object
|
|
47
|
+
snapshots remain core's validation responsibility.
|
|
48
|
+
|
|
49
|
+
For Arrow install `apache-arrow` and import `prepareArrowGraphData` from
|
|
50
|
+
`@modernrelay/orbit-data/arrow`. It accepts Arrow tables or IPC bytes. For Parquet
|
|
51
|
+
install `hyparquet` and import `prepareParquetGraphData` from
|
|
52
|
+
`@modernrelay/orbit-data/parquet`; each node/edge source is a file's bytes. Both
|
|
53
|
+
accept the same mapping and controls, without a `format` option.
|
|
54
|
+
|
|
55
|
+
## Preview before choosing columns
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
import { previewCsv } from '@modernrelay/orbit-data';
|
|
59
|
+
|
|
60
|
+
const preview = await previewCsv(file, {
|
|
61
|
+
signal: controller.signal,
|
|
62
|
+
maxRows: 5, // default
|
|
63
|
+
maxBytes: 256 * 1024, // default examined-byte budget
|
|
64
|
+
});
|
|
65
|
+
// preview.columns -> mapping selectors
|
|
66
|
+
// preview.rows -> raw strings, including quoted newlines and leading-zero IDs
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Preview uses the same CSV record parser and closes its iterator once the sample
|
|
70
|
+
is ready. `truncated: true` means the sample cap was reached; it does not inspect
|
|
71
|
+
another row to determine whether the file ends there. A record that cannot be
|
|
72
|
+
completed within the byte budget rejects. Bytes after the sample are not
|
|
73
|
+
validated. Reopen single-use streams for the actual preparation.
|
|
74
|
+
|
|
75
|
+
## Limits, progress, and cancellation
|
|
76
|
+
|
|
77
|
+
- Limits are optional positive safe integers; omitting them preserves the
|
|
78
|
+
unrestricted default. `maxBytes` counts supplied byte chunks across **both**
|
|
79
|
+
inputs, including headers. Row objects and existing Arrow tables have no wire
|
|
80
|
+
bytes and report zero. `maxNodes`/`maxEdges` count admitted rows before core
|
|
81
|
+
validation; duplicates count, while derived nodes count unique endpoint IDs.
|
|
82
|
+
- Limits reject with a `RangeError` naming the cap. They do not publish partial
|
|
83
|
+
graphs. Byte limits describe input size, **not** a JavaScript heap limit:
|
|
84
|
+
JSON parsing and Parquet decompression can require additional memory.
|
|
85
|
+
- Progress reports cumulative `{ phase, bytes, nodes, edges }`, at most once per
|
|
86
|
+
100 ms plus a final `complete` event. Phases are `reading`, `preparing`, and
|
|
87
|
+
`complete`; not every phase must produce a callback on a short load.
|
|
88
|
+
- Preparation yields tasks during row processing so browser input, cancellation,
|
|
89
|
+
and progress painting can run. Cancellation rejects with `AbortError`, including
|
|
90
|
+
cancellation during Parquet decoding. Synchronous parser calls cannot be
|
|
91
|
+
interrupted mid-call; cancellation is checked immediately afterward. Stalled
|
|
92
|
+
asynchronous reads stop being awaited, and their iterator is asked to close;
|
|
93
|
+
an uncooperative producer may finish its own pending I/O later.
|
|
94
|
+
|
|
95
|
+
## Opt-in columnar output
|
|
96
|
+
|
|
97
|
+
```ts
|
|
98
|
+
const prepared = await prepareGraphData(input, mapping, {
|
|
99
|
+
datasetKey: 'relationships', sourceRevision: 'upload-1', output: 'columnar',
|
|
100
|
+
}); // PreparedColumnarGraph; snapshot is ColumnarGraphSnapshot
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
All five formats support columnar output. The builder writes attribute columns
|
|
104
|
+
without retaining object graph nodes/edges. Strings use dictionaries, numbers
|
|
105
|
+
use Float64 arrays, and booleans use byte arrays. Missing, undefined, null, and
|
|
106
|
+
non-finite numeric cells become explicit null bits; an all-null column uses a
|
|
107
|
+
nullable Float64 array. Values keep their primitive type: a mixed string/number
|
|
108
|
+
column is an error. Summaries and mapping fingerprints match the object lane.
|
|
109
|
+
|
|
110
|
+
Nested arrays/objects, bigint attributes in raw row inputs, and `__proto__`
|
|
111
|
+
attributes reject with a remedy to use `output: 'object'`. Arrow/Parquet integer
|
|
112
|
+
normalization still applies before column construction. Unknown endpoints also
|
|
113
|
+
reject because typed endpoint indices cannot represent them. Supply the missing
|
|
114
|
+
nodes, derive nodes, or use the default object path for core's dangling-edge
|
|
115
|
+
diagnostics. Synthesized edge IDs use the same canonical helper as core.
|
|
116
|
+
|
|
117
|
+
Buffers and dictionaries are newly allocated. Inputs are never modified or
|
|
118
|
+
detached; snapshots use `bufferOwnership: 'borrowed'` for repeatable admission.
|
|
119
|
+
Callers may explicitly choose transfer ownership when handing a result to core.
|
|
120
|
+
Core currently materializes columnar rows during acceptance, so a smaller
|
|
121
|
+
prepared result does not imply a smaller final running graph or faster rendering.
|
|
122
|
+
|
|
123
|
+
## Save and reuse object artifacts
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
import { serializePrepared, loadPrepared } from '@modernrelay/orbit-data';
|
|
127
|
+
|
|
128
|
+
const bytes = serializePrepared(preparedObject);
|
|
129
|
+
const restored = loadPrepared(bytes); // validates the v1 object artifact
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
The default object API and version-1 artifact format are unchanged. Columnar
|
|
133
|
+
outputs are deliberately not accepted by the v1 serializer; keep their typed
|
|
134
|
+
buffers in memory or prepare object output when an existing JSON artifact is
|
|
135
|
+
required.
|
|
136
|
+
|
|
137
|
+
## Measure preparation
|
|
138
|
+
|
|
139
|
+
From the repository root run `node scripts/bench-data-preparation.mjs`. It runs
|
|
140
|
+
three fresh processes for each output with identical 100K-node/250K-edge row
|
|
141
|
+
streams and reports elapsed time, process peak RSS, and retained heap plus typed
|
|
142
|
+
buffers after GC. These are CPU preparation measurements, not GPU qualification.
|
|
143
|
+
The report explicitly evaluates whether columnar is faster and whether its
|
|
144
|
+
retained memory is lower; neither result is assumed.
|
|
145
|
+
|
|
146
|
+
One [recorded run](benchmarks/preparation-node24-darwin-arm64.json) on Node
|
|
147
|
+
24.15.0/macOS arm64 measured these medians across three fresh processes:
|
|
148
|
+
|
|
149
|
+
| Metric | Object | Columnar |
|
|
150
|
+
|---|---:|---:|
|
|
151
|
+
| Preparation | 628 ms | 702 ms |
|
|
152
|
+
| Retained heap + typed buffers | 70.2 MiB | 18.5 MiB |
|
|
153
|
+
| Process peak RSS | 277.0 MiB | 281.9 MiB |
|
|
154
|
+
|
|
155
|
+
Retained result memory was about 74% lower, but preparation was slower and peak
|
|
156
|
+
RSS did not improve. Timing varied (columnar 691–914 ms), so these are observations
|
|
157
|
+
for this synthetic workload, not speed guarantees or end-to-end graph benchmarks.
|
package/dist/arrow.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { GraphByteSource, GraphColumnMapping, GraphPrepareOptions, PreparedGraph } from './index.js';
|
|
1
|
+
import { GraphByteSource, GraphColumnMapping, GraphPrepareColumnarOptions, PreparedColumnarGraph, GraphPrepareOptions, PreparedGraph, GraphPrepareAnyOptions } from './index.js';
|
|
2
2
|
import '@modernrelay/orbit-core';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -44,7 +44,9 @@ type ArrowGraphPrepareInput = {
|
|
|
44
44
|
declare const _internals: {
|
|
45
45
|
importArrow: () => Promise<unknown>;
|
|
46
46
|
};
|
|
47
|
+
declare function prepareArrowGraphData<N = Record<string, unknown>, E = Record<string, unknown>>(input: ArrowGraphPrepareInput, mapping: GraphColumnMapping, options: Omit<GraphPrepareColumnarOptions, 'format'>): Promise<PreparedColumnarGraph<N, E>>;
|
|
47
48
|
declare function prepareArrowGraphData<N = Record<string, unknown>, E = Record<string, unknown>>(input: ArrowGraphPrepareInput, mapping: GraphColumnMapping, options: Omit<GraphPrepareOptions, 'format'>): Promise<PreparedGraph<N, E>>;
|
|
49
|
+
declare function prepareArrowGraphData<N = Record<string, unknown>, E = Record<string, unknown>>(input: ArrowGraphPrepareInput, mapping: GraphColumnMapping, options: Omit<GraphPrepareAnyOptions, 'format'>): Promise<PreparedGraph<N, E> | PreparedColumnarGraph<N, E>>;
|
|
48
50
|
|
|
49
51
|
export { _internals, prepareArrowGraphData };
|
|
50
52
|
export type { ArrowGraphPrepareInput, ArrowGraphSource, ArrowTableLike };
|
package/dist/arrow.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { normalizeJsonSafeValue } from './chunk-VRRKGDQJ.js';
|
|
2
|
-
import { throwIfAborted, buildPrepared, collectBytes, EMPTY_ROW_TABLE } from './chunk-
|
|
2
|
+
import { PreparationControl, throwIfAborted, buildPrepared, collectBytes, EMPTY_ROW_TABLE } from './chunk-5RVIGNTM.js';
|
|
3
3
|
|
|
4
4
|
// src/arrow.ts
|
|
5
5
|
var _internals = {
|
|
@@ -32,27 +32,29 @@ async function loadArrowModule() {
|
|
|
32
32
|
};
|
|
33
33
|
}
|
|
34
34
|
async function prepareArrowGraphData(input, mapping, options) {
|
|
35
|
+
const control = new PreparationControl(options);
|
|
35
36
|
const signal = options.signal;
|
|
36
37
|
throwIfAborted(signal);
|
|
37
38
|
const arrow = await loadArrowModule();
|
|
38
39
|
throwIfAborted(signal);
|
|
39
40
|
const deriveNodes = "deriveNodes" in input && input.deriveNodes === true;
|
|
40
|
-
const edgeTable = await arrowRowTable(input.edges, arrow, signal);
|
|
41
|
-
const nodeTable = deriveNodes ? null : await arrowRowTable(input.nodes, arrow, signal);
|
|
41
|
+
const edgeTable = await arrowRowTable(input.edges, arrow, signal, control);
|
|
42
|
+
const nodeTable = deriveNodes ? null : await arrowRowTable(input.nodes, arrow, signal, control);
|
|
42
43
|
return await buildPrepared({
|
|
43
44
|
nodeTable,
|
|
44
45
|
edgeTable,
|
|
45
46
|
mapping,
|
|
46
47
|
format: "arrow",
|
|
47
|
-
options: { ...options, format: "arrow" }
|
|
48
|
+
options: { ...options, format: "arrow" },
|
|
49
|
+
control
|
|
48
50
|
});
|
|
49
51
|
}
|
|
50
52
|
function isArrowTable(source) {
|
|
51
53
|
return typeof source === "object" && source !== null && "schema" in source && typeof source.getChild === "function" && Array.isArray(source.schema?.fields);
|
|
52
54
|
}
|
|
53
|
-
async function arrowRowTable(source, arrow, signal) {
|
|
55
|
+
async function arrowRowTable(source, arrow, signal, control) {
|
|
54
56
|
throwIfAborted(signal);
|
|
55
|
-
const table = isArrowTable(source) ? source : arrow.tableFromIPC(await collectBytes(source, signal));
|
|
57
|
+
const table = isArrowTable(source) ? source : arrow.tableFromIPC(await collectBytes(source, signal, control));
|
|
56
58
|
throwIfAborted(signal);
|
|
57
59
|
const columns = table.schema.fields.map((f) => f.name);
|
|
58
60
|
if (columns.length === 0 && table.numRows === 0) return EMPTY_ROW_TABLE;
|
package/dist/arrow.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/arrow.ts"],"names":[],"mappings":";;;;AA6CO,IAAM,UAAA,GAAa;AAAA,EACxB,WAAA,EAAa,MAAwB,OAAO,cAAc;AAC5D;AAOA,eAAe,eAAA,GAAwC;AACrD,EAAA,IAAI,GAAA;AACJ,EAAA,IAAI;AACF,IAAA,GAAA,GAAM,MAAM,WAAW,WAAA,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AAM,KAAA,GAAQ,OAAA,CAAQ,CAAC,CAAA,EAAG,IAAI,CAAC,CAAA;AAC/B,UAAA,IAAI,KAAA,KAAU,IAAA,IAAQ,KAAA,KAAU,MAAA,EAAW;AAG3C,UAAA,MAAA,CAAO,cAAA,CAAe,GAAA,EAAK,OAAA,CAAQ,CAAC,CAAA,EAAI;AAAA,YACtC,KAAA,EAAO,sBAAA,CAAuB,KAAA,EAAO,KAAA,CAAM,WAAW,CAAA;AAAA,YACtD,UAAA,EAAY,IAAA;AAAA,YACZ,QAAA,EAAU,IAAA;AAAA,YACV,YAAA,EAAc;AAAA,WACf,CAAA;AAAA,QACH;AACA,QAAA,cAAA,CAAe,MAAM,CAAA;AACrB,QAAA,MAAM,GAAA;AAAA,MACR;AACA,MAAA,cAAA,CAAe,MAAM,CAAA;AAAA,IACvB,CAAA;AAAG,GACL;AACF","file":"arrow.js","sourcesContent":["/**\n * Arrow format entry — `@modernrelay/orbit-data/arrow`.\n *\n * NEVER imported by the root entry: the\n * 'apache-arrow' optional peer is loaded with a DYNAMIC import inside the\n * call, so this module is import-safe without it (the clear install-hint\n * error fires only when preparation actually runs), and root-entry bundles\n * carry no arrow code.\n *\n * Sources per role are Arrow IPC bytes (file or stream framing\n * Blob/ArrayBuffer/AsyncIterable<Uint8Array>) or an already-constructed\n * arrow Table (duck-typed via `schema.fields`). Tables become row objects\n * through `getChild` vectors and feed the shared builder; columns come from\n * the SCHEMA (exact, not sampled). Value normalization for the object lane:\n * arrow nulls → absent keys, bigints → number when safely representable else\n * decimal string, and LIST/STRUCT values recursively become plain JSON\n * containers. Other values pass through.\n */\n\nimport { normalizeJsonSafeValue } from './jsonSafe';\n\nimport { buildPrepared } from './builder';\nimport { EMPTY_ROW_TABLE, type RowTable } from './rowTable';\nimport { collectBytes, throwIfAborted } from './sources';\nimport type {\n GraphByteSource,\n GraphColumnMapping,\n GraphPrepareOptions,\n PreparedGraph,\n} from './types';\n\n/** Structural subset of an apache-arrow Table (any supported major). */\nexport interface ArrowTableLike {\n readonly numRows: number;\n readonly schema: { readonly fields: ReadonlyArray<{ readonly name: string }> };\n getChild(name: string): { get(index: number): unknown } | null;\n}\n\nexport type ArrowGraphSource = GraphByteSource | ArrowTableLike;\n\nexport type ArrowGraphPrepareInput =\n | { nodes: ArrowGraphSource; edges: ArrowGraphSource }\n | { edges: ArrowGraphSource; deriveNodes: true };\n\n/** Test seam: lets suites simulate the missing-optional-dependency path. */\nexport const _internals = {\n importArrow: (): Promise<unknown> => import('apache-arrow'),\n};\n\ninterface ArrowModule {\n tableFromIPC(bytes: Uint8Array): ArrowTableLike;\n materialize(value: object): unknown;\n}\n\nasync function loadArrowModule(): Promise<ArrowModule> {\n let mod: unknown;\n try {\n mod = await _internals.importArrow();\n } catch (cause) {\n throw new Error(\n \"@modernrelay/orbit-data/arrow requires the optional peer dependency 'apache-arrow'. \" +\n 'Install it (e.g. `pnpm add apache-arrow`) to use prepareArrowGraphData.',\n { cause },\n );\n }\n const tableFromIPC = (mod as Record<string, unknown>)['tableFromIPC'];\n if (typeof tableFromIPC !== 'function') {\n throw new Error(\n \"@modernrelay/orbit-data/arrow: the installed 'apache-arrow' does not expose tableFromIPC \" +\n '(unsupported version?)',\n );\n }\n const { Vector, StructRow } = mod as typeof import('apache-arrow');\n return {\n tableFromIPC: tableFromIPC as (bytes: Uint8Array) => ArrowTableLike,\n materialize(value) {\n if (value instanceof Vector) return Array.from(value);\n // Iterate entries instead of using toJSON/Object.entries: Arrow's\n // property access and toJSON can shadow or lose fields such as\n // __proto__ and constructor. fromEntries always creates own data.\n if (value instanceof StructRow) return Object.fromEntries(value);\n return value;\n },\n };\n}\n\nexport async function prepareArrowGraphData<\n N = Record<string, unknown>,\n E = Record<string, unknown>,\n>(\n input: ArrowGraphPrepareInput,\n mapping: GraphColumnMapping,\n options: Omit<GraphPrepareOptions, 'format'>,\n): Promise<PreparedGraph<N, E>> {\n const signal = options.signal;\n throwIfAborted(signal);\n const arrow = await loadArrowModule();\n throwIfAborted(signal);\n const deriveNodes = 'deriveNodes' in input && input.deriveNodes === true;\n const edgeTable = await arrowRowTable(input.edges, arrow, signal);\n const nodeTable = deriveNodes\n ? null\n : await arrowRowTable((input as { nodes: ArrowGraphSource }).nodes, arrow, signal);\n return (await buildPrepared({\n nodeTable,\n edgeTable,\n mapping,\n format: 'arrow',\n options: { ...options, format: 'arrow' },\n })) as PreparedGraph<N, E>;\n}\n\nfunction isArrowTable(source: ArrowGraphSource): source is ArrowTableLike {\n return (\n typeof source === 'object' &&\n source !== null &&\n 'schema' in source &&\n typeof (source as ArrowTableLike).getChild === 'function' &&\n Array.isArray((source as ArrowTableLike).schema?.fields)\n );\n}\n\nasync function arrowRowTable(\n source: ArrowGraphSource,\n arrow: ArrowModule,\n signal: AbortSignal | undefined,\n): Promise<RowTable> {\n throwIfAborted(signal);\n const table = isArrowTable(source)\n ? source\n : arrow.tableFromIPC(await collectBytes(source as GraphByteSource, signal));\n throwIfAborted(signal);\n const columns = table.schema.fields.map((f) => f.name);\n if (columns.length === 0 && table.numRows === 0) return EMPTY_ROW_TABLE;\n const vectors = columns.map((name) => table.getChild(name));\n return {\n columns,\n rows: (async function* () {\n for (let i = 0; i < table.numRows; i++) {\n throwIfAborted(signal);\n const row: Record<string, unknown> = {};\n for (let j = 0; j < columns.length; j++) {\n const value = vectors[j]?.get(i);\n if (value === null || value === undefined) continue; // arrow null → absent\n // Arrow schemas may legally contain a `__proto__` column. Plain\n // assignment would invoke the legacy prototype setter and lose it.\n Object.defineProperty(row, columns[j]!, {\n value: normalizeJsonSafeValue(value, arrow.materialize),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n throwIfAborted(signal);\n yield row;\n }\n throwIfAborted(signal);\n })(),\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/arrow.ts"],"names":[],"mappings":";;;;AAiDO,IAAM,UAAA,GAAa;AAAA,EACxB,WAAA,EAAa,MAAwB,OAAO,cAAc;AAC5D;AAOA,eAAe,eAAA,GA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AI,KAAA,CAAM,SAAS,CAAA,EAAA,EAAK;AACtC,QAAA,cAAA,CAAe,MAAM,CAAA;AACrB,QAAA,MAAM,MAA+B,EAAC;AACtC,QAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,OAAA,CAAQ,QAAQ,CAAA,EAAA,EAAK;AACvC,UAAA,MAAM,KAAA,GAAQ,OAAA,CAAQ,CAAC,CAAA,EAAG,IAAI,CAAC,CAAA;AAC/B,UAAA,IAAI,KAAA,KAAU,IAAA,IAAQ,KAAA,KAAU,MAAA,EAAW;AAG3C,UAAA,MAAA,CAAO,cAAA,CAAe,GAAA,EAAK,OAAA,CAAQ,CAAC,CAAA,EAAI;AAAA,YACtC,KAAA,EAAO,sBAAA,CAAuB,KAAA,EAAO,KAAA,CAAM,WAAW,CAAA;AAAA,YACtD,UAAA,EAAY,IAAA;AAAA,YACZ,QAAA,EAAU,IAAA;AAAA,YACV,YAAA,EAAc;AAAA,WACf,CAAA;AAAA,QACH;AACA,QAAA,cAAA,CAAe,MAAM,CAAA;AACrB,QAAA,MAAM,GAAA;AAAA,MACR;AACA,MAAA,cAAA,CAAe,MAAM,CAAA;AAAA,IACvB,CAAA;AAAG,GACL;AACF","file":"arrow.js","sourcesContent":["/**\n * Arrow format entry — `@modernrelay/orbit-data/arrow`.\n *\n * NEVER imported by the root entry: the\n * 'apache-arrow' optional peer is loaded with a DYNAMIC import inside the\n * call, so this module is import-safe without it (the clear install-hint\n * error fires only when preparation actually runs), and root-entry bundles\n * carry no arrow code.\n *\n * Sources per role are Arrow IPC bytes (file or stream framing\n * Blob/ArrayBuffer/AsyncIterable<Uint8Array>) or an already-constructed\n * arrow Table (duck-typed via `schema.fields`). Tables become row objects\n * through `getChild` vectors and feed the shared builder; columns come from\n * the SCHEMA (exact, not sampled). Value normalization for the object lane:\n * arrow nulls → absent keys, bigints → number when safely representable else\n * decimal string, and LIST/STRUCT values recursively become plain JSON\n * containers. Other values pass through.\n */\n\nimport { normalizeJsonSafeValue } from './jsonSafe';\n\nimport { PreparationControl } from './control';\nimport { buildPrepared } from './builder';\nimport { EMPTY_ROW_TABLE, type RowTable } from './rowTable';\nimport { collectBytes, throwIfAborted } from './sources';\nimport type {\n GraphByteSource,\n GraphColumnMapping,\n GraphPrepareOptions,\n GraphPrepareAnyOptions,\n GraphPrepareColumnarOptions,\n PreparedColumnarGraph,\n PreparedGraph,\n} from './types';\n\n/** Structural subset of an apache-arrow Table (any supported major). */\nexport interface ArrowTableLike {\n readonly numRows: number;\n readonly schema: { readonly fields: ReadonlyArray<{ readonly name: string }> };\n getChild(name: string): { get(index: number): unknown } | null;\n}\n\nexport type ArrowGraphSource = GraphByteSource | ArrowTableLike;\n\nexport type ArrowGraphPrepareInput =\n | { nodes: ArrowGraphSource; edges: ArrowGraphSource }\n | { edges: ArrowGraphSource; deriveNodes: true };\n\n/** Test seam: lets suites simulate the missing-optional-dependency path. */\nexport const _internals = {\n importArrow: (): Promise<unknown> => import('apache-arrow'),\n};\n\ninterface ArrowModule {\n tableFromIPC(bytes: Uint8Array): ArrowTableLike;\n materialize(value: object): unknown;\n}\n\nasync function loadArrowModule(): Promise<ArrowModule> {\n let mod: unknown;\n try {\n mod = await _internals.importArrow();\n } catch (cause) {\n throw new Error(\n \"@modernrelay/orbit-data/arrow requires the optional peer dependency 'apache-arrow'. \" +\n 'Install it (e.g. `pnpm add apache-arrow`) to use prepareArrowGraphData.',\n { cause },\n );\n }\n const tableFromIPC = (mod as Record<string, unknown>)['tableFromIPC'];\n if (typeof tableFromIPC !== 'function') {\n throw new Error(\n \"@modernrelay/orbit-data/arrow: the installed 'apache-arrow' does not expose tableFromIPC \" +\n '(unsupported version?)',\n );\n }\n const { Vector, StructRow } = mod as typeof import('apache-arrow');\n return {\n tableFromIPC: tableFromIPC as (bytes: Uint8Array) => ArrowTableLike,\n materialize(value) {\n if (value instanceof Vector) return Array.from(value);\n // Iterate entries instead of using toJSON/Object.entries: Arrow's\n // property access and toJSON can shadow or lose fields such as\n // __proto__ and constructor. fromEntries always creates own data.\n if (value instanceof StructRow) return Object.fromEntries(value);\n return value;\n },\n };\n}\n\nexport function prepareArrowGraphData<N = Record<string, unknown>, E = Record<string, unknown>>(\n input: ArrowGraphPrepareInput, mapping: GraphColumnMapping, options: Omit<GraphPrepareColumnarOptions, 'format'>,\n): Promise<PreparedColumnarGraph<N, E>>;\nexport function prepareArrowGraphData<N = Record<string, unknown>, E = Record<string, unknown>>(\n input: ArrowGraphPrepareInput, mapping: GraphColumnMapping, options: Omit<GraphPrepareOptions, 'format'>,\n): Promise<PreparedGraph<N, E>>;\nexport function prepareArrowGraphData<N = Record<string, unknown>, E = Record<string, unknown>>(\n input: ArrowGraphPrepareInput, mapping: GraphColumnMapping, options: Omit<GraphPrepareAnyOptions, 'format'>,\n): Promise<PreparedGraph<N, E> | PreparedColumnarGraph<N, E>>;\nexport async function prepareArrowGraphData<\n N = Record<string, unknown>,\n E = Record<string, unknown>,\n>(\n input: ArrowGraphPrepareInput,\n mapping: GraphColumnMapping,\n options: Omit<GraphPrepareAnyOptions, 'format'>,\n): Promise<PreparedGraph<N, E> | PreparedColumnarGraph<N, E>> {\n const control = new PreparationControl(options as GraphPrepareAnyOptions);\n const signal = options.signal;\n throwIfAborted(signal);\n const arrow = await loadArrowModule();\n throwIfAborted(signal);\n const deriveNodes = 'deriveNodes' in input && input.deriveNodes === true;\n const edgeTable = await arrowRowTable(input.edges, arrow, signal, control);\n const nodeTable = deriveNodes\n ? null\n : await arrowRowTable((input as { nodes: ArrowGraphSource }).nodes, arrow, signal, control);\n return (await buildPrepared({\n nodeTable,\n edgeTable,\n mapping,\n format: 'arrow',\n options: { ...options, format: 'arrow' } as GraphPrepareAnyOptions,\n control,\n })) as PreparedGraph<N, E> | PreparedColumnarGraph<N, E>;\n}\n\nfunction isArrowTable(source: ArrowGraphSource): source is ArrowTableLike {\n return (\n typeof source === 'object' &&\n source !== null &&\n 'schema' in source &&\n typeof (source as ArrowTableLike).getChild === 'function' &&\n Array.isArray((source as ArrowTableLike).schema?.fields)\n );\n}\n\nasync function arrowRowTable(\n source: ArrowGraphSource,\n arrow: ArrowModule,\n signal: AbortSignal | undefined,\n control: PreparationControl,\n): Promise<RowTable> {\n throwIfAborted(signal);\n const table = isArrowTable(source)\n ? source\n : arrow.tableFromIPC(await collectBytes(source as GraphByteSource, signal, control));\n throwIfAborted(signal);\n const columns = table.schema.fields.map((f) => f.name);\n if (columns.length === 0 && table.numRows === 0) return EMPTY_ROW_TABLE;\n const vectors = columns.map((name) => table.getChild(name));\n return {\n columns,\n rows: (async function* () {\n for (let i = 0; i < table.numRows; i++) {\n throwIfAborted(signal);\n const row: Record<string, unknown> = {};\n for (let j = 0; j < columns.length; j++) {\n const value = vectors[j]?.get(i);\n if (value === null || value === undefined) continue; // arrow null → absent\n // Arrow schemas may legally contain a `__proto__` column. Plain\n // assignment would invoke the legacy prototype setter and lose it.\n Object.defineProperty(row, columns[j]!, {\n value: normalizeJsonSafeValue(value, arrow.materialize),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n throwIfAborted(signal);\n yield row;\n }\n throwIfAborted(signal);\n })(),\n };\n}\n"]}
|