xlsxrb 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +88 -0
  3. data/README.md +25 -3
  4. data/lib/xlsxrb/dsl_helpers.rb +65 -1
  5. data/lib/xlsxrb/elements/styles.rb +15 -6
  6. data/lib/xlsxrb/elements/worksheet.rb +2 -2
  7. data/lib/xlsxrb/number_formatter.rb +26 -8
  8. data/lib/xlsxrb/ooxml/cfb.rb +11 -3
  9. data/lib/xlsxrb/ooxml/crypto/agile.rb +48 -10
  10. data/lib/xlsxrb/ooxml/crypto/standard.rb +5 -1
  11. data/lib/xlsxrb/ooxml/crypto.rb +3 -0
  12. data/lib/xlsxrb/ooxml/shared_strings_parser.rb +26 -8
  13. data/lib/xlsxrb/ooxml/utils.rb +13 -0
  14. data/lib/xlsxrb/ooxml/workbook_writer.rb +43 -21
  15. data/lib/xlsxrb/ooxml/worksheet_parser.rb +116 -12
  16. data/lib/xlsxrb/ooxml/worksheet_writer.rb +338 -259
  17. data/lib/xlsxrb/ooxml/writer/drawing_xml.rb +206 -201
  18. data/lib/xlsxrb/ooxml/writer/features_xml.rb +109 -102
  19. data/lib/xlsxrb/ooxml/writer/styles_xml.rb +46 -46
  20. data/lib/xlsxrb/ooxml/writer.rb +167 -160
  21. data/lib/xlsxrb/ooxml/xml_builder.rb +35 -7
  22. data/lib/xlsxrb/ooxml/xml_parser.rb +34 -1
  23. data/lib/xlsxrb/ooxml/zip_reader.rb +95 -68
  24. data/lib/xlsxrb/ooxml/zip_writer.rb +16 -0
  25. data/lib/xlsxrb/stream_row.rb +2 -2
  26. data/lib/xlsxrb/stream_sheet.rb +26 -11
  27. data/lib/xlsxrb/stream_writer.rb +212 -86
  28. data/lib/xlsxrb/style_builder.rb +339 -0
  29. data/lib/xlsxrb/version.rb +1 -1
  30. data/lib/xlsxrb/workbook_builder.rb +239 -88
  31. data/lib/xlsxrb/worksheet_builder.rb +847 -139
  32. data/lib/xlsxrb.rb +87 -21
  33. data/sig/generated/xlsxrb/dsl_helpers.rbs +37 -0
  34. data/sig/generated/xlsxrb/elements/styles.rbs +5 -0
  35. data/sig/generated/xlsxrb/number_formatter.rbs +7 -0
  36. data/sig/generated/xlsxrb/ooxml/cfb.rbs +2 -0
  37. data/sig/generated/xlsxrb/ooxml/crypto/agile.rbs +10 -0
  38. data/sig/generated/xlsxrb/ooxml/shared_strings_parser.rbs +7 -0
  39. data/sig/generated/xlsxrb/ooxml/utils.rbs +10 -0
  40. data/sig/generated/xlsxrb/ooxml/workbook_writer.rbs +13 -0
  41. data/sig/generated/xlsxrb/ooxml/worksheet_parser.rbs +40 -0
  42. data/sig/generated/xlsxrb/ooxml/worksheet_writer.rbs +53 -0
  43. data/sig/generated/xlsxrb/ooxml/writer/features_xml.rbs +3 -0
  44. data/sig/generated/xlsxrb/ooxml/writer.rbs +4 -0
  45. data/sig/generated/xlsxrb/ooxml/xml_builder.rbs +19 -2
  46. data/sig/generated/xlsxrb/ooxml/xml_parser.rbs +10 -0
  47. data/sig/generated/xlsxrb/ooxml/zip_reader.rbs +12 -1
  48. data/sig/generated/xlsxrb/ooxml/zip_writer.rbs +8 -0
  49. data/sig/generated/xlsxrb/stream_row.rbs +2 -2
  50. data/sig/generated/xlsxrb/stream_sheet.rbs +9 -0
  51. data/sig/generated/xlsxrb/stream_writer.rbs +46 -6
  52. data/sig/generated/xlsxrb/style_builder.rbs +261 -0
  53. data/sig/generated/xlsxrb/workbook_builder.rbs +42 -9
  54. data/sig/generated/xlsxrb/worksheet_builder.rbs +618 -4
  55. data/sig/generated/xlsxrb.rbs +53 -8
  56. metadata +9 -3
data/lib/xlsxrb.rb CHANGED
@@ -77,6 +77,21 @@ module Xlsxrb
77
77
  # Base class for all exceptions raised by Xlsxrb.
78
78
  class Error < StandardError; end
79
79
 
80
+ # @api private
81
+ module Deprecation
82
+ LIB_DIR = File.expand_path(__dir__).freeze
83
+ private_constant :LIB_DIR
84
+
85
+ # Warns that a feature is deprecated, at the location +uplevel+ frames above the caller,
86
+ # or, with +uplevel: nil+, at the first caller outside this library, for methods that
87
+ # are reached both directly and through another xlsxrb method.
88
+ #: (String message, ?uplevel: Integer?) -> void
89
+ def self.warn(message, uplevel: 1)
90
+ uplevel ||= caller_locations(1)&.index { |location| !location.absolute_path.to_s.start_with?(LIB_DIR) } || 0
91
+ Kernel.warn("[Xlsxrb DEPRECATION] #{message}", uplevel: uplevel + 1)
92
+ end
93
+ end
94
+
80
95
  # Raised when parsing malformed or invalid XML structures.
