fastdb4ts 0.0.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/column.d.ts CHANGED
@@ -18,6 +18,7 @@ export declare class StridedColumn {
18
18
  private normalizeIndex;
19
19
  private getArrayConstructor;
20
20
  private getDataView;
21
+ private writeDirect;
21
22
  }
22
23
  type TypedArray = Uint8Array | Uint16Array | Uint32Array | Int32Array | Float32Array | Float64Array;
23
24
  export {};
package/dist/column.js CHANGED
@@ -63,8 +63,15 @@ export class StridedColumn {
63
63
  if (values.length !== this.length) {
64
64
  throw new FastdbRuntimeError(`Column fill length mismatch: expected ${this.length}, got ${values.length}.`);
65
65
  }
66
+ if (this.kind === this.module.ftU8n || this.kind === this.module.ftU16n) {
67
+ for (let i = 0; i < this.length; i += 1) {
68
+ this.set(i, values[i] ?? 0);
69
+ }
70
+ return;
71
+ }
72
+ const view = this.getDataView();
66
73
  for (let i = 0; i < this.length; i += 1) {
67
- this.set(i, values[i] ?? 0);
74
+ this.writeDirect(view, this.basePtr + i * this.stride, values[i] ?? 0);
68
75
  }
69
76
  }
70
77
  toArray() {
@@ -113,6 +120,37 @@ export class StridedColumn {
113
120
  throw new FastdbRuntimeError(`Field index ${this.fieldIndex} is not a numeric column.`);
114
121
  }
115
122
  getDataView() {
123
+ // Always access HEAPU8.buffer fresh: if WASM memory grows, Emscripten replaces
124
+ // module.HEAPU8 with a new typed array. The linear-memory addresses stored in
125
+ // basePtr remain valid (they are indices into the linear address space), but
126
+ // any previously captured ArrayBuffer reference becomes detached.
116
127
  return new DataView(this.module.HEAPU8.buffer);
117
128
  }
129
+ writeDirect(view, offset, value) {
130
+ if (this.kind === this.module.ftU8) {
131
+ view.setUint8(offset, Math.trunc(Number(value)));
132
+ return;
133
+ }
134
+ if (this.kind === this.module.ftU16) {
135
+ view.setUint16(offset, Math.trunc(Number(value)), true);
136
+ return;
137
+ }
138
+ if (this.kind === this.module.ftU32) {
139
+ view.setUint32(offset, Math.trunc(Number(value)), true);
140
+ return;
141
+ }
142
+ if (this.kind === this.module.ftI32) {
143
+ view.setInt32(offset, Math.trunc(Number(value)), true);
144
+ return;
145
+ }
146
+ if (this.kind === this.module.ftF32) {
147
+ view.setFloat32(offset, Number(value), true);
148
+ return;
149
+ }
150
+ if (this.kind === this.module.ftF64) {
151
+ view.setFloat64(offset, Number(value), true);
152
+ return;
153
+ }
154
+ throw new FastdbRuntimeError(`Field index ${this.fieldIndex} is not a directly writable numeric column.`);
155
+ }
118
156
  }
