documents.js 1.52.0 → 1.53.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/dist/index.cjs CHANGED
@@ -9211,12 +9211,12 @@ function textToPdfString(text) {
9211
9211
  }
9212
9212
  return pdfHexString(bytes);
9213
9213
  }
9214
- function pad2(n) {
9214
+ function pad2$2(n) {
9215
9215
  return n.toString().padStart(2, "0");
9216
9216
  }
9217
9217
  function formatPdfDate(iso) {
9218
9218
  const date = new Date(iso);
9219
- return `D:${date.getUTCFullYear()}${pad2(date.getUTCMonth() + 1)}${pad2(date.getUTCDate())}${pad2(date.getUTCHours())}${pad2(date.getUTCMinutes())}${pad2(date.getUTCSeconds())}Z`;
9219
+ return `D:${date.getUTCFullYear()}${pad2$2(date.getUTCMonth() + 1)}${pad2$2(date.getUTCDate())}${pad2$2(date.getUTCHours())}${pad2$2(date.getUTCMinutes())}${pad2$2(date.getUTCSeconds())}Z`;
9220
9220
  }
9221
9221
  function buildInfoDict(doc) {
9222
9222
  const entries = /* @__PURE__ */ new Map();
@@ -14571,6 +14571,1030 @@ function buildOdbTableCsv(tables, tableName) {
14571
14571
  return new TextEncoder().encode(`${lines.join("\r\n")}\r\n`);
14572
14572
  }
14573
14573
  //#endregion
14574
+ //#region src/hsqldb/rowformat.ts
14575
+ var HsqldbRowFormatError = class extends Error {
14576
+ constructor(message) {
14577
+ super(`HSQLDB binary row format error: ${message}`);
14578
+ this.name = "HsqldbRowFormatError";
14579
+ }
14580
+ };
14581
+ const SQL_TYPE_NAME_TO_CODE = {
14582
+ INTEGER: 4,
14583
+ INT: 4,
14584
+ IDENTITY: 4,
14585
+ DOUBLE: 8,
14586
+ FLOAT: 6,
14587
+ REAL: 7,
14588
+ VARCHAR: 12,
14589
+ CHAR: 1,
14590
+ CHARACTER: 1,
14591
+ LONGVARCHAR: -1,
14592
+ VARCHAR_IGNORECASE: 100,
14593
+ DATE: 91,
14594
+ TIME: 92,
14595
+ TIMESTAMP: 93,
14596
+ DATETIME: 93,
14597
+ DECIMAL: 3,
14598
+ NUMERIC: 2,
14599
+ BIT: 16,
14600
+ BOOLEAN: 16,
14601
+ TINYINT: -6,
14602
+ SMALLINT: 5,
14603
+ BIGINT: -5
14604
+ };
14605
+ const UNSUPPORTED_SQL_TYPE_NAMES = /* @__PURE__ */ new Set([
14606
+ "BINARY",
14607
+ "VARBINARY",
14608
+ "LONGVARBINARY",
14609
+ "OTHER",
14610
+ "OBJECT"
14611
+ ]);
14612
+ const LEADING_WORD_RE = /^([A-Za-z_][A-Za-z0-9_]*)/;
14613
+ function resolveHsqldbTypeCode(declaredType) {
14614
+ const word = LEADING_WORD_RE.exec(declaredType.trim())?.[1]?.toUpperCase();
14615
+ if (word === void 0) throw new HsqldbRowFormatError(`cannot resolve a SQL type name from column type clause "${declaredType}"`);
14616
+ if (UNSUPPORTED_SQL_TYPE_NAMES.has(word)) throw new HsqldbRowFormatError(`column type "${word}" has no document-content-model ContentCellValue equivalent (binary/object column types are not representable) -- from declared type "${declaredType}"`);
14617
+ const code = SQL_TYPE_NAME_TO_CODE[word];
14618
+ if (code === void 0) throw new HsqldbRowFormatError(`unrecognised HSQLDB column type "${word}" -- from declared type "${declaredType}"`);
14619
+ return code;
14620
+ }
14621
+ var HsqldbDataCursor = class {
14622
+ bytes;
14623
+ view;
14624
+ position;
14625
+ constructor(bytes, offset = 0) {
14626
+ this.bytes = bytes;
14627
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
14628
+ this.position = offset;
14629
+ }
14630
+ readUint8() {
14631
+ const value = this.view.getUint8(this.position);
14632
+ this.position += 1;
14633
+ return value;
14634
+ }
14635
+ readInt16() {
14636
+ const value = this.view.getInt16(this.position, false);
14637
+ this.position += 2;
14638
+ return value;
14639
+ }
14640
+ readInt32() {
14641
+ const value = this.view.getInt32(this.position, false);
14642
+ this.position += 4;
14643
+ return value;
14644
+ }
14645
+ readBigInt64() {
14646
+ const value = this.view.getBigInt64(this.position, false);
14647
+ this.position += 8;
14648
+ return value;
14649
+ }
14650
+ readFloat64() {
14651
+ const value = this.view.getFloat64(this.position, false);
14652
+ this.position += 8;
14653
+ return value;
14654
+ }
14655
+ readBytes(length) {
14656
+ const slice = this.bytes.subarray(this.position, this.position + length);
14657
+ this.position += length;
14658
+ return slice;
14659
+ }
14660
+ };
14661
+ function readModifiedUtf8(bytes) {
14662
+ let result = "";
14663
+ let i = 0;
14664
+ while (i < bytes.length) {
14665
+ const b0 = bytes[i];
14666
+ if (b0 === void 0) throw new HsqldbRowFormatError("truncated modified-UTF-8 byte sequence");
14667
+ if (b0 > 0 && b0 < 128) {
14668
+ result += String.fromCharCode(b0);
14669
+ i += 1;
14670
+ continue;
14671
+ }
14672
+ const leadNibble = b0 >> 4;
14673
+ if (leadNibble === 12 || leadNibble === 13) {
14674
+ const b1 = bytes[i + 1];
14675
+ if (b1 === void 0 || (b1 & 192) !== 128) throw new HsqldbRowFormatError("malformed modified-UTF-8 2-byte sequence");
14676
+ result += String.fromCharCode((b0 & 31) << 6 | b1 & 63);
14677
+ i += 2;
14678
+ continue;
14679
+ }
14680
+ if (leadNibble === 14) {
14681
+ const b1 = bytes[i + 1];
14682
+ const b2 = bytes[i + 2];
14683
+ if (b1 === void 0 || b2 === void 0 || (b1 & 192) !== 128 || (b2 & 192) !== 128) throw new HsqldbRowFormatError("malformed modified-UTF-8 3-byte sequence");
14684
+ result += String.fromCharCode((b0 & 15) << 12 | (b1 & 63) << 6 | b2 & 63);
14685
+ i += 3;
14686
+ continue;
14687
+ }
14688
+ throw new HsqldbRowFormatError(`malformed modified-UTF-8 lead byte 0x${b0.toString(16)}`);
14689
+ }
14690
+ return result;
14691
+ }
14692
+ function signedBigIntFromBytes(bytes) {
14693
+ if (bytes.length === 0) return 0n;
14694
+ let magnitude = 0n;
14695
+ for (const byte of bytes) magnitude = magnitude << 8n | BigInt(byte);
14696
+ const firstByte = bytes[0];
14697
+ return firstByte !== void 0 && (firstByte & 128) !== 0 ? magnitude - (1n << BigInt(8 * bytes.length)) : magnitude;
14698
+ }
14699
+ function decimalNumberFromUnscaled(unscaled, scale) {
14700
+ const isNegative = unscaled < 0n;
14701
+ const magnitudeDigits = (isNegative ? -unscaled : unscaled).toString();
14702
+ const sign = isNegative ? "-" : "";
14703
+ if (scale <= 0) return Number(`${sign}${magnitudeDigits}${"0".repeat(-scale)}`);
14704
+ const padded = magnitudeDigits.padStart(scale + 1, "0");
14705
+ const wholePart = padded.slice(0, padded.length - scale);
14706
+ const fractionPart = padded.slice(padded.length - scale);
14707
+ return Number(`${sign}${wholePart}.${fractionPart}`);
14708
+ }
14709
+ function pad2$1(n) {
14710
+ return String(n).padStart(2, "0");
14711
+ }
14712
+ function epochMillisToLocalDate(epochMillis) {
14713
+ return new Date(Number(epochMillis));
14714
+ }
14715
+ function formatLocalDate(epochMillis) {
14716
+ const date = epochMillisToLocalDate(epochMillis);
14717
+ return `${date.getFullYear()}-${pad2$1(date.getMonth() + 1)}-${pad2$1(date.getDate())}`;
14718
+ }
14719
+ function formatLocalTime(epochMillis) {
14720
+ const date = epochMillisToLocalDate(epochMillis);
14721
+ const base = `${pad2$1(date.getHours())}:${pad2$1(date.getMinutes())}:${pad2$1(date.getSeconds())}`;
14722
+ return date.getMilliseconds() === 0 ? base : `${base}.${String(date.getMilliseconds()).padStart(3, "0")}`;
14723
+ }
14724
+ function formatLocalTimestamp(epochMillis, nanos) {
14725
+ const date = epochMillisToLocalDate(epochMillis);
14726
+ const base = `${date.getFullYear()}-${pad2$1(date.getMonth() + 1)}-${pad2$1(date.getDate())} ${pad2$1(date.getHours())}:${pad2$1(date.getMinutes())}:${pad2$1(date.getSeconds())}`;
14727
+ return nanos === 0 ? base : `${base}.${String(nanos).padStart(9, "0")}`;
14728
+ }
14729
+ function readHsqldbColumnValue(cursor, typeCode) {
14730
+ if (cursor.readUint8() === 0) return { kind: "empty" };
14731
+ switch (typeCode) {
14732
+ case 1:
14733
+ case 12:
14734
+ case -1:
14735
+ case 100: {
14736
+ const byteLength = cursor.readInt32();
14737
+ return {
14738
+ kind: "string",
14739
+ value: readModifiedUtf8(cursor.readBytes(byteLength))
14740
+ };
14741
+ }
14742
+ case 5:
14743
+ case -6: return {
14744
+ kind: "number",
14745
+ value: cursor.readInt16()
14746
+ };
14747
+ case 4: return {
14748
+ kind: "number",
14749
+ value: cursor.readInt32()
14750
+ };
14751
+ case -5: return {
14752
+ kind: "number",
14753
+ value: Number(cursor.readBigInt64())
14754
+ };
14755
+ case 6:
14756
+ case 7:
14757
+ case 8: return {
14758
+ kind: "number",
14759
+ value: cursor.readFloat64()
14760
+ };
14761
+ case 2:
14762
+ case 3: {
14763
+ const byteLength = cursor.readInt32();
14764
+ const magnitudeBytes = cursor.readBytes(byteLength);
14765
+ const scale = cursor.readInt32();
14766
+ return {
14767
+ kind: "number",
14768
+ value: decimalNumberFromUnscaled(signedBigIntFromBytes(magnitudeBytes), scale)
14769
+ };
14770
+ }
14771
+ case 16: return {
14772
+ kind: "boolean",
14773
+ value: cursor.readUint8() !== 0
14774
+ };
14775
+ case 91: return {
14776
+ kind: "date",
14777
+ value: formatLocalDate(cursor.readBigInt64())
14778
+ };
14779
+ case 92: return {
14780
+ kind: "time",
14781
+ value: formatLocalTime(cursor.readBigInt64())
14782
+ };
14783
+ case 93: return {
14784
+ kind: "date",
14785
+ value: formatLocalTimestamp(cursor.readBigInt64(), cursor.readInt32())
14786
+ };
14787
+ default: throw new HsqldbRowFormatError(`unsupported SQL type code ${typeCode} while decoding a row value`);
14788
+ }
14789
+ }
14790
+ //#endregion
14791
+ //#region src/hsqldb/cache.ts
14792
+ const SUPPORTED_COMPATIBLE_VERSION_PREFIXES = ["1.7.", "1.8."];
14793
+ function parseHsqldbProperties(text) {
14794
+ const props = /* @__PURE__ */ new Map();
14795
+ for (const rawLine of text.split("\n")) {
14796
+ const line = rawLine.trim();
14797
+ if (line.length === 0 || line.startsWith("#")) continue;
14798
+ const eq = line.indexOf("=");
14799
+ if (eq === -1) continue;
14800
+ props.set(line.slice(0, eq).trim(), line.slice(eq + 1).trim());
14801
+ }
14802
+ const compatibleVersion = props.get("hsqldb.compatible_version");
14803
+ if (compatibleVersion !== void 0 && !SUPPORTED_COMPATIBLE_VERSION_PREFIXES.some((prefix) => compatibleVersion.startsWith(prefix))) throw new HsqldbRowFormatError(`database/properties declares hsqldb.compatible_version "${compatibleVersion}" -- this decoder is scoped to the HSQLDB 1.7.x/1.8.x CACHED-table row-store format (the version LibreOffice's own embedded driver ships) and does not know this version's own on-disk row-store layout`);
14804
+ return {
14805
+ cacheFileScale: Number(props.get("hsqldb.cache_file_scale") ?? "1") === 1 ? 1 : 8,
14806
+ compatibleVersion
14807
+ };
14808
+ }
14809
+ const SET_TABLE_INDEX_RE = /^SET\s+TABLE\s+("(?:[^"]|"")*"|[A-Za-z_][A-Za-z0-9_$#]*)\s+INDEX'((?:[^']|'')*)'\s*$/i;
14810
+ function unquoteIdentifier(raw) {
14811
+ if (raw.length >= 2 && raw.startsWith("\"") && raw.endsWith("\"")) return raw.slice(1, -1).replace(/""/g, "\"");
14812
+ return raw;
14813
+ }
14814
+ function parseHsqldbIndexRoots(scriptText) {
14815
+ const roots = /* @__PURE__ */ new Map();
14816
+ for (const rawLine of scriptText.split("\n")) {
14817
+ const match = SET_TABLE_INDEX_RE.exec(rawLine.trim());
14818
+ if (match === null) continue;
14819
+ const rawName = match[1] ?? "";
14820
+ const tokensText = match[2] ?? "";
14821
+ const tableName = unquoteIdentifier(rawName).toUpperCase();
14822
+ const tokens = tokensText.trim().length === 0 ? [] : tokensText.trim().split(/\s+/);
14823
+ if (tokens.length !== 2) throw new HsqldbRowFormatError(`table "${tableName}" declares ${Math.max(tokens.length - 1, 0)} index root(s) in its SET TABLE...INDEX line -- only a single-index (primary-key-only) CACHED table is supported`);
14824
+ const rootToken = tokens[0] ?? "";
14825
+ const rootPos = Number(rootToken);
14826
+ if (!Number.isInteger(rootPos)) throw new HsqldbRowFormatError(`table "${tableName}"'s SET TABLE...INDEX line has a non-integer root position "${rootToken}"`);
14827
+ roots.set(tableName, rootPos);
14828
+ }
14829
+ return roots;
14830
+ }
14831
+ function readHsqldbCachedTableRows(dataBytes, rootPos, cacheFileScale, columns) {
14832
+ const typeCodes = columns.map((column) => resolveHsqldbTypeCode(column.type));
14833
+ const results = [];
14834
+ function visit(pos) {
14835
+ if (pos <= 0) return;
14836
+ const byteOffset = pos * cacheFileScale;
14837
+ if (byteOffset < 0 || byteOffset + 4 > dataBytes.length) throw new HsqldbRowFormatError(`row position ${pos} (byte offset ${byteOffset}) falls outside database/data (${dataBytes.length} bytes)`);
14838
+ const cursor = new HsqldbDataCursor(dataBytes, byteOffset);
14839
+ const storageSize = cursor.readInt32();
14840
+ const rowEnd = byteOffset + storageSize;
14841
+ if (storageSize <= 0 || rowEnd > dataBytes.length) throw new HsqldbRowFormatError(`row at position ${pos} declares an invalid storage size ${storageSize}`);
14842
+ cursor.readInt32();
14843
+ const iLeft = cursor.readInt32();
14844
+ const iRight = cursor.readInt32();
14845
+ cursor.readInt32();
14846
+ const values = columns.map((_column, index) => {
14847
+ const typeCode = typeCodes[index];
14848
+ if (typeCode === void 0) throw new HsqldbRowFormatError("internal error: column/type-code alignment failure");
14849
+ return readHsqldbColumnValue(cursor, typeCode);
14850
+ });
14851
+ if (cursor.position > rowEnd) throw new HsqldbRowFormatError(`row at position ${pos} overran its own declared storage size (consumed ${cursor.position - byteOffset} bytes, declared ${storageSize})`);
14852
+ visit(iLeft);
14853
+ results.push(values);
14854
+ visit(iRight);
14855
+ }
14856
+ visit(rootPos);
14857
+ return results;
14858
+ }
14859
+ function decodeHsqldbCachedTables(tables, scriptText, dataBytes, propertiesText) {
14860
+ const { cacheFileScale } = parseHsqldbProperties(propertiesText);
14861
+ const roots = parseHsqldbIndexRoots(scriptText);
14862
+ return tables.map((table) => {
14863
+ const rootPos = roots.get(table.tableName.toUpperCase());
14864
+ if (rootPos === void 0) return table;
14865
+ const rows = readHsqldbCachedTableRows(dataBytes, rootPos, cacheFileScale, table.columns);
14866
+ return {
14867
+ ...table,
14868
+ rows
14869
+ };
14870
+ });
14871
+ }
14872
+ //#endregion
14873
+ //#region src/firebird/reader.ts
14874
+ var FirebirdBackupParseError = class extends Error {
14875
+ offset;
14876
+ constructor(message, offset) {
14877
+ super(`Firebird backup parse error at byte offset ${offset}: ${message}`);
14878
+ this.name = "FirebirdBackupParseError";
14879
+ this.offset = offset;
14880
+ }
14881
+ };
14882
+ var FirebirdBackupReader = class {
14883
+ bytes;
14884
+ position = 0;
14885
+ constructor(bytes) {
14886
+ this.bytes = bytes;
14887
+ }
14888
+ get offset() {
14889
+ return this.position;
14890
+ }
14891
+ atEnd() {
14892
+ return this.position >= this.bytes.length;
14893
+ }
14894
+ readTag() {
14895
+ const byte = this.bytes[this.position];
14896
+ if (byte === void 0) throw new FirebirdBackupParseError("unexpected end of stream reading a tag byte", this.position);
14897
+ this.position++;
14898
+ return byte;
14899
+ }
14900
+ peekTag() {
14901
+ return this.bytes[this.position];
14902
+ }
14903
+ readLengthByte() {
14904
+ const byte = this.bytes[this.position];
14905
+ if (byte === void 0) throw new FirebirdBackupParseError("unexpected end of stream reading an attribute length byte", this.position);
14906
+ this.position++;
14907
+ return byte;
14908
+ }
14909
+ readRawBytes(length) {
14910
+ if (this.position + length > this.bytes.length) throw new FirebirdBackupParseError(`unexpected end of stream reading ${length} raw byte(s)`, this.position);
14911
+ const slice = this.bytes.subarray(this.position, this.position + length);
14912
+ this.position += length;
14913
+ return slice;
14914
+ }
14915
+ readAttributeBytes() {
14916
+ const length = this.readLengthByte();
14917
+ return this.readRawBytes(length);
14918
+ }
14919
+ readInt32Attribute() {
14920
+ const bytes = this.readAttributeBytes();
14921
+ if (bytes.length !== 4) throw new FirebirdBackupParseError(`expected a 4-byte int32 attribute, found ${bytes.length} byte(s)`, this.position);
14922
+ return (bytes[0] ?? 0) | (bytes[1] ?? 0) << 8 | (bytes[2] ?? 0) << 16 | (bytes[3] ?? 0) << 24;
14923
+ }
14924
+ readTextAttribute() {
14925
+ const bytes = this.readAttributeBytes();
14926
+ return new TextDecoder("utf-8").decode(bytes);
14927
+ }
14928
+ skipAttributeValue() {
14929
+ this.readAttributeBytes();
14930
+ }
14931
+ skipFlatRecordAttributes() {
14932
+ for (;;) {
14933
+ if (this.readTag() === 0) return;
14934
+ this.skipAttributeValue();
14935
+ }
14936
+ }
14937
+ readRawPayload(length) {
14938
+ return this.readRawBytes(length);
14939
+ }
14940
+ readBlobSegmentLength() {
14941
+ return this.readLengthByte() | this.readLengthByte() << 8;
14942
+ }
14943
+ readSignedByte() {
14944
+ const byte = this.bytes[this.position];
14945
+ if (byte === void 0) throw new FirebirdBackupParseError("unexpected end of stream reading a compression control byte", this.position);
14946
+ this.position++;
14947
+ return byte >= 128 ? byte - 256 : byte;
14948
+ }
14949
+ readCompressedPayload(decompressedLength) {
14950
+ const output = new Uint8Array(decompressedLength);
14951
+ let written = 0;
14952
+ while (written < decompressedLength) {
14953
+ const count = this.readSignedByte();
14954
+ if (count > 0) {
14955
+ const remaining = decompressedLength - written;
14956
+ const take = Math.min(count, remaining);
14957
+ const literal = this.readRawBytes(take);
14958
+ output.set(literal, written);
14959
+ written += take;
14960
+ } else if (count < 0) {
14961
+ const repeatCount = Math.min(-count, decompressedLength - written);
14962
+ const fillByte = this.readLengthByte();
14963
+ output.fill(fillByte, written, written + repeatCount);
14964
+ written += repeatCount;
14965
+ }
14966
+ }
14967
+ return output;
14968
+ }
14969
+ };
14970
+ var XdrReader = class {
14971
+ bytes;
14972
+ position;
14973
+ end;
14974
+ constructor(bytes, start = 0, end = bytes.length) {
14975
+ this.bytes = bytes;
14976
+ this.position = start;
14977
+ this.end = end;
14978
+ }
14979
+ get offset() {
14980
+ return this.position;
14981
+ }
14982
+ atEnd() {
14983
+ return this.position >= this.end;
14984
+ }
14985
+ readInt32() {
14986
+ if (this.position + 4 > this.end) throw new FirebirdBackupParseError("unexpected end of XDR data reading a 4-byte integer", this.position);
14987
+ const b0 = this.bytes[this.position] ?? 0;
14988
+ const b1 = this.bytes[this.position + 1] ?? 0;
14989
+ const b2 = this.bytes[this.position + 2] ?? 0;
14990
+ const b3 = this.bytes[this.position + 3] ?? 0;
14991
+ this.position += 4;
14992
+ return b0 << 24 | b1 << 16 | b2 << 8 | b3 | 0;
14993
+ }
14994
+ readInt16() {
14995
+ return this.readInt32() << 16 >> 16;
14996
+ }
14997
+ readInt64() {
14998
+ const high = this.readInt32();
14999
+ const low = this.readInt32();
15000
+ return BigInt(high) << 32n | BigInt(low) & 4294967295n;
15001
+ }
15002
+ readDouble() {
15003
+ if (this.position + 8 > this.end) throw new FirebirdBackupParseError("unexpected end of XDR data reading an 8-byte double", this.position);
15004
+ const view = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8));
15005
+ for (let i = 0; i < 8; i++) view.setUint8(i, this.bytes[this.position + i] ?? 0);
15006
+ this.position += 8;
15007
+ return view.getFloat64(0, false);
15008
+ }
15009
+ readFloat() {
15010
+ if (this.position + 4 > this.end) throw new FirebirdBackupParseError("unexpected end of XDR data reading a 4-byte float", this.position);
15011
+ const view = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(4));
15012
+ for (let i = 0; i < 4; i++) view.setUint8(i, this.bytes[this.position + i] ?? 0);
15013
+ this.position += 4;
15014
+ return view.getFloat32(0, false);
15015
+ }
15016
+ readOpaque(len) {
15017
+ if (this.position + len > this.end) throw new FirebirdBackupParseError(`unexpected end of XDR data reading ${len} opaque byte(s)`, this.position);
15018
+ const slice = this.bytes.subarray(this.position, this.position + len);
15019
+ this.position += len;
15020
+ const padding = (4 - len % 4) % 4;
15021
+ this.position += padding;
15022
+ return slice;
15023
+ }
15024
+ };
15025
+ const BLR_TO_PHYSICAL_TYPE = /* @__PURE__ */ new Map([
15026
+ [7, "short"],
15027
+ [8, "long"],
15028
+ [9, "quad"],
15029
+ [10, "real"],
15030
+ [11, "double"],
15031
+ [12, "sql_date"],
15032
+ [13, "sql_time"],
15033
+ [14, "text"],
15034
+ [15, "text"],
15035
+ [16, "int64"],
15036
+ [23, "boolean"],
15037
+ [24, "dec64"],
15038
+ [25, "dec128"],
15039
+ [26, "int128"],
15040
+ [27, "double"],
15041
+ [28, "unsupported-tz"],
15042
+ [29, "unsupported-tz"],
15043
+ [30, "unsupported-tz"],
15044
+ [31, "unsupported-tz"],
15045
+ [35, "timestamp"],
15046
+ [37, "varying"],
15047
+ [38, "varying"],
15048
+ [40, "cstring"],
15049
+ [41, "cstring"],
15050
+ [261, "blob"]
15051
+ ]);
15052
+ var FirebirdUnsupportedFieldTypeError = class extends Error {
15053
+ blrType;
15054
+ constructor(blrType) {
15055
+ super(`Firebird backup: field has BLR type ${blrType}, which is not a recognised column datatype opcode for a Firebird-embedded .odb's own user/system tables`);
15056
+ this.name = "FirebirdUnsupportedFieldTypeError";
15057
+ this.blrType = blrType;
15058
+ }
15059
+ };
15060
+ function decodeBlrType(blrType) {
15061
+ const physical = BLR_TO_PHYSICAL_TYPE.get(blrType);
15062
+ if (physical === void 0) throw new FirebirdUnsupportedFieldTypeError(blrType);
15063
+ return physical;
15064
+ }
15065
+ function describeFieldType(physical, lengthBytes, scale, characterLength) {
15066
+ switch (physical) {
15067
+ case "short": return scale === 0 ? "SMALLINT" : `NUMERIC(4,${-scale})`;
15068
+ case "long": return scale === 0 ? "INTEGER" : `NUMERIC(9,${-scale})`;
15069
+ case "int64": return scale === 0 ? "BIGINT" : `NUMERIC(18,${-scale})`;
15070
+ case "real": return "FLOAT";
15071
+ case "double": return "DOUBLE PRECISION";
15072
+ case "sql_date": return "DATE";
15073
+ case "sql_time": return "TIME";
15074
+ case "timestamp": return "TIMESTAMP";
15075
+ case "text": return `CHAR(${characterLength ?? lengthBytes})`;
15076
+ case "varying": return `VARCHAR(${characterLength ?? lengthBytes})`;
15077
+ case "cstring": return `CSTRING(${characterLength ?? lengthBytes})`;
15078
+ case "boolean": return "BOOLEAN";
15079
+ case "blob": return "BLOB";
15080
+ case "quad": return "ARRAY";
15081
+ case "int128": return `NUMERIC(38,${-scale})`;
15082
+ case "dec64": return "DECFLOAT(16)";
15083
+ case "dec128": return "DECFLOAT(34)";
15084
+ case "unsupported-tz": return "TIMESTAMP/TIME WITH TIME ZONE";
15085
+ }
15086
+ }
15087
+ //#endregion
15088
+ //#region src/firebird/schema.ts
15089
+ const REC_FIELD = 4;
15090
+ const REC_RELATION_END$1 = 9;
15091
+ var FirebirdSchemaParseError = class extends Error {
15092
+ constructor(message) {
15093
+ super(`Firebird backup schema parse error: ${message}`);
15094
+ this.name = "FirebirdSchemaParseError";
15095
+ }
15096
+ };
15097
+ const ATT_RELATION_NAME$1 = 1;
15098
+ const ATT_FIELD_NAME = 1;
15099
+ const ATT_FIELD_TYPE = 8;
15100
+ const ATT_FIELD_LENGTH = 10;
15101
+ const ATT_FIELD_SCALE = 11;
15102
+ const ATT_FIELD_COMPUTED_FLAG = 23;
15103
+ const ATT_FIELD_CHARACTER_LENGTH = 41;
15104
+ function readField(reader) {
15105
+ let name;
15106
+ let blrType;
15107
+ let lengthBytes = 0;
15108
+ let scale = 0;
15109
+ let characterLength;
15110
+ let computed = false;
15111
+ for (;;) {
15112
+ const attribute = reader.readTag();
15113
+ if (attribute === 0) break;
15114
+ switch (attribute) {
15115
+ case ATT_FIELD_NAME:
15116
+ name = reader.readTextAttribute();
15117
+ break;
15118
+ case ATT_FIELD_TYPE:
15119
+ blrType = reader.readInt32Attribute();
15120
+ break;
15121
+ case ATT_FIELD_LENGTH:
15122
+ lengthBytes = reader.readInt32Attribute();
15123
+ break;
15124
+ case ATT_FIELD_SCALE:
15125
+ scale = reader.readInt32Attribute();
15126
+ break;
15127
+ case ATT_FIELD_CHARACTER_LENGTH:
15128
+ characterLength = reader.readInt32Attribute();
15129
+ break;
15130
+ case ATT_FIELD_COMPUTED_FLAG:
15131
+ computed = reader.readInt32Attribute() !== 0;
15132
+ break;
15133
+ default: reader.skipAttributeValue();
15134
+ }
15135
+ }
15136
+ if (name === void 0) throw new FirebirdSchemaParseError("a rec_field record had no att_field_name attribute");
15137
+ if (blrType === void 0) throw new FirebirdSchemaParseError(`field "${name}" had no att_field_type attribute`);
15138
+ const physicalType = decodeBlrType(blrType);
15139
+ const typeLabel = describeFieldType(physicalType, lengthBytes, scale, characterLength);
15140
+ return {
15141
+ name,
15142
+ physicalType,
15143
+ lengthBytes,
15144
+ scale,
15145
+ characterLength,
15146
+ typeLabel,
15147
+ computed
15148
+ };
15149
+ }
15150
+ function readRelationSchema(reader, onUnhandledNested) {
15151
+ let name;
15152
+ for (;;) {
15153
+ const attribute = reader.readTag();
15154
+ if (attribute === 0) break;
15155
+ if (attribute === ATT_RELATION_NAME$1) name = reader.readTextAttribute();
15156
+ else reader.skipAttributeValue();
15157
+ }
15158
+ if (name === void 0) throw new FirebirdSchemaParseError("a rec_relation record had no att_relation_name attribute");
15159
+ const fields = [];
15160
+ for (;;) {
15161
+ const recordType = reader.readTag();
15162
+ if (recordType === REC_RELATION_END$1) break;
15163
+ if (recordType === REC_FIELD) {
15164
+ fields.push(readField(reader));
15165
+ continue;
15166
+ }
15167
+ onUnhandledNested(recordType);
15168
+ }
15169
+ return {
15170
+ name,
15171
+ fields
15172
+ };
15173
+ }
15174
+ //#endregion
15175
+ //#region src/firebird/date.ts
15176
+ const ISC_TIME_SECONDS_PRECISION = 1e4;
15177
+ function decodeFirebirdDate(days) {
15178
+ let nday = days + 2400001 - 1721119;
15179
+ const century = Math.floor((4 * nday - 1) / 146097);
15180
+ nday = 4 * nday - 1 - 146097 * century;
15181
+ let day = Math.floor(nday / 4);
15182
+ nday = Math.floor((4 * day + 3) / 1461);
15183
+ day = 4 * day + 3 - 1461 * nday;
15184
+ day = Math.floor((day + 4) / 4);
15185
+ let month = Math.floor((5 * day - 3) / 153);
15186
+ day = 5 * day - 3 - 153 * month;
15187
+ day = Math.floor((day + 5) / 5);
15188
+ let year = 100 * century + nday;
15189
+ if (month < 10) month += 3;
15190
+ else {
15191
+ month -= 9;
15192
+ year += 1;
15193
+ }
15194
+ return {
15195
+ year,
15196
+ month,
15197
+ day
15198
+ };
15199
+ }
15200
+ function decodeFirebirdTime(ticks) {
15201
+ let remaining = ticks;
15202
+ const hours = Math.floor(remaining / (3600 * ISC_TIME_SECONDS_PRECISION));
15203
+ remaining %= 3600 * ISC_TIME_SECONDS_PRECISION;
15204
+ const minutes = Math.floor(remaining / (60 * ISC_TIME_SECONDS_PRECISION));
15205
+ remaining %= 60 * ISC_TIME_SECONDS_PRECISION;
15206
+ return {
15207
+ hours,
15208
+ minutes,
15209
+ seconds: Math.floor(remaining / ISC_TIME_SECONDS_PRECISION),
15210
+ fractions: remaining % ISC_TIME_SECONDS_PRECISION
15211
+ };
15212
+ }
15213
+ function pad2(value) {
15214
+ return String(value).padStart(2, "0");
15215
+ }
15216
+ function pad4(value) {
15217
+ return String(value).padStart(4, "0");
15218
+ }
15219
+ function formatFirebirdDate(days) {
15220
+ const { year, month, day } = decodeFirebirdDate(days);
15221
+ return `${pad4(year)}-${pad2(month)}-${pad2(day)}`;
15222
+ }
15223
+ function formatFirebirdTime(ticks) {
15224
+ const { hours, minutes, seconds, fractions } = decodeFirebirdTime(ticks);
15225
+ const millis = Math.round(fractions / 10);
15226
+ return `${pad2(hours)}:${pad2(minutes)}:${pad2(seconds)}.${String(millis).padStart(3, "0")}`;
15227
+ }
15228
+ function formatFirebirdTimestamp(days, ticks) {
15229
+ return `${formatFirebirdDate(days)} ${formatFirebirdTime(ticks)}`;
15230
+ }
15231
+ //#endregion
15232
+ //#region src/firebird/data.ts
15233
+ const REC_DATA = 6;
15234
+ const REC_BLOB = 7;
15235
+ const REC_RELATION_END = 9;
15236
+ const REC_GEN_ID = 18;
15237
+ const REC_INDEX = 5;
15238
+ const REC_TRIGGER = 13;
15239
+ const ATT_RELATION_NAME = 1;
15240
+ const ATT_DATA_LENGTH = 1;
15241
+ const ATT_DATA_DATA = 2;
15242
+ const ATT_XDR_LENGTH = 17;
15243
+ var FirebirdDataParseError = class extends Error {
15244
+ constructor(message) {
15245
+ super(`Firebird backup data parse error: ${message}`);
15246
+ this.name = "FirebirdDataParseError";
15247
+ }
15248
+ };
15249
+ var FirebirdCompositeRecordUnsupportedError = class extends Error {
15250
+ recordType;
15251
+ constructor(recordType, context) {
15252
+ super(`Firebird backup: encountered record type ${recordType} while ${context}, which this reader's own bounded implementation does not know how to skip safely (its own attribute/sub-record shape has not been verified against a real fixture) -- refusing to guess rather than risk silently desynchronising the rest of the stream`);
15253
+ this.name = "FirebirdCompositeRecordUnsupportedError";
15254
+ this.recordType = recordType;
15255
+ }
15256
+ };
15257
+ function skipBlobRecord(reader) {
15258
+ let segmentCount;
15259
+ for (;;) {
15260
+ const attribute = reader.readTag();
15261
+ if (attribute === 0) break;
15262
+ if (attribute === 5) segmentCount = reader.readInt32Attribute();
15263
+ else if (attribute === 7) {
15264
+ const count = segmentCount ?? 0;
15265
+ for (let i = 0; i < count; i++) {
15266
+ const length = reader.readBlobSegmentLength();
15267
+ reader.readRawPayload(length);
15268
+ }
15269
+ } else reader.skipAttributeValue();
15270
+ }
15271
+ }
15272
+ function decodeRowValues(fields, payload) {
15273
+ const storedFields = fields.filter((field) => !field.computed);
15274
+ const xdr = new XdrReader(payload);
15275
+ const rawValues = [];
15276
+ for (const field of storedFields) switch (field.physicalType) {
15277
+ case "short":
15278
+ rawValues.push({
15279
+ kind: "number",
15280
+ value: field.scale === 0 ? xdr.readInt16() : xdr.readInt16() * 10 ** field.scale
15281
+ });
15282
+ break;
15283
+ case "long":
15284
+ rawValues.push({
15285
+ kind: "number",
15286
+ value: field.scale === 0 ? xdr.readInt32() : xdr.readInt32() * 10 ** field.scale
15287
+ });
15288
+ break;
15289
+ case "int64": {
15290
+ const raw = xdr.readInt64();
15291
+ const scaled = field.scale === 0 ? Number(raw) : Number(raw) * 10 ** field.scale;
15292
+ rawValues.push({
15293
+ kind: "number",
15294
+ value: scaled
15295
+ });
15296
+ break;
15297
+ }
15298
+ case "real":
15299
+ rawValues.push({
15300
+ kind: "number",
15301
+ value: xdr.readFloat()
15302
+ });
15303
+ break;
15304
+ case "double":
15305
+ rawValues.push({
15306
+ kind: "number",
15307
+ value: xdr.readDouble()
15308
+ });
15309
+ break;
15310
+ case "sql_date": {
15311
+ const days = xdr.readInt32();
15312
+ rawValues.push({
15313
+ kind: "date",
15314
+ value: formatFirebirdDate(days)
15315
+ });
15316
+ break;
15317
+ }
15318
+ case "sql_time": {
15319
+ const ticks = xdr.readInt32() >>> 0;
15320
+ rawValues.push({
15321
+ kind: "time",
15322
+ value: formatFirebirdTime(ticks)
15323
+ });
15324
+ break;
15325
+ }
15326
+ case "timestamp": {
15327
+ const days = xdr.readInt32();
15328
+ const ticks = xdr.readInt32() >>> 0;
15329
+ rawValues.push({
15330
+ kind: "date",
15331
+ value: formatFirebirdTimestamp(days, ticks)
15332
+ });
15333
+ break;
15334
+ }
15335
+ case "text": {
15336
+ const bytes = xdr.readOpaque(field.lengthBytes);
15337
+ rawValues.push({
15338
+ kind: "string",
15339
+ value: new TextDecoder("utf-8").decode(bytes).replace(/\s+$/, "")
15340
+ });
15341
+ break;
15342
+ }
15343
+ case "varying": {
15344
+ const stringLength = xdr.readInt16();
15345
+ const bytes = xdr.readOpaque(stringLength);
15346
+ rawValues.push({
15347
+ kind: "string",
15348
+ value: new TextDecoder("utf-8").decode(bytes)
15349
+ });
15350
+ break;
15351
+ }
15352
+ case "cstring": {
15353
+ const stringLength = xdr.readInt16();
15354
+ const bytes = xdr.readOpaque(stringLength);
15355
+ rawValues.push({
15356
+ kind: "string",
15357
+ value: new TextDecoder("utf-8").decode(bytes)
15358
+ });
15359
+ break;
15360
+ }
15361
+ case "boolean": {
15362
+ const bytes = xdr.readOpaque(field.lengthBytes);
15363
+ rawValues.push({
15364
+ kind: "boolean",
15365
+ value: (bytes[0] ?? 0) !== 0
15366
+ });
15367
+ break;
15368
+ }
15369
+ case "blob":
15370
+ xdr.readInt32();
15371
+ xdr.readInt32();
15372
+ rawValues.push({ kind: "empty" });
15373
+ break;
15374
+ case "quad":
15375
+ xdr.readInt32();
15376
+ xdr.readInt32();
15377
+ rawValues.push({ kind: "empty" });
15378
+ break;
15379
+ case "int128":
15380
+ case "dec64":
15381
+ case "dec128":
15382
+ case "unsupported-tz": throw new FirebirdDataParseError(`column "${field.name}" has physical type "${field.physicalType}", which this reader's own bounded implementation does not decode (FB4+-only types not exercised by this reader's Firebird 3.0-era real fixture) -- see the README's .odb Tier 3 Fidelity note`);
15383
+ }
15384
+ for (let i = 0; i < storedFields.length; i++) if (xdr.readInt16() !== 0) rawValues[i] = { kind: "empty" };
15385
+ return rawValues.map((value) => value ?? { kind: "empty" });
15386
+ }
15387
+ function readRowGroup(reader, relation, compressed) {
15388
+ const rows = [];
15389
+ let terminator;
15390
+ for (;;) {
15391
+ const lengthTag = reader.readTag();
15392
+ if (lengthTag !== ATT_DATA_LENGTH) throw new FirebirdDataParseError(`relation "${relation.name}": expected att_data_length (tag ${ATT_DATA_LENGTH}), found tag ${lengthTag}`);
15393
+ let xdrLength = reader.readInt32Attribute();
15394
+ const maybeXdrTag = reader.readTag();
15395
+ if (maybeXdrTag === ATT_XDR_LENGTH) xdrLength = reader.readInt32Attribute();
15396
+ else if (maybeXdrTag !== ATT_DATA_DATA) throw new FirebirdDataParseError(`relation "${relation.name}": expected att_xdr_length or att_data_data, found tag ${maybeXdrTag}`);
15397
+ if (maybeXdrTag !== ATT_DATA_DATA) {
15398
+ const dataTag = reader.readTag();
15399
+ if (dataTag !== ATT_DATA_DATA) throw new FirebirdDataParseError(`relation "${relation.name}": expected att_data_data (tag ${ATT_DATA_DATA}), found tag ${dataTag}`);
15400
+ }
15401
+ const payload = compressed ? reader.readCompressedPayload(xdrLength) : reader.readRawPayload(xdrLength);
15402
+ rows.push(decodeRowValues(relation.fields, payload));
15403
+ let next = reader.readTag();
15404
+ while (next === REC_BLOB) {
15405
+ skipBlobRecord(reader);
15406
+ next = reader.readTag();
15407
+ }
15408
+ if (next !== REC_DATA) {
15409
+ terminator = next;
15410
+ break;
15411
+ }
15412
+ }
15413
+ return {
15414
+ rows,
15415
+ terminator
15416
+ };
15417
+ }
15418
+ function readRelationData(reader, schema, compressed) {
15419
+ let name;
15420
+ for (;;) {
15421
+ const attribute = reader.readTag();
15422
+ if (attribute === 0) break;
15423
+ if (attribute === ATT_RELATION_NAME) name = reader.readTextAttribute();
15424
+ else reader.skipAttributeValue();
15425
+ }
15426
+ if (name === void 0) throw new FirebirdDataParseError("a rec_relation_data record had no att_relation_name attribute");
15427
+ const relation = schema.get(name);
15428
+ if (relation === void 0) throw new FirebirdDataParseError(`rec_relation_data references relation "${name}", which no earlier rec_relation declared`);
15429
+ const rows = [];
15430
+ let recordType = reader.readTag();
15431
+ for (;;) {
15432
+ if (recordType === REC_RELATION_END) break;
15433
+ if (recordType === REC_DATA) {
15434
+ const group = readRowGroup(reader, relation, compressed);
15435
+ rows.push(...group.rows);
15436
+ recordType = group.terminator;
15437
+ continue;
15438
+ }
15439
+ if (recordType === REC_GEN_ID) {
15440
+ reader.readAttributeBytes();
15441
+ recordType = reader.readTag();
15442
+ continue;
15443
+ }
15444
+ if (recordType === REC_INDEX || recordType === REC_TRIGGER) {
15445
+ reader.skipFlatRecordAttributes();
15446
+ recordType = reader.readTag();
15447
+ continue;
15448
+ }
15449
+ throw new FirebirdCompositeRecordUnsupportedError(recordType, `reading relation data for "${name}"`);
15450
+ }
15451
+ return {
15452
+ relationName: name,
15453
+ rows
15454
+ };
15455
+ }
15456
+ //#endregion
15457
+ //#region src/firebird/backup.ts
15458
+ const REC_DATABASE = 1;
15459
+ const REC_RELATION = 3;
15460
+ const REC_RELATION_DATA = 8;
15461
+ const REC_END = 10;
15462
+ const REC_PHYSICAL_DB = 14;
15463
+ const FLAT_SKIPPABLE_RECORD_TYPES = /* @__PURE__ */ new Set([
15464
+ 2,
15465
+ 24,
15466
+ 31,
15467
+ 32,
15468
+ 33,
15469
+ 34,
15470
+ 35,
15471
+ 19,
15472
+ 20,
15473
+ 26,
15474
+ 12,
15475
+ 25,
15476
+ 36,
15477
+ 37,
15478
+ 39,
15479
+ 21,
15480
+ 22,
15481
+ 40,
15482
+ 41,
15483
+ 42,
15484
+ 43
15485
+ ]);
15486
+ var FirebirdBackupFormatError = class extends Error {
15487
+ constructor(message) {
15488
+ super(`Firebird backup: ${message}`);
15489
+ this.name = "FirebirdBackupFormatError";
15490
+ }
15491
+ };
15492
+ const ATT_BACKUP_FORMAT = 2;
15493
+ const ATT_BACKUP_COMPRESS = 4;
15494
+ const ATT_BACKUP_TRANSPORTABLE = 5;
15495
+ const ATT_PAGE_SIZE = 5;
15496
+ function readBurpHeader(reader) {
15497
+ let backupFormatVersion;
15498
+ let transportable = false;
15499
+ let compressed = false;
15500
+ for (;;) {
15501
+ const attribute = reader.readTag();
15502
+ if (attribute === 0) break;
15503
+ switch (attribute) {
15504
+ case ATT_BACKUP_FORMAT:
15505
+ backupFormatVersion = reader.readInt32Attribute();
15506
+ break;
15507
+ case ATT_BACKUP_TRANSPORTABLE:
15508
+ transportable = reader.readInt32Attribute() !== 0;
15509
+ break;
15510
+ case ATT_BACKUP_COMPRESS:
15511
+ compressed = reader.readInt32Attribute() !== 0;
15512
+ break;
15513
+ default: reader.skipAttributeValue();
15514
+ }
15515
+ }
15516
+ if (backupFormatVersion === void 0) throw new FirebirdBackupFormatError("the leading rec_burp record had no att_backup_format attribute -- not a recognisable gbak backup stream");
15517
+ return {
15518
+ backupFormatVersion,
15519
+ transportable,
15520
+ compressed
15521
+ };
15522
+ }
15523
+ function readDatabaseHeader(reader) {
15524
+ let pageSizeBytes;
15525
+ for (;;) {
15526
+ const attribute = reader.readTag();
15527
+ if (attribute === 0) break;
15528
+ if (attribute === ATT_PAGE_SIZE) pageSizeBytes = reader.readInt32Attribute();
15529
+ else reader.skipAttributeValue();
15530
+ }
15531
+ return { pageSizeBytes };
15532
+ }
15533
+ const SUPPORTED_BACKUP_FORMAT_VERSION = 10;
15534
+ function relationToColumns(relation) {
15535
+ return relation.fields.filter((field) => !field.computed).map((field) => ({
15536
+ name: field.name,
15537
+ type: field.typeLabel
15538
+ }));
15539
+ }
15540
+ function readFirebirdBackup(bytes) {
15541
+ const reader = new FirebirdBackupReader(bytes);
15542
+ const leadingRecordType = reader.readTag();
15543
+ if (leadingRecordType !== 0) throw new FirebirdBackupFormatError(`expected the stream to open with rec_burp (tag 0), found tag ${leadingRecordType} -- not a recognisable gbak backup stream`);
15544
+ const { backupFormatVersion, transportable, compressed } = readBurpHeader(reader);
15545
+ if (backupFormatVersion !== 10) throw new FirebirdBackupFormatError(`backup format version ${backupFormatVersion} is not supported -- this reader has only been built and verified against format version 10 (Firebird 3.0-era gbak output). Refusing to guess at a different format's own attribute/record shape rather than risk silently misdecoding it.`);
15546
+ if (!transportable) throw new FirebirdBackupFormatError("backup is in non-transportable (native binary) row format (att_backup_transportable=false) -- this reader only decodes the transportable/XDR row encoding, the one every real fixture it was built against actually uses (gbak's own default).");
15547
+ let pageSizeBytes;
15548
+ const schema = /* @__PURE__ */ new Map();
15549
+ const tablesInOrder = [];
15550
+ const rowsByRelation = /* @__PURE__ */ new Map();
15551
+ for (;;) {
15552
+ const recordType = reader.readTag();
15553
+ if (recordType === REC_END) break;
15554
+ if (recordType === REC_DATABASE || recordType === REC_PHYSICAL_DB) {
15555
+ pageSizeBytes = readDatabaseHeader(reader).pageSizeBytes ?? pageSizeBytes;
15556
+ continue;
15557
+ }
15558
+ if (recordType === REC_RELATION) {
15559
+ const relation = readRelationSchema(reader, (nestedRecordType) => {
15560
+ throw new FirebirdCompositeRecordUnsupportedError(nestedRecordType, "reading a relation's own schema (a rec_view child, most likely)");
15561
+ });
15562
+ schema.set(relation.name, relation);
15563
+ tablesInOrder.push(relation.name);
15564
+ continue;
15565
+ }
15566
+ if (recordType === REC_RELATION_DATA) {
15567
+ const result = readRelationData(reader, schema, compressed);
15568
+ rowsByRelation.set(result.relationName, result.rows);
15569
+ continue;
15570
+ }
15571
+ if (FLAT_SKIPPABLE_RECORD_TYPES.has(recordType)) {
15572
+ reader.skipFlatRecordAttributes();
15573
+ continue;
15574
+ }
15575
+ throw new FirebirdCompositeRecordUnsupportedError(recordType, "walking the backup stream's own top-level record sequence");
15576
+ }
15577
+ const tables = tablesInOrder.map((name) => {
15578
+ const relation = schema.get(name);
15579
+ if (relation === void 0) throw new FirebirdBackupFormatError(`internal error: relation "${name}" missing from its own schema map`);
15580
+ const rows = rowsByRelation.get(name) ?? [];
15581
+ return {
15582
+ tableName: relation.name,
15583
+ columns: relationToColumns(relation),
15584
+ rows
15585
+ };
15586
+ });
15587
+ return {
15588
+ summary: {
15589
+ backupFormatVersion,
15590
+ transportable,
15591
+ compressed,
15592
+ pageSizeBytes
15593
+ },
15594
+ tables
15595
+ };
15596
+ }
15597
+ //#endregion
14574
15598
  //#region src/odb/read.ts