81
96
  class ParseError < Error; end
82
97
 
@@ -689,6 +704,28 @@ module Xlsxrb
689
704
  DslHelpers.sanitize_sheet_name(name, replace_char: replace_char)
690
705
  end
691
706
 
707
+ # Cuts text to what a cell holds: 32,767 characters counted in UTF-16 code units, as
708
+ # Excel counts them, so a character outside the Basic Multilingual Plane, such as an emoji,
709
+ # counts as two. A character is never split. Writing longer text raises ArgumentError
710
+ # with +strict_excel_mode+ (the default); call this first to keep the start of the text
711
+ # instead.
712
+ #
713
+ # Text of 32,767 bytes or fewer always fits, so it is returned as is after its byte size
714
+ # is checked, without counting its characters. Longer text is returned as a new UTF-8
715
+ # String, even if it fits.
716
+ #
717
+ # @example
718
+ # Xlsxrb.truncate_cell_text("x" * 40_000).length #=> 32767
719
+ # Xlsxrb.truncate_cell_text("😀" * 20_000).length #=> 16383
720
+ #
721
+ # @param text [String]
722
+ # @return [String]
723
+ # @api public
724
+ #: (String text) -> String
725
+ def self.truncate_cell_text(text)
726
+ DslHelpers.truncate_cell_text(text)
727
+ end
728
+
692
729
  # Reads an XLSX file (streaming and lazy-loaded by default) from a file path, IO stream, or binary String.
693
730
  #
694
731
  # Sheets and rows are streamed lazily with O(1) constant memory. If a block is given,
@@ -720,12 +757,13 @@ module Xlsxrb
720
757
  #: (untyped source, ?password: String?, ?trim_empty_rows: bool, ?pad_empty_rows: bool, ?pad_empty_cells: bool, ?max_uncompressed_size: Integer?) { (StreamSheet) -> void } -> void
721
758
  #: (untyped source, ?password: String?, ?trim_empty_rows: bool, ?pad_empty_rows: bool, ?pad_empty_cells: bool, ?max_uncompressed_size: Integer?) -> Enumerator[StreamSheet, void]
722
759
  def self.read(source, password: nil, trim_empty_rows: false, pad_empty_rows: false, pad_empty_cells: false, max_uncompressed_size: nil, &)
723
- prepared_source = prepare_source_io(source, password)
760
+ # The prepared source is what the Enumerator reads, so that it is prepared once.
761
+ source = prepare_source_io(source, password)
724
762
  return to_enum(:read, source, password: password, trim_empty_rows: trim_empty_rows, pad_empty_rows: pad_empty_rows, pad_empty_cells: pad_empty_cells, max_uncompressed_size: max_uncompressed_size) unless block_given?
725
763
 
726
764
  zip_options = {}
727
765
  zip_options[:max_uncompressed_size] = max_uncompressed_size if max_uncompressed_size
728
- zip_reader = Ooxml::ZipReader.open(prepared_source, **zip_options)
766
+ zip_reader = Ooxml::ZipReader.open(source, **zip_options)
729
767
 
730
768
  begin
731
769
  workbook_path = resolve_workbook_entry(zip_reader)
@@ -932,30 +970,36 @@ module Xlsxrb
932
970
 
933
971
  # Writes an XLSX file or IO stream (streaming or in-memory), or returns a binary string.
934
972
  #
935
- # @overload write(?target, password: nil, encryption_mode: :standard, strict_excel_mode: true, &block)
973
+ # @overload write(?target, password: nil, encryption_mode: nil, strict_excel_mode: true, &block)
936
974
  # Streaming write: yields a {StreamWriter} context for high-speed, zero-allocation XLSX generation.
937
975
  # If target is omitted, returns the generated XLSX as an in-memory binary String.
938
976
  # @param target [String, IO, StringIO, nil] Optional destination file path or writable IO object.
939
977
  # @param password [String, nil] Optional password to encrypt the generated XLSX file.
940
- # @param encryption_mode [Symbol] Encryption algorithm (:standard or :agile).
978
+ # @param encryption_mode [Symbol, nil] Encryption scheme used with a password: `:agile` (AES-256, with a check
979
+ # that the file is unchanged) or `:standard` (AES-128; deprecated, and an error from 0.3.0). When omitted,
980
+ # Standard is written in 0.2 and Agile from 0.3.0. See docs/adr/0013-write-agile-encryption-read-both.md.
941
981
  # @param strict_excel_mode [Boolean] Whether to enforce Microsoft Excel specification limits.
942
982
  # @yield [stream_writer]
943
983
  # @yieldparam stream_writer [Xlsxrb::StreamWriter]
944
984
  # @return [String, void] Binary data if target is omitted, or void if written to target.
945
985
  #
946
- # @overload write(workbook, password: nil, encryption_mode: :standard)
986
+ # @overload write(workbook, password: nil, encryption_mode: nil)
947
987
  # In-memory write: exports the workbook to an in-memory binary String.
948
988
  # @param workbook [Elements::Workbook] The workbook to write.
949
989
  # @param password [String, nil] Optional password to encrypt the binary string.
950
- # @param encryption_mode [Symbol] Encryption algorithm (:standard or :agile).
990
+ # @param encryption_mode [Symbol, nil] Encryption scheme used with a password: `:agile` (AES-256, with a check
991
+ # that the file is unchanged) or `:standard` (AES-128; deprecated, and an error from 0.3.0). When omitted,
992
+ # Standard is written in 0.2 and Agile from 0.3.0. See docs/adr/0013-write-agile-encryption-read-both.md.
951
993
  # @return [String] Binary data representing the XLSX file.