@@ -0,0 +1,20 @@
1
+ import { type FastdbModule, type WxDatabaseHandle } from './wasm-loader.js';
2
+ export declare class FastdbOwnedBytes {
3
+ private readonly module;
4
+ private readonly size;
5
+ private ptr;
6
+ constructor(module: FastdbModule, ptr: number, size: number);
7
+ get byteLength(): number;
8
+ get dataPtr(): number;
9
+ get view(): Uint8Array;
10
+ release(): void;
11
+ takeForDatabase(): {
12
+ module: FastdbModule;
13
+ ptr: number;
14
+ byteLength: number;
15
+ };
16
+ private requireOwned;
17
+ }
18
+ export type FastdbDatabaseBytes = Uint8Array | ArrayBuffer | FastdbOwnedBytes;
19
+ export declare function allocateFastdbOwnedBytes(module: FastdbModule, byteLength: number): FastdbOwnedBytes;
20
+ export declare function loadDatabaseFromBytes(module: FastdbModule, bytes: FastdbDatabaseBytes): WxDatabaseHandle;
@@ -0,0 +1,101 @@
1
+ import { FastdbRuntimeError } from './errors.js';
2
+ export class FastdbOwnedBytes {
3
+ module;
4
+ size;
5
+ ptr;
6
+ constructor(module, ptr, size) {
7
+ this.module = module;
8
+ this.size = size;
9
+ if (!Number.isSafeInteger(ptr) || ptr <= 0) {
10
+ throw new FastdbRuntimeError('fastdb owned buffer pointer must be a positive WASM heap address.');
11
+ }
12
+ if (!Number.isSafeInteger(size) || size <= 0) {
13
+ throw new FastdbRuntimeError('fastdb owned buffer byte length must be a positive integer.');
14
+ }
15
+ this.ptr = ptr;
16
+ }
17
+ get byteLength() {
18
+ return this.size;
19
+ }
20
+ get dataPtr() {
21
+ return this.requireOwned();
22
+ }
23
+ get view() {
24
+ const ptr = this.requireOwned();
25
+ return this.module.HEAPU8.subarray(ptr, ptr + this.size);
26
+ }
27
+ release() {
28
+ if (this.ptr === null) {
29
+ return;
30
+ }
31
+ const ptr = this.ptr;
32
+ this.ptr = null;
33
+ this.module._free(ptr);
34
+ }
35
+ takeForDatabase() {
36
+ const ptr = this.requireOwned();
37
+ this.ptr = null;
38
+ return {
39
+ module: this.module,
40
+ ptr,
41
+ byteLength: this.size,
42
+ };
43
+ }
44
+ requireOwned() {
45
+ if (this.ptr === null) {
46
+ throw new FastdbRuntimeError('fastdb owned buffer has already been transferred or released.');
47
+ }
48
+ return this.ptr;
49
+ }
50
+ }
51
+ export function allocateFastdbOwnedBytes(module, byteLength) {
52
+ if (!Number.isSafeInteger(byteLength) || byteLength <= 0) {
53
+ throw new FastdbRuntimeError('fastdb owned buffer byte length must be a positive integer.');
54
+ }
55
+ const ptr = module._malloc(byteLength);
56
+ if (ptr === 0) {
57
+ throw new FastdbRuntimeError(`Failed to allocate ${byteLength} bytes in the fastdb WASM heap.`);
58
+ }
59
+ return new FastdbOwnedBytes(module, ptr, byteLength);
60
+ }
61
+ export function loadDatabaseFromBytes(module, bytes) {
62
+ if (bytes instanceof FastdbOwnedBytes) {
63
+ const owned = bytes.takeForDatabase();
64
+ if (owned.module !== module) {
65
+ owned.module._free(owned.ptr);
66
+ throw new FastdbRuntimeError('fastdb owned buffer was allocated by a different WASM module.');
67
+ }
68
+ return loadDatabaseFromOwnedHeap(module, owned.ptr, owned.byteLength);
69
+ }
70
+ if (bytes instanceof ArrayBuffer) {
71
+ return loadDatabaseFromBytes(module, new Uint8Array(bytes));
72
+ }
73
+ if (bytes.byteLength === 0) {
74
+ throw new FastdbRuntimeError('Cannot load an empty fastdb buffer.');
75
+ }
76
+ const owned = allocateFastdbOwnedBytes(module, bytes.byteLength);
77
+ try {
78
+ owned.view.set(bytes);
79
+ const payload = owned.takeForDatabase();
80
+ return loadDatabaseFromOwnedHeap(module, payload.ptr, payload.byteLength);
81
+ }
82
+ finally {
83
+ owned.release();
84
+ }
85
+ }
86
+ function loadDatabaseFromOwnedHeap(module, ptr, byteLength) {
87
+ let ownedByDatabase = false;
88
+ try {
89
+ const db = module.WxDatabase.loadFromOwnedHeap(ptr, byteLength);
90
+ if (!db) {
91
+ throw new FastdbRuntimeError('Failed to load fastdb buffer.');
92
+ }
93
+ ownedByDatabase = true;
94
+ return db;
95
+ }
96
+ finally {
97
+ if (!ownedByDatabase) {
98
+ module._free(ptr);
99
+ }
100
+ }
101
+ }
package/dist/feature.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type ClassSchema } from './schema.js';
2
- import type { WxDatabaseBuildHandle, WxDatabaseHandle, WxFeatureHandle } from './wasm-loader.js';
2
+ import { type WxDatabaseBuildHandle, type WxDatabaseHandle, type WxFeatureHandle } from './wasm-loader.js';
3
3
  declare const PROXY_SYMBOL: unique symbol;
