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