952
994
  #
953
- # @overload write(target, workbook, password: nil, encryption_mode: :standard)
995
+ # @overload write(target, workbook, password: nil, encryption_mode: nil)
954
996
  # In-memory write: writes the workbook to a file path or IO stream.
955
997
  # @param target [String, IO, StringIO] Destination file path or writable IO object.
956
998
  # @param workbook [Elements::Workbook] The workbook to write.
957
999
  # @param password [String, nil] Optional password to encrypt the output file.
958
- # @param encryption_mode [Symbol] Encryption algorithm (:standard or :agile).
1000
+ # @param encryption_mode [Symbol, nil] Encryption scheme used with a password: `:agile` (AES-256, with a check
1001
+ # that the file is unchanged) or `:standard` (AES-128; deprecated, and an error from 0.3.0). When omitted,
1002
+ # Standard is written in 0.2 and Agile from 0.3.0. See docs/adr/0013-write-agile-encryption-read-both.md.
959
1003
  # @return [void]
960
1004
  #
961
1005
  # @example Streaming write to file
@@ -984,8 +1028,8 @@ module Xlsxrb
984
1028
  # @param compression_level [Integer, nil] ZIP deflate compression level (0..9, or Zlib::DEFAULT_COMPRESSION
985
1029
  # for zlib's level 6). Defaults to {DEFAULT_COMPRESSION_LEVEL}. Higher levels write smaller files more slowly;
986
1030
  # level 0 stores entries without compression. See docs/adr/0009-default-zip-compression-level.md.
987
- #: (?untyped target_or_workbook, ?Elements::Workbook | untyped workbook_or_nil, ?password: String?, ?encryption_mode: Symbol, ?strict_excel_mode: bool, ?default_font: untyped?, ?shared_strings: bool, ?compression_level: Integer | nil) ?{ (StreamWriter) -> void } -> untyped
988
- def self.write(target_or_workbook = OMITTED_TARGET, workbook_or_nil = nil, password: nil, encryption_mode: :standard, strict_excel_mode: true, default_font: nil, shared_strings: true, compression_level: DEFAULT_COMPRESSION_LEVEL, &)
1031
+ #: (?untyped target_or_workbook, ?Elements::Workbook | untyped workbook_or_nil, ?password: String?, ?encryption_mode: Symbol?, ?strict_excel_mode: bool, ?default_font: untyped?, ?shared_strings: bool, ?compression_level: Integer | nil) ?{ (StreamWriter) -> void } -> untyped
1032
+ def self.write(target_or_workbook = OMITTED_TARGET, workbook_or_nil = nil, password: nil, encryption_mode: nil, strict_excel_mode: true, default_font: nil, shared_strings: true, compression_level: DEFAULT_COMPRESSION_LEVEL, &)
989
1033
  if block_given?
990
1034
  if target_or_workbook.equal?(OMITTED_TARGET)
991
1035
  io = StringIO.new
@@ -1005,7 +1049,7 @@ module Xlsxrb
1005
1049
  yield stream_writer
1006
1050
  stream_writer.close
1007
1051
  plain_bytes = buf.string.b
1008
- encrypted_bytes = Ooxml::Crypto.encrypt(plain_bytes, password, mode: encryption_mode)
1052
+ encrypted_bytes = Ooxml::Crypto.encrypt(plain_bytes, password, mode: write_encryption_mode(encryption_mode))
1009
1053
  if target.is_a?(String)
1010
1054
  File.binwrite(target, encrypted_bytes)
1011
1055
  elsif target.respond_to?(:write)
@@ -1224,7 +1268,7 @@ module Xlsxrb
1224
1268
  workbook_properties: wb_properties,
1225
1269
  compression_level: compression_level
1226
1270
  )
1227
- encrypted_bytes = Ooxml::Crypto.encrypt(buf.string.b, password, mode: encryption_mode)
1271
+ encrypted_bytes = Ooxml::Crypto.encrypt(buf.string.b, password, mode: write_encryption_mode(encryption_mode))
1228
1272
  if target.is_a?(String)
1229
1273
  File.binwrite(target, encrypted_bytes)
1230
1274
  elsif target.respond_to?(:write)
@@ -1258,6 +1302,10 @@ module Xlsxrb
1258
1302
  # end
1259
1303
  # end
1260
1304
  #
1305
+ # @note Planned for version 0.3.0: Cell#format_code of the built cells will be the
1306
+ # number format of each cell's resolved style, as in a loaded workbook; cells styled
1307
+ # :default or :none will have style index 0; and a style index given in cell_styles
1308
+ # will be kept only in Cell#style_index.
1261
1309
  # @param strict_excel_mode [Boolean] Whether to enforce Microsoft Excel specification limits.
1262
1310
  # @param default_font [Hash, nil] Optional default font options.
1263
1311
  # @yield [builder]
@@ -2580,11 +2628,27 @@ module Xlsxrb
2580
2628
  )
2581
2629
  end
2582
2630
 