4
4
  export type FeatureDatabaseHandle = WxDatabaseHandle | WxDatabaseBuildHandle;
5
5
  export interface FeatureClass<T extends Feature = Feature> {
package/dist/feature.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { FastdbRuntimeError, FastdbSchemaError, FastdbUsageError, } from './errors.js';
2
- import { getClassSchema, getFieldDefinition, } from './schema.js';
3
- import { isNumericField, isRefField, } from './types.js';
2
+ import { getClassSchema, getFieldDefinition, resolveListItem, } from './schema.js';
3
+ import { coerceBoolScalar, isListField, isNumericField, isRefField, } from './types.js';
4
+ import { getInitializedFastdbModule, } from './wasm-loader.js';
4
5
  const PROXY_SYMBOL = Symbol('fastdb4ts.proxy');
5
6
  export class Feature {
6
7
  _origin = null;
@@ -111,16 +112,56 @@ function readMappedField(feature, def) {
111
112
  case 'f64':
112
113
  return origin.getFieldAsFloat(def.index);
113
114
  case 'str':
114
- case 'wstr':
115
115
  return origin.getFieldAsString(def.index);
116
+ case 'wstr':
117
+ return origin.getFieldAsWString(def.index);
116
118
  case 'bytes':
117
- return origin.geometryView();
119
+ return copyChunkToBytes(origin.geometryView());
120
+ case 'list':
121
+ return readMappedListField(origin, def);
118
122
  case 'ref':
119
123
  return feature._cache?.[def.name] ?? null;
120
124
  default:
121
125
  throw new FastdbSchemaError(`Unsupported field kind: ${entry.kind}`);
122
126
  }
123
127
  }
128
+ function copyChunkToBytes(chunk) {
129
+ const module = getInitializedFastdbModule();
130
+ return module.HEAPU8.slice(chunk.data, chunk.data + chunk.size);
131
+ }
132
+ function readMappedListField(origin, def) {
133
+ if (!isListField(def.entry)) {
134
+ throw new FastdbSchemaError(`Field "${def.name}" is not a list field.`);
135
+ }
136
+ const item = resolveListItem(def.entry);
137
+ if (!isFieldType(item) || !item.arrayCtor) {
138
+ throw new FastdbSchemaError(`Mapped list field "${def.name}" can only materialize numeric scalar lists through the columnar runtime.`);
139
+ }
140
+ const bytes = copyChunkToBytes(origin.getFieldAsListView(def.index));
141
+ if (bytes.length === 0) {
142
+ return [];
143
+ }
144
+ const bytesPerElement = item.arrayCtor.BYTES_PER_ELEMENT;
145
+ if (bytes.length % bytesPerElement !== 0) {
146
+ throw new FastdbRuntimeError(`Mapped list field "${def.name}" has ${bytes.length} byte(s), not a multiple of ${bytesPerElement}.`);
147
+ }
148
+ const source = typedArraySource(bytes);
149
+ const typed = new item.arrayCtor(source.buffer, source.byteOffset, bytes.length / bytesPerElement);
150
+ if (item.kind === 'bool') {
151
+ return Array.from(typed, (value) => coerceBoolScalar(value));
152
+ }
153
+ return Array.from(typed);
154
+ }
155
+ function typedArraySource(bytes) {
156
+ if (bytes.buffer instanceof ArrayBuffer) {
157
+ return { buffer: bytes.buffer, byteOffset: bytes.byteOffset };
158
+ }
159
+ const copy = bytes.slice();
160
+ return { buffer: copy.buffer, byteOffset: copy.byteOffset };
161
+ }
162
+ function isFieldType(value) {
163
+ return typeof value === 'object' && value !== null && 'kind' in value && 'originType' in value;
164
+ }
124
165
  function writeMappedField(feature, def, value) {
125
166
  const origin = feature._origin;
126
167
  if (!origin) {
@@ -133,7 +174,7 @@ function writeMappedField(feature, def, value) {
133
174
  return;
134
175
  }
135
176
  if (entry.kind === 'bool') {
136
- origin.setFieldInt(def.index, value ? 1 : 0);
177
+ origin.setFieldInt(def.index, coerceBoolScalar(value) ? 1 : 0);
137
178
  return;
138
179
  }
139
180
  origin.setFieldInt(def.index, Math.trunc(Number(value)));
@@ -143,7 +184,10 @@ function writeMappedField(feature, def, value) {
143
184
  writeRefField(feature, def, entry, value);
144
185
  return;
145
186
  }
146
- throw new FastdbUsageError(`Direct writes to db-mapped field "${def.name}" of type "${entry.kind}" are not supported yet.`);
187
+ // For str/wstr/bytes/list: WxFeatureHandle does not support writing these types back
188
+ // to the underlying WASM storage on an immutable database. Fall back to in-memory cache
189
+ // only — changes are not persisted across toBuffer() / fromBuffer() round-trips.
190
+ feature._getCache()[def.name] = value;
147
191
  }
148
192
  function writeRefField(feature, def, entry, value) {
149
193
  if (value === null || value === undefined) {
@@ -160,8 +204,9 @@ function writeRefField(feature, def, entry, value) {
160
204
  }
161
205
  function createDefaultValue(def) {
162
206
  const entry = def.entry;
163
- if (isRefField(entry) && def.target) {
164
- return createFeature(def.target);
207
+ if (isRefField(entry)) {
208
+ // Ref fields default to null to avoid infinite recursion for self-referential schemas.
209
+ return null;
165
210
  }
166
211
  return entry.createDefault();
167
212
  }
package/dist/index.d.ts CHANGED
@@ -4,10 +4,14 @@ export { ORM, TableDefn, } from './orm.js';
4
4
  export { Table } from './table.js';
5
5
  export { StridedColumn } from './column.js';
6
6
  export { FastSerializer } from './serializer.js';
7
+ export { FastdbOwnedBytes, allocateFastdbOwnedBytes, loadDatabaseFromBytes, } from './database-buffer.js';
8
+ export type { FastdbDatabaseBytes } from './database-buffer.js';
9
+ export { decodeFastdbCallDb, decodeFastdbFeature, encodeFastdbCallDb, encodeFastdbFeature, viewFastdbCallDb, } from './call-db.js';
7
10
  export { defineSchema, getClassSchema, } from './schema.js';
8
11
  export { BOOL, BYTES, F32, F64, I32, REF, STR, U8, U8N, U16, U16N, U32, WSTR, listOf, ref, } from './types.js';
9
12
  export { FastdbError, FastdbRuntimeError, FastdbSchemaError, FastdbUsageError, } from './errors.js';
10
13
  export type { ChunkView, FieldDefView, FastdbModule, FastdbModuleFactory, WxDatabaseBuildHandle, WxDatabaseHandle, WxFeatureHandle, WxLayerTableBuildHandle, WxLayerTableHandle, WxMemoryStreamHandle, } from './wasm-loader.js';
11
14
  export type { ClassSchema, SchemaDefinition, SchemaFieldDefinition, } from './schema.js';
15
+ export type { FastdbCallDbArrayItem, FastdbCallDbBinding, FastdbCallDbArrayView, FastdbCallDbColumnView, FastdbCallDbFeatureDependency, FastdbCallDbScalarField, FastdbCallDbTable, FastdbCallDbTableView, FastdbCallDbView, FastdbFeatureCodecBinding, } from './call-db.js';
12
16
  export type { FeatureClass, FeatureDatabaseHandle, } from './feature.js';
13
17
  export type { FieldKind, FieldTypeDef, ListFieldDef, ListItemDef, RefFieldDef, SchemaEntry, TypedArrayConstructor, TypedArrayInstance, } from './types.js';
package/dist/index.js CHANGED
@@ -4,6 +4,8 @@ export { ORM, TableDefn, } from './orm.js';
4
4
  export { Table } from './table.js';
5
5
  export { StridedColumn } from './column.js';
6
6
  export { FastSerializer } from './serializer.js';
7
+ export { FastdbOwnedBytes, allocateFastdbOwnedBytes, loadDatabaseFromBytes, } from './database-buffer.js';
8
+ export { decodeFastdbCallDb, decodeFastdbFeature, encodeFastdbCallDb, encodeFastdbFeature, viewFastdbCallDb, } from './call-db.js';
7
9
  export { defineSchema, getClassSchema, } from './schema.js';
8
10
  export { BOOL, BYTES, F32, F64, I32, REF, STR, U8, U8N, U16, U16N, U32, WSTR, listOf, ref, } from './types.js';
9
11
  export { FastdbError, FastdbRuntimeError, FastdbSchemaError, FastdbUsageError, } from './errors.js';
package/dist/orm.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Feature, type FeatureClass } from './feature.js';
2
2
  import { Table } from './table.js';
3
+ import { type FastdbDatabaseBytes } from './database-buffer.js';
3
4
  export declare class TableDefn<T extends Feature> {
4
5
  readonly featureType: FeatureClass<T>;
5
6
  readonly capacity: number;
@@ -10,17 +11,23 @@ export declare class ORM {
10
11
  private readonly module;
11
12
  private origin;
12
13
  private readonly tableMap;
14
+ private _closed;
13
15
  private constructor();
14
16
  get fixed(): boolean;
15
17
  static create(): ORM;
16
18
  static truncate(defns: TableDefn<Feature>[]): ORM;
17
- static fromBuffer(data: Uint8Array | ArrayBuffer): ORM;
19
+ static fromBuffer(data: FastdbDatabaseBytes): ORM;
18
20
  push<T extends Feature>(feature: T, tableName?: string): void;
21
+ ensureTable<T extends Feature>(featureType: FeatureClass<T>, name?: string): Table<T>;
19
22
  combine(): void;
20
23
  toBuffer(): Uint8Array;
21
24
  table<T extends Feature>(featureType: FeatureClass<T>, name?: string): Table<T>;
25
+ /** Release WASM resources held by this ORM. Idempotent — safe to call multiple times. */
26
+ close(): void;
27
+ private static getModule;
22
28
  private getBuildOrigin;
23
29
  private defineTableFields;
30
+ private configureDefaultGeometry;
24
31
  private ensureTruncateCompatible;
25
32
  private copyChunkToBytes;
26
33
  private disposeBuildTables;
package/dist/orm.js CHANGED
@@ -1,7 +1,9 @@
1
- import { getClassSchema } from './schema.js';
1
+ import { getClassSchema, resolveListItem } from './schema.js';
2
2
  import { FastdbRuntimeError, FastdbUsageError } from './errors.js';
3
3
  import { Table } from './table.js';
4
+ import { loadDatabaseFromBytes } from './database-buffer.js';
4
5
  import { getInitializedFastdbModule } from './wasm-loader.js';
6
+ import { coerceBoolScalar, isListField } from './types.js';
5
7
  export class TableDefn {
6
8
  featureType;
7
9
  capacity;
@@ -16,6 +18,7 @@ export class ORM {
16
18
  module;
17
19
  origin;
18
20
  tableMap = new Map();
21
+ _closed = false;
19
22
  constructor(origin, module) {
20
23
  this.origin = origin;
21
24
  this.module = module;
@@ -24,7 +27,7 @@ export class ORM {
24
27
  return 'bufferView' in this.origin;
25
28
  }
26
29
  static create() {
27
- const module = getInitializedFastdbModule();
30
+ const module = ORM.getModule();
28
31
  const origin = new module.WxDatabaseBuild();
29
32
  origin.begin('');
30
33
  return new ORM(origin, module);
@@ -39,7 +42,7 @@ export class ORM {
39
42
  orm.ensureTruncateCompatible(defn.featureType);
40
43
  const layerName = defn.name ?? defn.featureType.name;
41
44
  const table = build.createLayerBegin(layerName);
42
- table.setGeometryType(orm.module.gtAny, orm.module.cfDefault, false);
45
+ orm.configureDefaultGeometry(table, defn.featureType);
43
46
  orm.defineTableFields(table, defn.featureType);
44
47
  build.createLayerEnd();
45
48
  build.truncate(layerName, defn.capacity);
@@ -48,32 +51,14 @@ export class ORM {
48
51
  return orm;
49
52
  }
50
53
  static fromBuffer(data) {
51
- const module = getInitializedFastdbModule();
52
- const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
53
- const ptr = module._malloc(bytes.byteLength);
54
- try {
55
- module.HEAPU8.set(bytes, ptr);
56
- const db = module.WxDatabase.loadFromHeap(ptr, bytes.byteLength);
57
- return new ORM(db, module);
58
- }
59
- finally {
60
- module._free(ptr);
61
- }
54
+ const module = ORM.getModule();
55
+ return new ORM(loadDatabaseFromBytes(module, data), module);
62
56
  }
63
57
  push(feature, tableName) {
64
- const build = this.getBuildOrigin();
65
58
  const featureType = feature.constructor;
66
59
  const name = tableName ?? featureType.name;
67
- let table = this.tableMap.get(name);
68
- let origin;
69
- if (!table) {
70
- origin = build.createLayerBegin(name);
71
- origin.setGeometryType(this.module.gtAny, this.module.cfDefault, false);
72
- this.defineTableFields(origin, featureType);
73
- this.tableMap.set(name, new Table(featureType, origin, build, this.module));
74
- table = this.tableMap.get(name);
75
- }
76
- origin = table.origin;
60
+ const table = this.ensureTable(featureType, name);
61
+ const origin = table.origin;
77
62
  origin.addFeatureBegin();
78
63
  try {
79
64
  const schema = getClassSchema(featureType);
@@ -81,7 +66,7 @@ export class ORM {
81
66
  const value = feature[field.name];
82
67
  const kind = field.entry.kind;
83
68
  if (kind === 'bool') {
84
- origin.setFieldInt(field.index, value ? 1 : 0);
69
+ origin.setFieldInt(field.index, coerceBoolScalar(value) ? 1 : 0);
85
70
  }
86
71
  else if (kind === 'u8' ||
87
72
  kind === 'u16' ||
@@ -95,9 +80,24 @@ export class ORM {
95
80
  kind === 'f64') {
96
81
  origin.setFieldDouble(field.index, Number(value));
97
82
  }
98
- else if (kind === 'str' || kind === 'wstr') {
83
+ else if (kind === 'str') {
99
84
  origin.setFieldString(field.index, String(value ?? ''));
100
85
  }
86
+ else if (kind === 'wstr') {
87
+ origin.setFieldWString(field.index, String(value ?? ''));
88
+ }
89
+ else if (kind === 'bytes') {
90
+ const bytes = normalizeBytes(value);
91
+ withHeapBytes(this.module, bytes, (ptr, size) => {
92
+ origin.setGeometryRaw(ptr, size);
93
+ });
94
+ }
95
+ else if (isListField(field.entry)) {
96
+ const bytes = normalizeNumericList(value, listElementFieldType(field), `field "${field.name}"`);
97
+ withHeapBytes(this.module, bytes, (ptr, size) => {
98
+ origin.setFieldListNumeric(field.index, ptr, size);
99
+ });
100
+ }
101
101
  else {
102
102
  throw new FastdbUsageError(`push() does not support field kind "${kind}" yet.`);
103
103
  }
@@ -107,6 +107,20 @@ export class ORM {
107
107
  origin.addFeatureEnd();
108
108
  }
109
109
  }
110
+ ensureTable(featureType, name) {
111
+ const build = this.getBuildOrigin();
112
+ const tableName = name ?? featureType.name;
113
+ const cached = this.tableMap.get(tableName);
114
+ if (cached) {
115
+ return cached;
116
+ }
117
+ const origin = build.createLayerBegin(tableName);
118
+ this.configureDefaultGeometry(origin, featureType);
119
+ this.defineTableFields(origin, featureType);
120
+ const table = new Table(featureType, origin, build, this.module);
121
+ this.tableMap.set(tableName, table);
122
+ return table;
123
+ }
110
124
  combine() {
111
125
  const build = this.getBuildOrigin();
112
126
  const stream = new this.module.WxMemoryStream();
@@ -151,6 +165,22 @@ export class ORM {
151
165
  }
152
166
  throw new FastdbRuntimeError(`Table "${tableName}" not found.`);
153
167
  }
168
+ /** Release WASM resources held by this ORM. Idempotent — safe to call multiple times. */
169
+ close() {
170
+ if (this._closed)
171
+ return;
172
+ this._closed = true;
173
+ this.tableMap.clear();
174
+ this.origin.delete();
175
+ }
176
+ static getModule() {
177
+ try {
178
+ return getInitializedFastdbModule();
179
+ }
180
+ catch {
181
+ throw new FastdbRuntimeError('fastdb4ts has not been initialized. Call `await initFastdb()` before creating an ORM.');
182
+ }
183
+ }
154
184
  getBuildOrigin() {
155
185
  if (this.fixed) {
156
186
  throw new FastdbUsageError('Operation is only available for mutable ORM instances.');
@@ -159,10 +189,28 @@ export class ORM {
159
189
  }
160
190
  defineTableFields(table, featureType) {
161
191
  const schema = getClassSchema(featureType);
192
+ const bytesFields = schema.fieldList.filter((field) => field.entry.kind === 'bytes');
193
+ if (bytesFields.length > 1) {
194
+ throw new FastdbUsageError(`ORM.push() does not support multiple bytes fields in "${featureType.name}"; fastdb columnar bytes use the feature raw payload.`);
195
+ }
162
196
  for (const field of schema.fieldList) {
163
- table.addField(field.name, field.entry.originType, 0, 1);
197
+ if (isListField(field.entry)) {
198
+ table.addListField(field.name, listElementFieldType(field).originType);
199
+ }
200
+ else {
201
+ table.addField(field.name, field.entry.originType, 0, 1);
202
+ }
164
203
  }
165
204
  }
205
+ configureDefaultGeometry(table, featureType) {
206
+ const schema = getClassSchema(featureType);
207
+ if (schema.fieldList.some((field) => field.entry.kind === 'bytes')) {
208
+ table.setGeometryType(this.module.gtAny, this.module.cfDefault, false);
209
+ return;
210
+ }
211
+ table.setGeometryType(this.module.gtPoint, this.module.cfTx32, true);
212
+ table.setExtent(-180, -90, 180, 90);
213
+ }
166
214
  ensureTruncateCompatible(featureType) {
167
215
  const schema = getClassSchema(featureType);
168
216
  for (const field of schema.fieldList) {
@@ -183,3 +231,74 @@ export class ORM {
183
231
  }
184
232
  }
185
233
  }
234
+ function normalizeBytes(value) {
235
+ if (value === null || value === undefined) {
236
+ return new Uint8Array(0);
237
+ }
238
+ if (value instanceof Uint8Array) {
239
+ return value;
240
+ }
241
+ if (value instanceof ArrayBuffer) {
242
+ return new Uint8Array(value);
243
+ }
244
+ if (ArrayBuffer.isView(value)) {
245
+ return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
246
+ }
247
+ throw new FastdbUsageError(`push() bytes fields expect Uint8Array or ArrayBuffer, got "${typeof value}".`);
248
+ }
249
+ function listElementFieldType(field) {
250
+ if (!isListField(field.entry)) {
251
+ throw new FastdbUsageError(`Field "${field.name}" is not a list field.`);
252
+ }
253
+ const item = resolveListItem(field.entry);
254
+ if (!isFieldType(item) || !item.arrayCtor || !isSupportedListElementKind(item.kind)) {
255
+ throw new FastdbUsageError(`push() list field "${field.name}" supports only numeric scalar list elements in the columnar runtime.`);
256
+ }
257
+ return item;
258
+ }
259
+ function normalizeNumericList(value, item, context) {
260
+ if (value === null || value === undefined) {
261
+ return new Uint8Array(0);
262
+ }
263
+ const arrayCtor = item.arrayCtor;
264
+ if (!arrayCtor) {
265
+ throw new FastdbUsageError(`${context} is not a numeric fastdb list field.`);
266
+ }
267
+ if (ArrayBuffer.isView(value) && !(value instanceof DataView)) {
268
+ const view = value;
269
+ if (value.constructor === arrayCtor) {
270
+ return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
271
+ }
272
+ }
273
+ if (!Array.isArray(value) && !(ArrayBuffer.isView(value) && !(value instanceof DataView))) {
274
+ throw new FastdbUsageError(`${context} expects an array or typed array value.`);
275
+ }
276
+ const values = Array.from(value);
277
+ const typed = new arrayCtor(values.length);
278
+ for (let index = 0; index < values.length; index += 1) {
279
+ const numeric = item.kind === 'bool'
280
+ ? (coerceBoolScalar(values[index]) ? 1 : 0)
281
+ : Number(values[index]);
282
+ typed[index] = numeric;
283
+ }
284
+ return new Uint8Array(typed.buffer, typed.byteOffset, typed.byteLength);
285
+ }
286
+ function isSupportedListElementKind(kind) {
287
+ return kind === 'bool' || kind === 'u8' || kind === 'u16' || kind === 'u32' || kind === 'i32' || kind === 'u8n' || kind === 'u16n' || kind === 'f32' || kind === 'f64';
288
+ }
289
+ function isFieldType(value) {
290
+ return typeof value === 'object' && value !== null && 'kind' in value && 'originType' in value;
291
+ }
292
+ function withHeapBytes(module, bytes, fn) {
293
+ if (bytes.length === 0) {
294
+ return fn(0, 0);
295
+ }
296
+ const ptr = module._malloc(bytes.length);
297
+ try {
298
+ module.HEAPU8.set(bytes, ptr);
299
+ return fn(ptr, bytes.length);
300
+ }
301
+ finally {
302
+ module._free(ptr);
303
+ }
304
+ }
@@ -1,5 +1,32 @@
1
1
  import { Feature, type FeatureClass } from './feature.js';
2
+ import { type FastdbDatabaseBytes } from './database-buffer.js';
2
3
  export declare class FastSerializer {
3
4
  static dumps(obj: Feature): Uint8Array;
4
- static loads<T extends Feature>(data: Uint8Array | ArrayBuffer, rootType: FeatureClass<T>): T | null;
5
+ static loads<T extends Feature>(data: FastdbDatabaseBytes, rootType: FeatureClass<T>): T | null;
5
6
  }
7
+ declare class ByteWriter {
8
+ private buf;
9
+ private view;
10
+ private offset;
11
+ constructor(initialCapacity?: number);
12
+ writeU16(value: number): void;
13
+ writeU32(value: number): void;
14
+ writeI32(value: number): void;
15
+ writeF64(value: number): void;
16
+ writeBytes(bytes: Uint8Array): void;
17
+ finish(): Uint8Array;
18
+ private ensureCapacity;
19
+ }
20
+ declare class ByteReader {
21
+ private readonly bytes;
22
+ private offset;
23
+ private readonly view;
24
+ constructor(bytes: Uint8Array);
25
+ private checkRead;
26
+ readU16(): number;
27
+ readU32(): number;
28
+ readI32(): number;
29
+ readF64(): number;
30
+ readBytes(size: number): Uint8Array;
31
+ }
32
+ export { ByteReader, ByteWriter };