14575
15599
  var OdbNoEmbeddedDataSourceError = class extends Error {
14576
15600
  url;
@@ -14589,12 +15613,21 @@ var OdbUnsupportedFormatError = class extends Error {
14589
15613
  }
14590
15614
  };
14591
15615
  const DATABASE_SCRIPT_PART = "database/script";
15616
+ const DATABASE_DATA_PART = "database/data";
15617
+ const DATABASE_PROPERTIES_PART = "database/properties";
15618
+ const DATABASE_FIREBIRD_PART = "database/firebird.fbk";
14592
15619
  function isXmlMediaType(mediaType) {
14593
15620
  return mediaType === "text/xml" || mediaType === "application/xml" || mediaType.endsWith("+xml");
14594
15621
  }
14595
- const GZIP_MAGIC = [31, 139];
15622
+ function isZlibHeader(bytes) {
15623
+ if (bytes.length < 2) return false;
15624
+ const cmf = bytes[0];
15625
+ const flg = bytes[1];
15626
+ if (cmf === void 0 || flg === void 0) return false;
15627
+ return (cmf & 15) === 8 && (cmf * 256 + flg) % 31 === 0;
15628
+ }
14596
15629
  function classifyScriptBytes(bytes) {
14597
- if (bytes.length >= GZIP_MAGIC.length && bytes[0] === GZIP_MAGIC[0] && bytes[1] === GZIP_MAGIC[1]) return "compressed";
15630
+ if (isZlibHeader(bytes)) return "compressed";
14598
15631
  for (const byte of bytes) if (byte < 32 && byte !== 9 && byte !== 10 && byte !== 13) return "binary";
14599
15632
  try {
14600
15633
  new TextDecoder("utf-8", { fatal: true }).decode(bytes);
@@ -14609,18 +15642,32 @@ function readOdbTables(pkg) {
14609
15642
  const url = inventory.connection.url;
14610
15643
  if (url === void 0) throw new OdbUnsupportedFormatError("unrecognised-engine", "an embedded connection with no connection url to identify its engine");
14611
15644
  const engine = url.slice(14);
14612
- if (engine === "firebird") throw new OdbUnsupportedFormatError("firebird", `Firebird's embedded database engine ("${url}")`);
15645
+ if (engine === "firebird") {
15646
+ const firebirdPart = pkg.parts[DATABASE_FIREBIRD_PART];
15647
+ if (firebirdPart === void 0) throw new OdbUnsupportedFormatError("unrecognised-engine", `an embedded Firebird engine with no ${DATABASE_FIREBIRD_PART} part -- an unrecognised embedded storage shape`);
15648
+ if (firebirdPart.kind !== "binary") throw new Error(`readOdbTables: ${DATABASE_FIREBIRD_PART} is not a binary part (found kind "${firebirdPart.kind}") -- malformed .odb package`);
15649
+ return readFirebirdBackup((0, odf_js.base64ToBytes)(firebirdPart.base64)).tables;
15650
+ }
14613
15651
  if (engine !== "hsqldb") throw new OdbUnsupportedFormatError("unrecognised-engine", `the embedded "${engine}" database engine`);
14614
15652
  const manifestEntry = (0, odf_js.readManifest)(pkg).entries.find((entry) => entry.fullPath === DATABASE_SCRIPT_PART);
14615
15653
  if (manifestEntry !== void 0 && isXmlMediaType(manifestEntry.mediaType)) throw new Error(`readOdbTables: ${DATABASE_SCRIPT_PART} is declared as an XML sub-document in the manifest (media type "${manifestEntry.mediaType}") -- not a recognised HSQLDB script part`);
14616
15654
  const scriptPart = pkg.parts[DATABASE_SCRIPT_PART];
14617
- if (scriptPart === void 0) throw new OdbUnsupportedFormatError("unrecognised-engine", `an embedded HSQLDB engine with no ${DATABASE_SCRIPT_PART} part -- binary HSQLDB cache-only storage, or an unrecognised embedded storage shape`);
15655
+ if (scriptPart === void 0) throw new OdbUnsupportedFormatError("unrecognised-engine", `an embedded HSQLDB engine with no ${DATABASE_SCRIPT_PART} part -- an unrecognised embedded storage shape`);
14618
15656
  if (scriptPart.kind !== "binary") throw new Error(`readOdbTables: ${DATABASE_SCRIPT_PART} is not a binary part (found kind "${scriptPart.kind}") -- malformed .odb package`);
14619
15657
  const scriptBytes = (0, odf_js.base64ToBytes)(scriptPart.base64);
14620
15658
  const classification = classifyScriptBytes(scriptBytes);
14621
- if (classification === "compressed") throw new OdbUnsupportedFormatError("hsqldb-compressed", "HSQLDB's compressed script format (hsqldb.script_format=3)");
14622
- if (classification === "binary") throw new OdbUnsupportedFormatError("hsqldb-binary", "HSQLDB's binary script format (hsqldb.script_format=1)");
14623
- return parseHsqldbScript(scriptBytes);
15659
+ if (classification === "compressed") throw new OdbUnsupportedFormatError("hsqldb-compressed", "HSQLDB's compressed whole-script format (hsqldb.script_format=3) -- a zlib-wrapped copy of the same length-prefixed binary DDL/DML statement encoding hsqldb.script_format=1 uses, not compressed SQL text");
15660
+ if (classification === "binary") throw new OdbUnsupportedFormatError("hsqldb-binary", "HSQLDB's binary whole-script format (hsqldb.script_format=1) -- a length-prefixed, COMMAND-tagged binary encoding of the script's own DDL/DML statements themselves, a materially different and larger undertaking than CACHED-table row-store decoding (Tier 2)");
15661
+ return withCachedTableRows(pkg, parseHsqldbScript(scriptBytes), scriptBytes);
15662
+ }
15663
+ function withCachedTableRows(pkg, tables, scriptBytes) {
15664
+ const dataPart = pkg.parts[DATABASE_DATA_PART];
15665
+ if (dataPart === void 0) return tables;
15666
+ if (dataPart.kind !== "binary") throw new Error(`readOdbTables: ${DATABASE_DATA_PART} is not a binary part (found kind "${dataPart.kind}") -- malformed .odb package`);
15667
+ const propertiesPart = pkg.parts[DATABASE_PROPERTIES_PART];
15668
+ if (propertiesPart === void 0) throw new Error(`readOdbTables: ${DATABASE_DATA_PART} is present but ${DATABASE_PROPERTIES_PART} is not -- malformed .odb package (a CACHED-table row store always ships alongside its own properties file, which this decoder needs for the cache file's own scale)`);
15669
+ if (propertiesPart.kind !== "binary") throw new Error(`readOdbTables: ${DATABASE_PROPERTIES_PART} is not a binary part (found kind "${propertiesPart.kind}") -- malformed .odb package`);
15670
+ return decodeHsqldbCachedTables(tables, new TextDecoder("utf-8", { fatal: true }).decode(scriptBytes), (0, odf_js.base64ToBytes)(dataPart.base64), new TextDecoder("utf-8", { fatal: true }).decode((0, odf_js.base64ToBytes)(propertiesPart.base64)));
14624
15671
  }
14625
15672
  //#endregion
14626
15673
  //#region src/odb/spreadsheet.ts
@@ -15704,6 +16751,14 @@ exports.DocxRun = DocxRun;
15704
16751
  exports.DocxTable = DocxTable;
15705
16752
  exports.DocxTableCell = DocxTableCell;
15706
16753
  exports.DocxTableRow = DocxTableRow;
16754
+ exports.FIREBIRD_SUPPORTED_BACKUP_FORMAT_VERSION = SUPPORTED_BACKUP_FORMAT_VERSION;
16755
+ exports.FirebirdBackupFormatError = FirebirdBackupFormatError;
16756
+ exports.FirebirdBackupParseError = FirebirdBackupParseError;
16757
+ exports.FirebirdCompositeRecordUnsupportedError = FirebirdCompositeRecordUnsupportedError;
16758
+ exports.FirebirdDataParseError = FirebirdDataParseError;
16759
+ exports.FirebirdSchemaParseError = FirebirdSchemaParseError;
16760
+ exports.FirebirdUnsupportedFieldTypeError = FirebirdUnsupportedFieldTypeError;
16761
+ exports.HsqldbRowFormatError = HsqldbRowFormatError;
15707
16762
  exports.HsqldbScriptParseError = HsqldbScriptParseError;
15708
16763
  Object.defineProperty(exports, "LAYOUT_FORMAT_VERSION", {
15709
16764
  enumerable: true,
@@ -15904,6 +16959,7 @@ Object.defineProperty(exports, "decodeEntities", {
15904
16959
  return ooxml_js.decodeEntities;
15905
16960
  }
15906
16961
  });
16962
+ exports.decodeHsqldbCachedTables = decodeHsqldbCachedTables;
15907
16963
  Object.defineProperty(exports, "decodePackage", {
15908
16964
  enumerable: true,
15909
16965
  get: function() {
@@ -16024,6 +17080,7 @@ exports.pptxPdfCodec = pptxPdfCodec;
16024
17080
  exports.pptxToOdp = pptxToOdp;
16025
17081
  exports.pptxToPdf = pptxToPdf;
16026
17082
  exports.readDocxContent = readDocxContent;
17083
+ exports.readFirebirdBackup = readFirebirdBackup;
16027
17084
  exports.readOdbTables = readOdbTables;
16028
17085
  exports.readOdfEmbeddedFormula = readOdfEmbeddedFormula;
16029
17086
  exports.readOdfFormulaContent = readOdfFormulaContent;