2631
+ STANDARD_ENCRYPTION_MESSAGE = "encryption_mode: :standard is deprecated; pass encryption_mode: :agile, which Excel 2010 and later open. " \
2632
+ "In version 0.3.0 a password always writes Agile encryption and :standard raises ArgumentError."
2633
+ private_constant :STANDARD_ENCRYPTION_MESSAGE
2634
+
2635
+ # The scheme to encrypt with. Standard stays the default in 0.2; asking for it by name warns.
2636
+ #: (Symbol? encryption_mode) -> Symbol
2637
+ def write_encryption_mode(encryption_mode)
2638
+ Deprecation.warn(STANDARD_ENCRYPTION_MESSAGE, uplevel: nil) if encryption_mode == :standard
2639
+ encryption_mode || :standard
2640
+ end
2641
+
2642
+ STRING_SOURCE_AS_DATA_MESSAGE = "Passing xlsx data as a String to Xlsxrb.load and Xlsxrb.read is deprecated; " \
2643
+ "pass a stream, as in StringIO.new(data). In version 0.3.0 a String is always a file path."
2644
+ private_constant :STRING_SOURCE_AS_DATA_MESSAGE
2645
+
2583
2646
  #: (untyped source, String? password) -> untyped
2584
2647
  def prepare_source_io(source, password)
2585
2648
  if source.is_a?(String)
2586
2649
  bin_source = source.encoding == Encoding::BINARY ? source : source.b
2587
2650
  if bin_source.start_with?("PK\x03\x04".b) || bin_source.include?("\x00".b) || Ooxml::Cfb::Reader.cfb?(bin_source)
2651
+ Deprecation.warn(STRING_SOURCE_AS_DATA_MESSAGE, uplevel: nil)
2588
2652
  if Ooxml::Cfb::Reader.cfb?(bin_source)
2589
2653
  decrypted_zip = Ooxml::Crypto.decrypt(bin_source, password)
2590
2654
  StringIO.new(decrypted_zip)
@@ -2613,18 +2677,20 @@ module Xlsxrb
2613
2677
  raise Errno::ENOENT, shown
2614
2678
  end
2615
2679
  elsif source.respond_to?(:read) && source.respond_to?(:pos) && source.respond_to?(:seek)
2616
- begin
2680
+ # Only looking at the first bytes may fail, for a stream that cannot seek. An error
2681
+ # from decrypting, such as a wrong password, is the caller's to see.
2682
+ first_bytes = begin
2617
2683
  cur_pos = source.pos
2618
- first_bytes = source.read(8)
2684
+ peeked = source.read(8)
2619
2685
  source.seek(cur_pos)
2620
- if Ooxml::Cfb::Reader.cfb?(first_bytes)
2621
- full_data = source.read
2622
- decrypted_zip = Ooxml::Crypto.decrypt(full_data, password)
2623
- StringIO.new(decrypted_zip)
2624
- else
2625
- source
2626
- end
2686
+ peeked
2627
2687
  rescue StandardError
2688
+ nil
2689
+ end
2690
+ if Ooxml::Cfb::Reader.cfb?(first_bytes)
2691
+ decrypted_zip = Ooxml::Crypto.decrypt(source.read, password)
2692
+ StringIO.new(decrypted_zip)
2693
+ else
2628
2694
  source
2629
2695
  end
2630
2696
  else
@@ -83,9 +83,24 @@ module Xlsxrb
83
83
  #
84
84
  # @param styles [untyped]
85
85
  # @return [untyped]
86
+ # @raise [ArgumentError] If the Hash looks like an inline style rather than columns mapped to styles.
86
87
  # : (untyped styles) -> untyped
87
88
  def self.normalize_row_styles: (untyped styles) -> untyped
88
89
 
90
+ # Hint for a cell_styles Hash that reads like an inline style.
91
+ INLINE_CELL_STYLES_HINT: ::String
92
+
93
+ # Raises when an entry of a cell_styles Hash cannot be a column mapped to a style:
94
+ # a style option name as the key (a column name has at most three letters), or a
95
+ # value that is not a style name, a style index, an inline style, or nil.
96
+ #
97
+ # @param column [Object] The entry's key.
98
+ # @param style [Object] The entry's value.
99
+ # @return [void]
100
+ # @raise [ArgumentError]
101
+ # : (untyped column, untyped style) -> void
102
+ def self.check_column_style!: (untyped column, untyped style) -> void
103
+
89
104
  # Style names that select the workbook's default cell format.
90
105
  DEFAULT_STYLE_NAMES: untyped
91
106
 
@@ -260,6 +275,28 @@ module Xlsxrb
260
275
 
261
276
  MAX_SHEET_NAME_LENGTH: ::Integer
262
277
 
278
+ MAX_CELL_TEXT_LENGTH: ::Integer
279
+
280
+ # Raises ArgumentError if +text+ is longer than a cell holds: 32,767 UTF-16 code units,
281
+ # as Excel counts it (ADR 0011). Text of N UTF-16 code units has at least N bytes, so
282
+ # callers on hot paths call this only for text longer than MAX_CELL_TEXT_LENGTH bytes,
283
+ # which bytesize tells in O(1).
284
+ #
285
+ # @param text [String]
286
+ # @return [void]
287
+ # @raise [ArgumentError]
288
+ # : (String text) -> void
289
+ def self.check_cell_text_length!: (String text) -> void
290
+
291
+ # Cuts +text+ to the whole characters that fit in a cell: 32,767 UTF-16 code units, as
292
+ # Excel counts them (ADR 0011). Text of 32,767 bytes or fewer always fits and is returned
293
+ # as is, so most text is not counted. Longer text is returned as a new UTF-8 String.
294
+ #
295
+ # @param text [String]
296
+ # @return [String]
297
+ # : (String text) -> String
298
+ def self.truncate_cell_text: (String text) -> String
299
+
263
300
  # Sanitizes a worksheet name to ensure it conforms to Excel constraints within 31 characters.
264
301
  # Replaces forbidden characters (\ / ? * [ ] : and control characters),
265
302
  # replaces leading/trailing apostrophes, and replaces reserved 'History' with 'History_'.
@@ -337,6 +337,11 @@ module Xlsxrb
337
337
 
338
338
  private
339
339
 
340
+ # Whether +value+ can be an index into cellXfs. A larger Integer is not one, and
341
+ # Array#[] raises RangeError for an Integer that does not fit in a machine word.
342
+ # : (untyped value) -> bool
343
+ def style_index?: (untyped value) -> bool
344
+
340
345
  def next_num_fmt_id: () -> untyped
341
346
 
342
347
  def invalidate_cache!: () -> untyped
@@ -10,6 +10,13 @@ module Xlsxrb
10
10
  # Built-in date and time format code strings.
11
11
  DATE_PATTERNS: untyped
12
12
 
13
+ # Excel accepts format codes of up to 255 characters. Longer codes are not applied: the
14
+ # cost of formatting grows with the code, for every cell that uses it.
15
+ MAX_FORMAT_CODE_LENGTH: ::Integer
16
+
17
+ # Stands for a literal "%" while a date format code is converted to a strftime pattern.
18
+ LITERAL_PERCENT: ::String
19
+
13
20
  # Formats a cell value according to an Excel format code string.
14
21
  #
15
22
  # @param value [Object, nil] The cell's raw or typed value.
@@ -83,6 +83,8 @@ module Xlsxrb
83
83
 
84
84
  def parse_header: () -> untyped
85
85
 
86
+ # The header takes the first sector: 512 bytes in version 3, and 4,096 in version 4,
87
+ # where it is padded with zeros. Sector 0 follows it.
86
88
  def sector_offset: (untyped sector_id) -> untyped
87
89
 
88
90
  def read_sector: (untyped sector_id) -> untyped
@@ -25,6 +25,16 @@ module Xlsxrb
25
25
 
26
26
  private def self.parse_encryption_info: (untyped bytes) -> untyped
27
27
 
28
+ # Data integrity ([MS-OFFCRYPTO] 2.3.4.14): the HMAC of the whole EncryptedPackage
29
+ # stream. The HMAC key and value are encrypted with the package key, each with an
30
+ # IV derived from the keyData salt.
31
+ private def self.integrity_verified?: (untyped info, untyped cipher_name, untyped digest, untyped package_key, untyped encrypted_package_bytes) -> untyped
32
+
33
+ # xlsxrb 0.2.1 and earlier wrote an HMAC of the package before encryption, with the HMAC
34
+ # key and value encrypted under keys derived from the password. Files it wrote are
35
+ # still read; this HMAC also fails for a package that was changed.
36
+ private def self.legacy_integrity_verified?: (untyped info, untyped cipher_name, untyped digest, untyped h_final, untyped plain) -> untyped
37
+
28
38
  private def self.digest_for: (untyped name) -> untyped
29
39
 
30
40
  private def self.cipher_name_for: (untyped algo, untyped key_bits) -> untyped
@@ -15,6 +15,13 @@ module Xlsxrb
15
15
 
16
16
  def self.fast_scan: (untyped xml_src) -> untyped
17
17
 
18
+ # Returns the index of the first +pattern+ at or after +from+, or the size of +xml+ when
19
+ # there is none. +cached+ is the result of the previous call for the same pattern with a
20
+ # smaller +from+; while it is not behind +from+ it is still the answer, so a caller that
21
+ # moves forward searches each stretch of +xml+ once.
22
+ # : (String xml, String pattern, Integer from, Integer? cached) -> Integer
23
+ def self.next_index: (String xml, String pattern, Integer from, Integer? cached) -> Integer
24
+
18
25
  def self.extract_multi_t: (untyped xml, untyped from, untyped to, untyped t_start_pattern, untyped t_start_len, untyped t_end_tag, untyped t_end_len, untyped rph_start_pattern, untyped rph_end_tag, untyped rph_end_len, ?has_rph: untyped) -> untyped
19
26
 
20
27
  def self.normalize_newlines: (untyped str) -> untyped
@@ -34,6 +34,16 @@ module Xlsxrb
34
34
  # Default date-time format code used by Writer for Time cells.
35
35
  DEFAULT_DATETIME_FORMAT: ::String
36
36
 
37
+ # First bytes of the four-byte UTF-8 sequences, which encode the characters outside
38
+ # the Basic Multilingual Plane: two UTF-16 code units each.
39
+ SUPPLEMENTARY_LEAD_BYTES: untyped
40
+
41
+ # The length of UTF-8 text in UTF-16 code units, the unit Excel counts its text
42
+ # limits in (ADR 0011): one per character, and one more for each character outside
43
+ # the Basic Multilingual Plane, such as an emoji.
44
+ # : (String text) -> Integer
45
+ def self.utf16_length: (String text) -> Integer
46
+
37
47
  # Checks whether a serial number is a valid Excel date within the supported range.
38
48
  # : (untyped serial, ?date1904: bool) -> bool
39
49
  def self.valid_excel_date?: (untyped serial, ?date1904: bool) -> bool
@@ -88,8 +88,21 @@ module Xlsxrb
88
88
 
89
89
  ESCAPE_MAP: untyped
90
90
 
91
+ MEDIA_EXTENSION_RE: ::Regexp
92
+
93
+ # Returns the extension for a media part name. It becomes part of a ZIP entry name, a
94
+ # relationship target, and a content type, so anything but letters and digits is
95
+ # rejected.
96
+ # : (untyped ext) -> String
97
+ def media_extension: (untyped ext) -> String
98
+
91
99
  def escape_xml: (untyped value) -> untyped
92
100
 
101
+ # Escapes cell text: encodes it as ST_Xstring (XmlBuilder.encode_xstring), so that
102
+ # text that looks like _xHHHH_ and characters XML 1.0 cannot hold are read back as
103
+ # written, then escapes the XML special characters.
104
+ def escape_text: (untyped value) -> untyped
105
+
93
106
  def write_shared_strings_xml: (untyped zip) -> untyped
94
107
 
95
108
  def write_worksheet_xml: (untyped io, untyped sheet, ?drawing_rid: untyped, ?picture_rid: untyped, ?sheet_protection: untyped, ?protected_ranges: untyped, ?auto_filter: untyped, ?filter_columns: untyped, ?sort_state: untyped, ?merge_cells: untyped, ?conditional_formats: untyped, ?data_validations: untyped, ?hyperlinks: untyped, ?print_options: untyped, ?page_margins: untyped, ?page_setup: untyped, ?header_footer: untyped, ?row_breaks: untyped, ?col_breaks: untyped, ?column_breaks: untyped, ?cell_watches: untyped, ?ignored_errors: untyped, ?freeze_pane: untyped, ?split_pane: untyped, ?selection: untyped, ?sheet_view: untyped, ?sheet_properties: untyped, ?sheet_format: untyped, ?tables: untyped, ?table_start_rid: untyped, ?legacy_drawing_rid: untyped, ?sparkline_groups: untyped, ?phonetic_pr: untyped, ?sheet_calc_pr: untyped) -> untyped
@@ -78,6 +78,20 @@ module Xlsxrb
78
78
  # : (String raw) -> (Integer | Float)?
79
79
  def self.numeric_cell_value: (String raw) -> (Integer | Float)?
80
80
 
81
+ # Excel's last row. A larger row number is not a worksheet row, and an unbounded one
82
+ # would be built digit by digit into an arbitrarily large Integer.
83
+ MAX_ROW_NUMBER: ::Integer
84
+
85
+ # Longer text is not read as a number. Excel writes numbers in at most 25 characters;
86
+ # converting millions of digits to an Integer takes time that grows faster than their
87
+ # number, and matching them takes memory in proportion.
88
+ MAX_NUMERIC_TEXT_BYTES: ::Integer
89
+
90
+ # Looks up a shared string by the index in a cell's <v>. An index that is negative or
91
+ # too long to be one reads as an empty string, as an index past the end does.
92
+ # : (Array[untyped] shared_strings, String raw_index) -> untyped
93
+ def self.shared_string_at: (Array[untyped] shared_strings, String raw_index) -> untyped
94
+
81
95
  # SECURITY NOTE: Decodes only standard predefined XML entities in a single pass.
82
96
  # This completely prevents "Billion Laughs" attacks (exponential entity expansion)
83
97
  # because it avoids recursive expansion and ignores custom entities entirely.
@@ -105,6 +119,9 @@ module Xlsxrb
105
119
  # rubocop:disable Style/OptionalBooleanParameter
106
120
  def self.fast_scan_rows_direct: (untyped xml_src, untyped shared_strings, untyped _part_name, ?untyped styles, ?untyped date1904, ?untyped pad_empty_cells) ?{ (?) -> untyped } -> untyped
107
121
 
122
+ # Bytes of one row, or of markup between rows, held while streaming a worksheet.
123
+ MAX_STREAM_BUFFER_BYTES: untyped
124
+
108
125
  # rubocop:disable Style/OptionalBooleanParameter
109
126
  def self.scan_rows_stream: (untyped source, untyped shared_strings, untyped _part_name, ?untyped styles, ?untyped date1904, ?untyped pad_empty_cells) ?{ (?) -> untyped } -> untyped
110
127
 
@@ -125,6 +142,29 @@ module Xlsxrb
125
142
 
126
143
  ATTR_S: ::Regexp
127
144
 
145
+ CELL_CLOSE_RE: ::Regexp
146
+
147
+ UNCLOSED_CELL_RE: ::Regexp
148
+
149
+ INLINE_STRING_OPEN_RE: ::Regexp
150
+
151
+ INLINE_STRING_CLOSE_RE: ::Regexp
152
+
153
+ # Raises ParseError for a row whose last <c> or <is> start tag has no end tag.
154
+ #
155
+ # SECURITY NOTE: CELL_FAST_RE looks ahead for </c> and </is>. For a start tag with no end
156
+ # tag after it, that search runs to the end of the row and fails, once per such tag, so
157
+ # a row of 40,000 unclosed <c> tags (a 3 KB file) took minutes. Every search made here
158
+ # is a single pass over the row.
159
+ # : (String chunk) -> void
160
+ def self.verify_cells_closed!: (String chunk) -> void
161
+
162
+ # Returns the bytes of a row with every sequence that is not UTF-8 replaced by U+FFFD,
163
+ # so that the text, formulas, and attributes cut from it are valid strings. A row that
164
+ # is valid, as nearly all are, is returned as is.
165
+ # : (String chunk) -> String
166
+ def self.scrub_row: (String chunk) -> String
167
+
128
168
  def self.fast_parse_cells_direct: (untyped xml, untyped from, untyped to, untyped shared_strings, untyped row_source, ?untyped prefix) -> untyped
129
169
 
130
170
  # rubocop:disable Style/OptionalBooleanParameter
@@ -13,10 +13,43 @@ module Xlsxrb
13
13
 
14
14
  INTEGER_STRINGS: untyped
15
15
 
16
+ # Matches a value that claims to be a Time through is_a? without being one, such as
17
+ # ActiveSupport::TimeWithZone, which `when Time` does not match. The writers try it
18
+ # after their Time and Date branches, so other values never reach it. Such a value
19
+ # is written as the Time that to_time gives.
20
+ # @api private
21
+ module TimeLike
22
+ # : (untyped value) -> bool
23
+ def self.===: (untyped value) -> bool
24
+
25
+ # A Time with the value's year, month, day, hour, minute, second, and UTC offset,
26
+ # which keeps its wall clock.
27
+ # : (untyped value) -> Time
28
+ def self.to_time: (untyped value) -> Time
29
+ end
30
+
16
31
  def initialize: (untyped io, ?date1904: untyped) -> untyped
17
32
 
33
+ # Makes the row writers reject text longer than a cell holds (32,767 characters),
34
+ # as the strict Excel mode of the caller asks.
35
+ # @api private
36
+ # : (bool strict) -> void
37
+ def strict_excel_mode=: (bool strict) -> void
38
+
39
+ # Sets what gives the style id for a Time-like value in a styled cell, so that a
40
+ # style without a number format can be given its date-time variant.
41
+ # @api private
42
+ # : (untyped resolver) -> void
43
+ attr_writer time_like_style_resolver: untyped
44
+
18
45
  def set_column_style: (untyped col_index, untyped style_id) -> untyped
19
46
 
47
+ # Drops the resolved column style ids, for a caller that changed the style id a
48
+ # name in the style map stands for.
49
+ # @api private
50
+ # : () -> void
51
+ def forget_column_style_ids: () -> void
52
+
20
53
  # Write the worksheet header. Call once before writing rows.
21
54
  # Options for pre-sheetData elements:
22
55
  # sheet_properties: Hash of sheet-level properties (:tab_color, etc.)
@@ -38,6 +71,21 @@ module Xlsxrb
38
71
 
39
72
  private
40
73
 
74
+ # Writes the cells of a row that has cell styles, row attributes, or column styles.
75
+ # It is not inlined in write_row_values because YJIT ran the same loop there about
76
+ # 1.6 times slower, after the row attribute handling.
77
+ def write_styled_cells: (untyped buf, untyped values, untyped max_len, untyped row_num_str, untyped styles, untyped is_styles_collection, untyped single_style_id, untyped row_style_id, untyped style_map, untyped sst, untyped sst_index) -> untyped
78
+
79
+ # The style id of each column style, indexed by column, resolved once instead of
80
+ # for every cell. It is resolved again when the style map is another Hash, or after
81
+ # set_column_style or forget_column_style_ids.
82
+ # : (Hash[untyped, Integer]? style_map) -> Array[Integer?]
83
+ def column_style_ids: (Hash[untyped, Integer]? style_map) -> Array[Integer?]
84
+
85
+ # Writes a cell for write_styled_cells whose value is a formula, rich text, BigDecimal,
86
+ # cell error, or another value that write_styled_cells does not write itself.
87
+ def write_complex_cell: (untyped buf, untyped col_ref, untyped row_num_str, untyped value, untyped style_id, untyped sst, untyped sst_index) -> untyped
88
+
41
89
  def resolve_style_id: (untyped style, untyped style_map) -> untyped
42
90
 
43
91
  def write_sheet_properties: (untyped props) -> untyped
@@ -116,6 +164,11 @@ module Xlsxrb
116
164
  ESCAPE_MAP: untyped
117
165
 
118
166
  def escape_xml: (untyped value) -> untyped
167
+
168
+ # Escapes cell text: encodes it as ST_Xstring (XmlBuilder.encode_xstring), so that
169
+ # text that looks like _xHHHH_ and characters XML 1.0 cannot hold are read back as
170
+ # written, then escapes the XML special characters.
171
+ def escape_text: (untyped value) -> untyped
119
172
  end
120
173
  end
121
174
  end
@@ -40,6 +40,9 @@ module Xlsxrb
40
40
  def build_line_end_xml: (untyped element, untyped opts) -> untyped
41
41
 
42
42
  # : (untyped value) -> untyped
43
+ # Escapes cell text: ST_Xstring (XmlBuilder.encode_xstring), then XML.
44
+ def xml_escape_text: (untyped value) -> untyped
45
+
43
46
  def xml_escape: (untyped value) -> untyped
44
47
 
45
48
  # : (untyped rich_text) -> untyped
@@ -686,6 +686,10 @@ module Xlsxrb
686
686
 
687
687
  CHART_TYPE_MAP: untyped
688
688
 
689
+ # The elements of EG_ColorTransform in DrawingML. A transform's type is written as an
690
+ # element name, so only these are accepted.
691
+ COLOR_TRANSFORMS: untyped
692
+
689
693
  NO_AXIS_CHARTS: untyped
690
694
 
691
695
  THREE_AXIS_CHARTS: untyped
@@ -39,19 +39,36 @@ module Xlsxrb
39
39
 
40
40
  UNESCAPE_RE: ::Regexp
41
41
 
42
- # Escapes XML special characters in a string.
42
+ INVALID_XML_CHARS_RE: ::Regexp
43
+
44
+ # Escapes XML special characters in a string, and removes characters that XML 1.0
45
+ # cannot hold, such as U+0001 and U+FFFE: a part that contains one is not well-formed.
46
+ # Binary strings are only escaped.
43
47
  #
44
48
  # @param value [Object]
45
49
  # @return [String]
46
50
  # : (untyped value) -> String
47
51
  def self.escape: (untyped value) -> String
48
52
 
49
- NUM_ENTITY_RE: ::Regexp
53
+ XSTRING_ENCODE_RE: ::Regexp
54
+
55
+ # Encodes cell text as ISO/IEC 29500-1 ST_Xstring, the inverse of the _xHHHH_ part
56
+ # of unescape: an underscore that starts an _xHHHH_ sequence becomes _x005F_, and a
57
+ # character that XML 1.0 cannot hold, such as U+0001 or U+FFFE, becomes _xHHHH_.
58
+ # Excel and unescape read the original text back. The value must be UTF-8.
59
+ #
60
+ # @param value [String]
61
+ # @return [String]
62
+ # : (String value) -> String
63
+ def self.encode_xstring: (String value) -> String
64
+
65
+ ENTITY_RE: ::Regexp
50
66
 
51
67
  XSTRING_RE: ::Regexp
52
68
 
53
69
  # Unescapes predefined and numeric/hex XML entities, as well as
54
70
  # ISO/IEC 29500-1 ST_Xstring (_xHHHH_) control character sequences.
71
+ # Each entity is decoded once: "&amp;lt;" is the text "&lt;", not "<".
55
72
  #
56
73
  # @param value [Object]
57
74
  # @return [String]
@@ -14,8 +14,18 @@ module Xlsxrb
14
14
  # : (String xml_string) -> REXML::Parsers::SAX2Parser
15
15
  def self.sax2_parser: (String xml_string) -> REXML::Parsers::SAX2Parser
16
16
 
17
+ # Elements may nest this deep. SpreadsheetML, DrawingML, and VML parts stay far below
18
+ # it, and REXML's SAX2 parser takes time proportional to the depth for every tag, so
19
+ # that 20,000 nested elements (a 3 KB file) took 15 seconds.
20
+ MAX_ELEMENT_DEPTH: ::Integer
21
+
17
22
  # SAX2 parser that wraps each listener in an AttributeDecoder.
18
23
  class DecodingSAX2Parser < REXML::Parsers::SAX2Parser
24
+ # Parses the document, reporting malformed XML and exceeded entity expansion limits
25
+ # as Xlsxrb::ParseError.
26
+ # : () -> untyped
27
+ def parse: () -> untyped
28
+
19
29
  # : (*untyped args) ?{ (*untyped) -> untyped } -> untyped
20
30
  def listen: (*untyped args) ?{ (*untyped) -> untyped } -> untyped
21
31
  end
@@ -82,6 +82,8 @@ module Xlsxrb
82
82
  # : () -> Hash[String, String?]
83
83
  def read_all: () -> Hash[String, String?]
84
84
 
85
+ XML_PART_SUFFIXES: untyped
86
+
85
87
  # Returns raw bytes for a single entry, or nil if not found.
86
88
  # : (String name) -> String?
87
89
  def read_entry: (String name) -> String?
@@ -134,10 +136,19 @@ module Xlsxrb
134
136
 
135
137
  def parse_catalog_from_local_headers: (untyped io) -> untyped
136
138
 
137
- def find_data_descriptor_stream: (untyped io, untyped method, ?zip64: untyped) -> untyped
139
+ # Finds where a deflate stream of unknown length ends by inflating it, without keeping
140
+ # the output, and consumes the data descriptor that follows.
141
+ # Returns the compressed size, the uncompressed size, and the descriptor's CRC-32.
142
+ # : (untyped io, Integer method, ?zip64: bool) -> [Integer, Integer, Integer?]
143
+ def scan_data_descriptor_entry: (untyped io, Integer method, ?zip64: bool) -> [ Integer, Integer, Integer? ]
138
144
 
139
145
  def decompress: (untyped raw, untyped method) -> untyped
140
146
 
147
+ # Raises ZipError when the entry's data would lie outside the archive, so that a
148
+ # forged size is never passed to IO#read as a length to allocate.
149
+ # : (Entry entry) -> void
150
+ def verify_entry_bounds!: (Entry entry) -> void
151
+
141
152
  def safe_inflate: (untyped raw, untyped wbits) -> untyped
142
153
 
143
154
  def normalize_entry_name: (untyped name) -> untyped
@@ -52,6 +52,14 @@ module Xlsxrb
52
52
 
53
53
  private
54
54
 
55
+ UNSAFE_ENTRY_NAME_RE: ::Regexp
56
+
57
+ # Rejects names that a program extracting the archive could write outside its target
58
+ # directory (absolute paths, ".." segments, backslashes) and names with control
59
+ # characters.
60
+ # : (String path) -> void
61
+ def validate_entry_name!: (String path) -> void
62
+
55
63
  def determine_seekable: () -> untyped
56
64
 
57
65
  # : (Integer value) -> bool
@@ -9,9 +9,9 @@ module Xlsxrb
9
9
  # puts "#{cell.ref}: #{cell.value}"
10
10
  # end
11
11
  #
12
- # @example Random access or array conversion (cached on-demand)
12
+ # @example Random access or the row's values (cached on-demand)
13
13
  # cell = row[0]
14
- # values = row.to_a
14
+ # values = row.values
15
15
  #
16
16
  # @api public
17
17
  class StreamRow