@awacloud/fw 0.1.0 → 1.0.0

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 (609) hide show
  1. package/CHANGELOG.md +125 -0
  2. package/NOTICE +8 -0
  3. package/README.md +163 -31
  4. package/dist/build/fw.core.pure.meta.json +6 -6
  5. package/dist/build/fw.core.pure.min.js +15 -12
  6. package/dist/build/fw.full.pure.meta.json +13 -7
  7. package/dist/build/fw.full.pure.min.js +45 -42
  8. package/dist/build/fw.minimal.pure.meta.json +6 -6
  9. package/dist/build/fw.minimal.pure.min.js +16 -13
  10. package/dist/build/fw.pack.compress-heavy.pure.meta.json +6 -6
  11. package/dist/build/fw.pack.compress-heavy.pure.min.js +3 -3
  12. package/dist/build/fw.pack.crypto-advanced.pure.meta.json +6 -6
  13. package/dist/build/fw.pack.crypto-advanced.pure.min.js +1 -1
  14. package/dist/build/fw.pack.crypto-basic.pure.meta.json +6 -6
  15. package/dist/build/fw.pack.crypto-basic.pure.min.js +1 -1
  16. package/dist/build/fw.pack.crypto-identity.pure.meta.json +7 -6
  17. package/dist/build/fw.pack.crypto-identity.pure.min.js +4 -4
  18. package/dist/build/fw.pwa.pure.meta.json +7 -6
  19. package/dist/build/fw.pwa.pure.min.js +38 -35
  20. package/dist/build/fw.site-interactive.pure.meta.json +6 -6
  21. package/dist/build/fw.site-interactive.pure.min.js +37 -34
  22. package/dist/build/fw.site.pure.meta.json +6 -6
  23. package/dist/build/fw.site.pure.min.js +24 -21
  24. package/dist/build/fw.spa.pure.meta.json +8 -7
  25. package/dist/build/fw.spa.pure.min.js +41 -38
  26. package/dist/build/sanity-base-classic.min.js +1 -1
  27. package/dist/build/sanity.min.js +1 -1
  28. package/dist/types/core/internal.d.ts +29 -0
  29. package/dist/types/core/internal.d.ts.map +1 -0
  30. package/dist/types/core/logger.d.ts +23 -4
  31. package/dist/types/core/logger.d.ts.map +1 -1
  32. package/dist/types/core/modules.d.ts +374 -61
  33. package/dist/types/core/modules.d.ts.map +1 -1
  34. package/dist/types/core/runtime.d.ts +10 -6
  35. package/dist/types/core/runtime.d.ts.map +1 -1
  36. package/dist/types/core/worker-helper.d.ts +35 -0
  37. package/dist/types/core/worker-helper.d.ts.map +1 -1
  38. package/dist/types/crypto/cipher/aes.d.ts +1 -7
  39. package/dist/types/crypto/cipher/aes.d.ts.map +1 -1
  40. package/dist/types/crypto/cipher/chacha20.d.ts +0 -10
  41. package/dist/types/crypto/cipher/chacha20.d.ts.map +1 -1
  42. package/dist/types/crypto/hash/argon2.d.ts +0 -15
  43. package/dist/types/crypto/hash/argon2.d.ts.map +1 -1
  44. package/dist/types/crypto/hash/blake2b.d.ts.map +1 -1
  45. package/dist/types/crypto/hash/hmac.d.ts.map +1 -1
  46. package/dist/types/crypto/hash/pbkdf2.d.ts.map +1 -1
  47. package/dist/types/crypto/hash/poly1305.d.ts.map +1 -1
  48. package/dist/types/crypto/hash/sha224.d.ts +1 -1
  49. package/dist/types/crypto/hash/sha256.d.ts +4 -13
  50. package/dist/types/crypto/hash/sha256.d.ts.map +1 -1
  51. package/dist/types/crypto/hash/sha3.d.ts.map +1 -1
  52. package/dist/types/crypto/hash/sha384.d.ts +1 -1
  53. package/dist/types/crypto/hash/sha512.d.ts +4 -13
  54. package/dist/types/crypto/hash/sha512.d.ts.map +1 -1
  55. package/dist/types/crypto/mode/cmac.d.ts +0 -6
  56. package/dist/types/crypto/mode/cmac.d.ts.map +1 -1
  57. package/dist/types/crypto/mode/ctr.d.ts +0 -6
  58. package/dist/types/crypto/mode/ctr.d.ts.map +1 -1
  59. package/dist/types/crypto/mode/gcm.d.ts +0 -9
  60. package/dist/types/crypto/mode/gcm.d.ts.map +1 -1
  61. package/dist/types/crypto/pkc/ecc.d.ts +0 -1
  62. package/dist/types/crypto/pkc/ecc.d.ts.map +1 -1
  63. package/dist/types/crypto/pkc/ed25519.d.ts +4 -25
  64. package/dist/types/crypto/pkc/ed25519.d.ts.map +1 -1
  65. package/dist/types/crypto/pkc/hybridSign.d.ts +25 -5
  66. package/dist/types/crypto/pkc/hybridSign.d.ts.map +1 -1
  67. package/dist/types/crypto/pkc/ml_dsa.d.ts +6 -26
  68. package/dist/types/crypto/pkc/ml_dsa.d.ts.map +1 -1
  69. package/dist/types/crypto/pkc/ml_kem.d.ts +0 -43
  70. package/dist/types/crypto/pkc/ml_kem.d.ts.map +1 -1
  71. package/dist/types/crypto/pkc/rsa.d.ts +0 -24
  72. package/dist/types/crypto/pkc/rsa.d.ts.map +1 -1
  73. package/dist/types/crypto/pkc/slh_dsa.d.ts +6 -16
  74. package/dist/types/crypto/pkc/slh_dsa.d.ts.map +1 -1
  75. package/dist/types/crypto/pkc/x25519.d.ts +0 -6
  76. package/dist/types/crypto/pkc/x25519.d.ts.map +1 -1
  77. package/dist/types/crypto/utils/bitArray.d.ts +0 -8
  78. package/dist/types/crypto/utils/bitArray.d.ts.map +1 -1
  79. package/dist/types/crypto/utils/jws.d.ts +6 -14
  80. package/dist/types/crypto/utils/jws.d.ts.map +1 -1
  81. package/dist/types/crypto/utils/keyformat.d.ts +52 -0
  82. package/dist/types/crypto/utils/keyformat.d.ts.map +1 -1
  83. package/dist/types/crypto/utils/random.d.ts +1 -10
  84. package/dist/types/crypto/utils/random.d.ts.map +1 -1
  85. package/dist/types/crypto/utils/rsaKeygen.d.ts +0 -10
  86. package/dist/types/crypto/utils/rsaKeygen.d.ts.map +1 -1
  87. package/dist/types/crypto/utils/uuid.d.ts.map +1 -1
  88. package/dist/types/crypto/utils/x509.d.ts +397 -0
  89. package/dist/types/crypto/utils/x509.d.ts.map +1 -0
  90. package/dist/types/crypto/wasm/argon2.d.ts +2 -1
  91. package/dist/types/crypto/wasm/argon2.d.ts.map +1 -1
  92. package/dist/types/crypto/wasm/pbkdf2.d.ts +2 -2
  93. package/dist/types/crypto/wasm/pbkdf2.d.ts.map +1 -1
  94. package/dist/types/crypto/wasm/rsa.d.ts.map +1 -1
  95. package/dist/types/crypto/wasm/runtime.d.ts +13 -0
  96. package/dist/types/crypto/wasm/runtime.d.ts.map +1 -1
  97. package/dist/types/crypto/webcrypto/aes.d.ts.map +1 -1
  98. package/dist/types/crypto/webcrypto/aeskw.d.ts.map +1 -1
  99. package/dist/types/crypto/webcrypto/digest.d.ts +0 -4
  100. package/dist/types/crypto/webcrypto/digest.d.ts.map +1 -1
  101. package/dist/types/crypto/webcrypto/rsa.d.ts.map +1 -1
  102. package/dist/types/dom/fs/fileIntake.d.ts +59 -0
  103. package/dist/types/dom/fs/fileIntake.d.ts.map +1 -0
  104. package/dist/types/dom/fs/fsAccess.d.ts.map +1 -1
  105. package/dist/types/dom/query/dnd.d.ts.map +1 -1
  106. package/dist/types/dom/query/sound.d.ts +89 -0
  107. package/dist/types/dom/query/sound.d.ts.map +1 -0
  108. package/dist/types/dom/rendering/chart.d.ts.map +1 -1
  109. package/dist/types/dom/rendering/component.d.ts +9 -3
  110. package/dist/types/dom/rendering/component.d.ts.map +1 -1
  111. package/dist/types/dom/rendering/parser.d.ts +39 -0
  112. package/dist/types/dom/rendering/parser.d.ts.map +1 -1
  113. package/dist/types/dom/rendering/render.d.ts.map +1 -1
  114. package/dist/types/dom/rendering/sanitize.d.ts +4 -0
  115. package/dist/types/dom/rendering/sanitize.d.ts.map +1 -1
  116. package/dist/types/dom/rendering/secPolicy.d.ts.map +1 -1
  117. package/dist/types/dom/rendering/styleSheet.d.ts +74 -0
  118. package/dist/types/dom/rendering/styleSheet.d.ts.map +1 -0
  119. package/dist/types/dom/rendering/template.d.ts +9 -3
  120. package/dist/types/dom/rendering/template.d.ts.map +1 -1
  121. package/dist/types/dom/rendering/themeTokens.d.ts +9 -3
  122. package/dist/types/dom/rendering/themeTokens.d.ts.map +1 -1
  123. package/dist/types/dom/rendering/uiSession-core.d.ts +9 -3
  124. package/dist/types/dom/rendering/uiSession-core.d.ts.map +1 -1
  125. package/dist/types/dom/rendering/uiSession-list.d.ts +9 -3
  126. package/dist/types/dom/rendering/uiSession-list.d.ts.map +1 -1
  127. package/dist/types/dom/rendering/uiSession.d.ts +18 -6
  128. package/dist/types/dom/rendering/uiSession.d.ts.map +1 -1
  129. package/dist/types/dom/sw/installPrompt.d.ts +89 -0
  130. package/dist/types/dom/sw/installPrompt.d.ts.map +1 -0
  131. package/dist/types/dom/sw/precache.d.ts +149 -0
  132. package/dist/types/dom/sw/precache.d.ts.map +1 -0
  133. package/dist/types/dom/sw/swUpdate.d.ts +129 -0
  134. package/dist/types/dom/sw/swUpdate.d.ts.map +1 -0
  135. package/dist/types/dom/utils/clipboard.d.ts +8 -0
  136. package/dist/types/dom/utils/clipboard.d.ts.map +1 -1
  137. package/dist/types/dom/utils/keybindings.d.ts.map +1 -1
  138. package/dist/types/dom/utils/route.d.ts.map +1 -1
  139. package/dist/types/dom/utils/ua.d.ts +2 -2
  140. package/dist/types/dom/utils/ua.d.ts.map +1 -1
  141. package/dist/types/io/calc/crc32.d.ts.map +1 -1
  142. package/dist/types/io/codec/b64.d.ts +24 -0
  143. package/dist/types/io/codec/b64.d.ts.map +1 -1
  144. package/dist/types/io/codec/cbor.d.ts +1 -0
  145. package/dist/types/io/codec/cbor.d.ts.map +1 -1
  146. package/dist/types/io/codec/hex.d.ts.map +1 -1
  147. package/dist/types/io/codec/msgpack.d.ts +1 -0
  148. package/dist/types/io/codec/msgpack.d.ts.map +1 -1
  149. package/dist/types/io/codec/url.d.ts +3 -1
  150. package/dist/types/io/codec/url.d.ts.map +1 -1
  151. package/dist/types/io/codec/utf8.d.ts.map +1 -1
  152. package/dist/types/io/compress/bitstream.d.ts +1 -1
  153. package/dist/types/io/compress/brotli.d.ts +0 -1
  154. package/dist/types/io/compress/brotli.d.ts.map +1 -1
  155. package/dist/types/io/compress/brotli_shared.d.ts +0 -4
  156. package/dist/types/io/compress/brotli_shared.d.ts.map +1 -1
  157. package/dist/types/io/compress/deflate.d.ts +14 -1
  158. package/dist/types/io/compress/deflate.d.ts.map +1 -1
  159. package/dist/types/io/compress/gzip.d.ts +4 -0
  160. package/dist/types/io/compress/gzip.d.ts.map +1 -1
  161. package/dist/types/io/compress/huffman.d.ts +7 -0
  162. package/dist/types/io/compress/huffman.d.ts.map +1 -1
  163. package/dist/types/io/compress/lz4.d.ts +4 -2
  164. package/dist/types/io/compress/lz4.d.ts.map +1 -1
  165. package/dist/types/io/compress/lz77.d.ts +17 -0
  166. package/dist/types/io/compress/lz77.d.ts.map +1 -1
  167. package/dist/types/io/compress/lzw.d.ts +2 -0
  168. package/dist/types/io/compress/lzw.d.ts.map +1 -1
  169. package/dist/types/io/compress/zip.d.ts.map +1 -1
  170. package/dist/types/io/compress/zlib.d.ts +9 -2
  171. package/dist/types/io/compress/zlib.d.ts.map +1 -1
  172. package/dist/types/io/math/linalg.d.ts.map +1 -1
  173. package/dist/types/process/rpc.d.ts.map +1 -1
  174. package/dist/types/process/workerPool.d.ts.map +1 -1
  175. package/dist/types/sanity/base.d.ts +12 -2
  176. package/dist/types/sanity/base.d.ts.map +1 -1
  177. package/dist/types/sanity/lockdown.d.ts +6 -5
  178. package/dist/types/sanity/lockdown.d.ts.map +1 -1
  179. package/dist/types/sanity/wasm-gate.d.ts +1 -1
  180. package/docs/README.md +17 -10
  181. package/docs/api/README.md +5 -5
  182. package/docs/api/core/logger.md +2 -1
  183. package/docs/api/core/modules.md +3 -3
  184. package/docs/api/core/runtime.md +9 -9
  185. package/docs/api/core/worker-helper.md +12 -2
  186. package/docs/api/crypto/README.md +1 -1
  187. package/docs/api/crypto/cipher/README.md +2 -2
  188. package/docs/api/crypto/cipher/aes.md +5 -10
  189. package/docs/api/crypto/cipher/chacha20.md +3 -8
  190. package/docs/api/crypto/hash/README.md +5 -5
  191. package/docs/api/crypto/hash/adf.md +21 -11
  192. package/docs/api/crypto/hash/argon2.md +3 -12
  193. package/docs/api/crypto/hash/blake2b.md +12 -14
  194. package/docs/api/crypto/hash/pbkdf2.md +1 -1
  195. package/docs/api/crypto/hash/sha224.md +2 -2
  196. package/docs/api/crypto/hash/sha256.md +4 -4
  197. package/docs/api/crypto/hash/sha3.md +2 -2
  198. package/docs/api/crypto/hash/sha384.md +1 -1
  199. package/docs/api/crypto/hash/sha512.md +5 -5
  200. package/docs/api/crypto/hash/sha512_224.md +1 -1
  201. package/docs/api/crypto/hash/sha512_256.md +1 -1
  202. package/docs/api/crypto/mode/README.md +3 -3
  203. package/docs/api/crypto/mode/cbc.md +2 -2
  204. package/docs/api/crypto/mode/chacha20poly1305.md +1 -1
  205. package/docs/api/crypto/mode/cmac.md +4 -4
  206. package/docs/api/crypto/mode/ctr.md +2 -3
  207. package/docs/api/crypto/mode/gcm.md +5 -5
  208. package/docs/api/crypto/mode/kw.md +4 -4
  209. package/docs/api/crypto/pkc/README.md +8 -8
  210. package/docs/api/crypto/pkc/ecc.md +19 -17
  211. package/docs/api/crypto/pkc/ed25519.md +10 -15
  212. package/docs/api/crypto/pkc/hybridKem.md +8 -2
  213. package/docs/api/crypto/pkc/hybridSign.md +34 -7
  214. package/docs/api/crypto/pkc/ml_dsa.md +20 -19
  215. package/docs/api/crypto/pkc/ml_kem.md +3 -3
  216. package/docs/api/crypto/pkc/rsa.md +7 -9
  217. package/docs/api/crypto/pkc/slh_dsa.md +12 -12
  218. package/docs/api/crypto/pkc/x25519.md +5 -4
  219. package/docs/api/crypto/utils/README.md +7 -7
  220. package/docs/api/crypto/utils/aes_modes.md +2 -5
  221. package/docs/api/crypto/utils/asn1.md +25 -16
  222. package/docs/api/crypto/utils/jws.md +6 -4
  223. package/docs/api/crypto/utils/keyformat.md +24 -15
  224. package/docs/api/crypto/utils/pad.md +1 -1
  225. package/docs/api/crypto/utils/pem.md +3 -3
  226. package/docs/api/crypto/utils/random.md +3 -4
  227. package/docs/api/crypto/utils/rsaKeygen.md +2 -2
  228. package/docs/api/crypto/utils/totp.md +2 -2
  229. package/docs/api/crypto/utils/uuid.md +5 -5
  230. package/docs/api/crypto/utils/x509.md +124 -0
  231. package/docs/api/crypto/wasm/aes.md +1 -1
  232. package/docs/api/crypto/wasm/argon2.md +6 -4
  233. package/docs/api/crypto/wasm/ml_kem.md +1 -0
  234. package/docs/api/crypto/wasm/pbkdf2.md +8 -8
  235. package/docs/api/crypto/wasm/rsa.md +1 -1
  236. package/docs/api/crypto/wasm/runtime.md +27 -10
  237. package/docs/api/crypto/webcrypto/aes.md +1 -1
  238. package/docs/api/crypto/webcrypto/aeskw.md +2 -2
  239. package/docs/api/crypto/webcrypto/digest.md +3 -5
  240. package/docs/api/crypto/webcrypto/ecc.md +1 -1
  241. package/docs/api/crypto/webcrypto/ed25519.md +1 -1
  242. package/docs/api/crypto/webcrypto/rsa.md +3 -2
  243. package/docs/api/crypto/webcrypto/x25519.md +1 -1
  244. package/docs/api/dom/README.md +6 -1
  245. package/docs/api/dom/fs/README.md +1 -0
  246. package/docs/api/dom/fs/fileIntake.md +120 -0
  247. package/docs/api/dom/fs/fsAccess.md +1 -0
  248. package/docs/api/dom/fs/indexedDB.md +1 -1
  249. package/docs/api/dom/fs/storage.md +1 -1
  250. package/docs/api/dom/query/README.md +2 -1
  251. package/docs/api/dom/query/dnd.md +4 -1
  252. package/docs/api/dom/query/dom.md +5 -0
  253. package/docs/api/dom/query/sound.md +103 -0
  254. package/docs/api/dom/rendering/README.md +4 -3
  255. package/docs/api/dom/rendering/chart.md +5 -4
  256. package/docs/api/dom/rendering/component.md +25 -3
  257. package/docs/api/dom/rendering/parser.md +5 -2
  258. package/docs/api/dom/rendering/reactiveBind.md +1 -1
  259. package/docs/api/dom/rendering/render.md +2 -2
  260. package/docs/api/dom/rendering/sanitize.md +10 -2
  261. package/docs/api/dom/rendering/secPolicy.md +4 -4
  262. package/docs/api/dom/rendering/styleSheet.md +85 -0
  263. package/docs/api/dom/rendering/template.md +20 -5
  264. package/docs/api/dom/rendering/themeTokens.md +6 -3
  265. package/docs/api/dom/rendering/uiSession.md +18 -5
  266. package/docs/api/dom/rendering/virtualScroll.md +2 -2
  267. package/docs/api/dom/sensors/geolocation.md +1 -1
  268. package/docs/api/dom/sw/README.md +7 -1
  269. package/docs/api/dom/sw/cache.md +2 -1
  270. package/docs/api/dom/sw/installPrompt.md +111 -0
  271. package/docs/api/dom/sw/precache.md +124 -0
  272. package/docs/api/dom/sw/serviceWorker.md +4 -2
  273. package/docs/api/dom/sw/swUpdate.md +112 -0
  274. package/docs/api/dom/utils/clipboard.md +56 -5
  275. package/docs/api/dom/utils/entropyCollector.md +1 -1
  276. package/docs/api/dom/utils/keybindings.md +17 -2
  277. package/docs/api/dom/utils/leaderElection.md +2 -2
  278. package/docs/api/dom/utils/route.md +1 -0
  279. package/docs/api/dom/utils/ua.md +15 -10
  280. package/docs/api/io/calc/crc32.md +4 -1
  281. package/docs/api/io/codec/README.md +2 -2
  282. package/docs/api/io/codec/b64.md +31 -2
  283. package/docs/api/io/codec/buffer.md +1 -1
  284. package/docs/api/io/codec/cbor.md +6 -4
  285. package/docs/api/io/codec/csv.md +178 -178
  286. package/docs/api/io/codec/hex.md +10 -2
  287. package/docs/api/io/codec/msgpack.md +4 -3
  288. package/docs/api/io/codec/url.md +4 -3
  289. package/docs/api/io/codec/utf8.md +3 -3
  290. package/docs/api/io/compress/bitstream.md +6 -3
  291. package/docs/api/io/compress/brotli.md +36 -4
  292. package/docs/api/io/compress/brotli_shared.md +1 -1
  293. package/docs/api/io/compress/deflate.md +42 -34
  294. package/docs/api/io/compress/gzip.md +26 -6
  295. package/docs/api/io/compress/huffman.md +2 -1
  296. package/docs/api/io/compress/lz4.md +5 -3
  297. package/docs/api/io/compress/lz77.md +26 -3
  298. package/docs/api/io/compress/lzw.md +13 -8
  299. package/docs/api/io/compress/zip.md +36 -10
  300. package/docs/api/io/compress/zlib.md +21 -5
  301. package/docs/api/io/math/linalg.md +1 -1
  302. package/docs/api/io/utils/valid.md +1 -1
  303. package/docs/api/process/rpc.md +3 -2
  304. package/docs/api/process/workerPool.md +1 -1
  305. package/docs/api/sanity/base.md +9 -5
  306. package/docs/api/sanity/lockdown.md +7 -6
  307. package/docs/api/surface.json +12311 -0
  308. package/docs/api/typed.md +5 -3
  309. package/docs/dev/README.md +2 -0
  310. package/docs/dev/bench.md +76 -0
  311. package/docs/dev/crypto-references.md +54 -0
  312. package/docs/dev/provenance.md +30 -7
  313. package/docs/dev/publishing.md +7 -7
  314. package/docs/dev/runtime.md +1 -1
  315. package/docs/dev/testing.md +13 -0
  316. package/docs/evidence/l4-evidence.md +86 -0
  317. package/docs/evidence/pqc-hybrid-evidence.md +7 -6
  318. package/docs/guide/README.md +1 -0
  319. package/docs/guide/_QUICK_REF.md +5 -5
  320. package/docs/guide/doc-format.md +4 -3
  321. package/docs/guide/integrations-hmr.md +1 -1
  322. package/docs/guide/module-creation-workflow.md +8 -8
  323. package/docs/guide/rendering-pipeline.md +11 -4
  324. package/docs/guide/security.md +7 -5
  325. package/docs/guide/stability.md +123 -0
  326. package/docs/guide/tutorial-todo.md +20 -8
  327. package/docs/guide/typescript.md +9 -0
  328. package/docs/guide/worker-confinement.md +30 -17
  329. package/docs/notes/lz77-deflate-factorization.md +3 -3
  330. package/docs/tools/README.md +1 -1
  331. package/docs/tools/bundler.md +3 -3
  332. package/docs/tools/codegen.md +1 -1
  333. package/docs/tools/standalone.md +0 -1
  334. package/fw.config.json +2 -2
  335. package/integrations/_shared/catalog.generated.json +7 -1
  336. package/integrations/_shared/core.js +1 -1
  337. package/integrations/astro/index.js +1 -1
  338. package/integrations/eslint/README.md +7 -1
  339. package/integrations/nextjs/index.js +1 -1
  340. package/integrations/nodejs/README.md +3 -3
  341. package/integrations/turbopack/index.js +2 -2
  342. package/integrations/typedoc/categorize.js +1 -1
  343. package/integrations/typedoc/typedoc.json +2 -1
  344. package/integrations/vite/index.js +2 -2
  345. package/integrations/vite/vite-env.d.ts +7 -4
  346. package/integrations/webpack/index.js +3 -3
  347. package/package.json +76 -10
  348. package/src/core/internal.js +31 -0
  349. package/src/core/logger.js +95 -23
  350. package/src/core/modules.js +17 -8
  351. package/src/core/readyState.js +1 -1
  352. package/src/core/runtime.js +74 -27
  353. package/src/core/worker-helper.js +83 -4
  354. package/src/crypto/NIST_CONFORMANCE.md +47 -34
  355. package/src/crypto/cipher/aes.acvp.md +7 -8
  356. package/src/crypto/cipher/aes.js +280 -229
  357. package/src/crypto/cipher/chacha20.acvp.md +6 -7
  358. package/src/crypto/cipher/chacha20.js +91 -61
  359. package/src/crypto/hash/adf.js +1 -1
  360. package/src/crypto/hash/argon2.acvp.md +11 -15
  361. package/src/crypto/hash/argon2.js +9 -24
  362. package/src/crypto/hash/blake2b.js +157 -125
  363. package/src/crypto/hash/hkdf.acvp.md +15 -15
  364. package/src/crypto/hash/hkdf.js +1 -1
  365. package/src/crypto/hash/hmac.acvp.md +10 -12
  366. package/src/crypto/hash/hmac.js +5 -1
  367. package/src/crypto/hash/pbkdf2.acvp.md +13 -13
  368. package/src/crypto/hash/pbkdf2.js +36 -8
  369. package/src/crypto/hash/poly1305.acvp.md +10 -6
  370. package/src/crypto/hash/poly1305.js +171 -50
  371. package/src/crypto/hash/sha224.acvp.md +3 -3
  372. package/src/crypto/hash/sha224.js +4 -4
  373. package/src/crypto/hash/sha256.acvp.md +2 -2
  374. package/src/crypto/hash/sha256.js +514 -50
  375. package/src/crypto/hash/sha3.acvp.md +9 -9
  376. package/src/crypto/hash/sha3.js +127 -71
  377. package/src/crypto/hash/sha384.acvp.md +3 -3
  378. package/src/crypto/hash/sha384.js +4 -4
  379. package/src/crypto/hash/sha512.acvp.md +7 -8
  380. package/src/crypto/hash/sha512.js +107 -108
  381. package/src/crypto/hash/sha512_224.acvp.md +6 -6
  382. package/src/crypto/hash/sha512_224.js +2 -2
  383. package/src/crypto/hash/sha512_256.acvp.md +6 -6
  384. package/src/crypto/hash/sha512_256.js +2 -2
  385. package/src/crypto/mode/cbc.acvp.md +2 -2
  386. package/src/crypto/mode/cbc.js +1 -1
  387. package/src/crypto/mode/chacha20poly1305.acvp.md +6 -6
  388. package/src/crypto/mode/chacha20poly1305.js +3 -3
  389. package/src/crypto/mode/cmac.acvp.md +5 -5
  390. package/src/crypto/mode/cmac.js +8 -8
  391. package/src/crypto/mode/ctr.acvp.md +2 -2
  392. package/src/crypto/mode/ctr.js +1 -3
  393. package/src/crypto/mode/gcm.acvp.md +6 -6
  394. package/src/crypto/mode/gcm.js +7 -7
  395. package/src/crypto/mode/kw.acvp.md +4 -4
  396. package/src/crypto/mode/kw.js +5 -5
  397. package/src/crypto/pkc/ecc.acvp.md +13 -13
  398. package/src/crypto/pkc/ecc.js +9 -11
  399. package/src/crypto/pkc/ed25519.acvp.md +30 -34
  400. package/src/crypto/pkc/ed25519.js +453 -94
  401. package/src/crypto/pkc/hybrid-kat.provenance.md +4 -4
  402. package/src/crypto/pkc/hybridSign.js +103 -24
  403. package/src/crypto/pkc/ml_dsa.acvp.md +18 -18
  404. package/src/crypto/pkc/ml_dsa.js +29 -32
  405. package/src/crypto/pkc/ml_kem.acvp.md +7 -7
  406. package/src/crypto/pkc/ml_kem.js +15 -21
  407. package/src/crypto/pkc/rsa.acvp.md +11 -15
  408. package/src/crypto/pkc/rsa.js +7 -44
  409. package/src/crypto/pkc/slh_dsa.acvp.md +16 -16
  410. package/src/crypto/pkc/slh_dsa.js +16 -18
  411. package/src/crypto/pkc/x25519.acvp.md +13 -10
  412. package/src/crypto/pkc/x25519.js +273 -29
  413. package/src/crypto/utils/aes_modes.acvp.md +1 -2
  414. package/src/crypto/utils/aes_modes.js +2 -2
  415. package/src/crypto/utils/asn1-oid.js +1 -1
  416. package/src/crypto/utils/asn1.js +1 -1
  417. package/src/crypto/utils/bitArray.js +33 -48
  418. package/src/crypto/utils/bn.js +1 -1
  419. package/src/crypto/utils/jws.js +37 -41
  420. package/src/crypto/utils/keyformat.js +181 -2
  421. package/src/crypto/utils/pem.js +1 -1
  422. package/src/crypto/utils/random.acvp.md +5 -5
  423. package/src/crypto/utils/random.js +845 -846
  424. package/src/crypto/utils/rsaKeygen.acvp.md +3 -2
  425. package/src/crypto/utils/rsaKeygen.js +6 -6
  426. package/src/crypto/utils/totp.js +1 -1
  427. package/src/crypto/utils/uuid.acvp.md +5 -5
  428. package/src/crypto/utils/uuid.js +11 -10
  429. package/src/crypto/utils/x509.js +591 -0
  430. package/src/crypto/wasm/aes.js +1 -1
  431. package/src/crypto/wasm/aes.scalar.wasm +0 -0
  432. package/src/crypto/wasm/argon2.js +17 -1
  433. package/src/crypto/wasm/argon2.scalar.wasm +0 -0
  434. package/src/crypto/wasm/blake2b.scalar.wasm +0 -0
  435. package/src/crypto/wasm/blake2b.simd.wasm +0 -0
  436. package/src/crypto/wasm/chacha20poly1305.scalar.wasm +0 -0
  437. package/src/crypto/wasm/chacha20poly1305.simd.wasm +0 -0
  438. package/src/crypto/wasm/cmac.scalar.wasm +0 -0
  439. package/src/crypto/wasm/ecc.js +3 -3
  440. package/src/crypto/wasm/ecc.scalar.wasm +0 -0
  441. package/src/crypto/wasm/ed25519.js +1 -1
  442. package/src/crypto/wasm/ed25519.scalar.wasm +0 -0
  443. package/src/crypto/wasm/hkdf.scalar.wasm +0 -0
  444. package/src/crypto/wasm/hmac.scalar.wasm +0 -0
  445. package/src/crypto/wasm/ml_dsa.js +2 -2
  446. package/src/crypto/wasm/ml_dsa.scalar.wasm +0 -0
  447. package/src/crypto/wasm/ml_dsa.simd.wasm +0 -0
  448. package/src/crypto/wasm/ml_kem.js +2 -2
  449. package/src/crypto/wasm/ml_kem.scalar.wasm +0 -0
  450. package/src/crypto/wasm/ml_kem.simd.wasm +0 -0
  451. package/src/crypto/wasm/pbkdf2.js +8 -6
  452. package/src/crypto/wasm/pbkdf2.scalar.wasm +0 -0
  453. package/src/crypto/wasm/rsa.js +6 -5
  454. package/src/crypto/wasm/rsa.scalar.wasm +0 -0
  455. package/src/crypto/wasm/runtime.js +84 -17
  456. package/src/crypto/wasm/sha2.scalar.wasm +0 -0
  457. package/src/crypto/wasm/sha3.scalar.wasm +0 -0
  458. package/src/crypto/wasm/sha3.simd.wasm +0 -0
  459. package/src/crypto/wasm/slh_dsa.js +1 -1
  460. package/src/crypto/wasm/slh_dsa.scalar.wasm +0 -0
  461. package/src/crypto/wasm/x25519.js +1 -1
  462. package/src/crypto/wasm/x25519.scalar.wasm +0 -0
  463. package/src/crypto/webcrypto/aes.js +8 -2
  464. package/src/crypto/webcrypto/aeskw.js +7 -2
  465. package/src/crypto/webcrypto/digest.js +1 -15
  466. package/src/crypto/webcrypto/ecc.js +2 -2
  467. package/src/crypto/webcrypto/ed25519.js +2 -2
  468. package/src/crypto/webcrypto/hmac.js +2 -2
  469. package/src/crypto/webcrypto/rsa.js +7 -2
  470. package/src/crypto/webcrypto/x25519.js +2 -2
  471. package/src/dom/display/animate.js +1 -1
  472. package/src/dom/display/fullscreen.js +1 -1
  473. package/src/dom/fs/download.js +1 -1
  474. package/src/dom/fs/fileIntake.js +192 -0
  475. package/src/dom/fs/fsAccess.js +2 -3
  476. package/src/dom/fs/indexedDB.js +1 -1
  477. package/src/dom/fs/remoteStore.js +1 -1
  478. package/src/dom/fs/storage.js +1 -1
  479. package/src/dom/lifecycle/idle.js +1 -1
  480. package/src/dom/lifecycle/visibility.js +1 -1
  481. package/src/dom/lifecycle/wakeLock.js +1 -1
  482. package/src/dom/net/ajax.js +1 -1
  483. package/src/dom/net/network.js +1 -1
  484. package/src/dom/net/sse.js +1 -1
  485. package/src/dom/net/webrtc.js +1 -1
  486. package/src/dom/net/ws.js +1 -1
  487. package/src/dom/query/dnd.js +56 -4
  488. package/src/dom/query/dom.js +1 -1
  489. package/src/dom/query/events.js +1 -1
  490. package/src/dom/query/gesture.js +1 -1
  491. package/src/dom/query/media.js +1 -1
  492. package/src/dom/query/sound.js +333 -0
  493. package/src/dom/rendering/chart.js +736 -663
  494. package/src/dom/rendering/component.js +25 -14
  495. package/src/dom/rendering/devtools.js +2 -2
  496. package/src/dom/rendering/parser.js +155 -12
  497. package/src/dom/rendering/render.js +14 -4
  498. package/src/dom/rendering/sanitize.js +11 -4
  499. package/src/dom/rendering/secPolicy.js +6 -4
  500. package/src/dom/rendering/styleSheet.js +217 -0
  501. package/src/dom/rendering/template.js +72 -13
  502. package/src/dom/rendering/themeTokens.js +542 -522
  503. package/src/dom/rendering/uiSession-core.js +51 -6
  504. package/src/dom/rendering/uiSession-direct.js +1 -1
  505. package/src/dom/rendering/uiSession-list.js +4 -4
  506. package/src/dom/rendering/uiSession.js +1 -1
  507. package/src/dom/rendering/virtualScroll.js +341 -341
  508. package/src/dom/sensors/battery.js +1 -1
  509. package/src/dom/sensors/geolocation.js +1 -1
  510. package/src/dom/sensors/networkInfo.js +1 -1
  511. package/src/dom/sensors/sensors.js +1 -1
  512. package/src/dom/sw/backgroundSync.js +1 -1
  513. package/src/dom/sw/cache.js +1 -1
  514. package/src/dom/sw/installPrompt.js +151 -0
  515. package/src/dom/sw/precache.js +257 -0
  516. package/src/dom/sw/push.js +1 -1
  517. package/src/dom/sw/sharedWorker.js +1 -1
  518. package/src/dom/sw/swUpdate.js +239 -0
  519. package/src/dom/utils/a11y.js +1 -1
  520. package/src/dom/utils/clipboard.js +56 -6
  521. package/src/dom/utils/entropyCollector.js +1 -1
  522. package/src/dom/utils/focus.js +1 -1
  523. package/src/dom/utils/form.js +1 -1
  524. package/src/dom/utils/keybindings.js +600 -574
  525. package/src/dom/utils/leaderElection.js +1 -1
  526. package/src/dom/utils/notifications.js +1 -1
  527. package/src/dom/utils/permissions.js +107 -107
  528. package/src/dom/utils/route.js +14 -2
  529. package/src/dom/utils/ua.js +42 -28
  530. package/src/dom/utils/webauthn.js +1 -1
  531. package/src/io/binary/reader.js +1 -1
  532. package/src/io/binary/writer.js +1 -1
  533. package/src/io/calc/bigint.js +1 -1
  534. package/src/io/calc/crc32.js +28 -2
  535. package/src/io/calc/easing.js +514 -514
  536. package/src/io/codec/b64.js +189 -52
  537. package/src/io/codec/base32.js +1 -1
  538. package/src/io/codec/base58.js +1 -1
  539. package/src/io/codec/buffer.js +1 -1
  540. package/src/io/codec/cbor.js +111 -18
  541. package/src/io/codec/csv.js +1 -1
  542. package/src/io/codec/hex.js +51 -6
  543. package/src/io/codec/mime.js +1 -1
  544. package/src/io/codec/msgpack.js +47 -6
  545. package/src/io/codec/url.js +24 -7
  546. package/src/io/codec/utf8.js +5 -3
  547. package/src/io/codec/xml.js +1 -1
  548. package/src/io/compress/bitstream.js +2 -2
  549. package/src/io/compress/brotli.js +663 -163
  550. package/src/io/compress/brotli_dict.js +1 -1
  551. package/src/io/compress/brotli_dict_words.js +1 -1
  552. package/src/io/compress/brotli_frame.js +1 -1
  553. package/src/io/compress/brotli_shared.js +7 -7
  554. package/src/io/compress/deflate.js +87 -53
  555. package/src/io/compress/gzip.js +187 -74
  556. package/src/io/compress/huffman.js +24 -1
  557. package/src/io/compress/lz4.js +45 -7
  558. package/src/io/compress/lz77.js +148 -63
  559. package/src/io/compress/lzw.js +35 -19
  560. package/src/io/compress/zip.js +862 -815
  561. package/src/io/compress/zlib.js +87 -7
  562. package/src/io/i18n/i18n.js +1 -1
  563. package/src/io/math/fixed-point.js +1 -1
  564. package/src/io/math/geom.js +1 -1
  565. package/src/io/math/interp.js +1 -1
  566. package/src/io/math/linalg.js +10 -4
  567. package/src/io/math/stats.js +1 -1
  568. package/src/io/structures/btree.js +1 -1
  569. package/src/io/structures/heap.js +1 -1
  570. package/src/io/structures/lruCache.js +1 -1
  571. package/src/io/structures/ringBuffer.js +1 -1
  572. package/src/io/structures/tree-walker.js +1 -1
  573. package/src/io/structures/trie.js +1 -1
  574. package/src/io/sync/abort.js +1 -1
  575. package/src/io/sync/atomics.js +1 -1
  576. package/src/io/sync/cancellable.js +1 -1
  577. package/src/io/sync/channel.js +1 -1
  578. package/src/io/sync/mutex.js +1 -1
  579. package/src/io/sync/semaphore.js +1 -1
  580. package/src/io/sync/tokenBucket.js +1 -1
  581. package/src/io/text/ansi.js +1 -1
  582. package/src/io/text/html-entities.js +1 -1
  583. package/src/io/time/date.js +1 -1
  584. package/src/io/timing/clock.js +1 -1
  585. package/src/io/timing/rateLimit.js +1 -1
  586. package/src/io/timing/scheduler.js +1 -1
  587. package/src/io/utils/errors.js +1 -1
  588. package/src/io/utils/eventBus.js +1 -1
  589. package/src/io/utils/signal.js +1 -1
  590. package/src/io/utils/valid.js +1 -1
  591. package/src/main.js +1 -1
  592. package/src/process/message.js +1 -1
  593. package/src/process/rpc.js +7 -3
  594. package/src/process/workerPool.js +11 -4
  595. package/src/sanity/base.js +85 -39
  596. package/src/sanity/lockdown-apply.js +3 -3
  597. package/src/sanity/lockdown.js +58 -32
  598. package/src/sanity/wasm-gate.js +2 -2
  599. package/src/typed.js +7 -3
  600. package/third-party/NOTICE-brotli-dictionary.txt +69 -0
  601. package/third-party/NOTICE-fw-wasm-crypto.txt +576 -0
  602. package/third-party/NOTICE-whatwg-entities.txt +44 -0
  603. package/types/registry.generated.d.ts +7 -1
  604. package/types/typed.d.ts +7 -3
  605. package/dist/types/crypto/utils/aes_ctr.d.ts +0 -84
  606. package/dist/types/crypto/utils/aes_ctr.d.ts.map +0 -1
  607. package/docs/api/crypto/utils/aes_ctr.md +0 -71
  608. package/src/crypto/utils/aes_ctr.acvp.md +0 -67
  609. package/src/crypto/utils/aes_ctr.js +0 -134
@@ -1,4 +1,4 @@
1
- // Copyright (c) 2026 AwaCloud SAS
1
+ // Copyright (c) 2026 AwaCloud SAS
2
2
  // Author: Matthieu Bouilloux
3
3
  // SPDX-License-Identifier: Apache-2.0
4
4
 
@@ -35,7 +35,8 @@
35
35
  *
36
36
  * One public option: `opts.quality ∈ [0, 11]` (default `6`) - speed/ratio
37
37
  * profile (`0` = trivial uncompressed, `1..3` chainDepth 2..4 lazy off,
38
- * `4..7` lazy on, `8..11` block splitting + chainDepth 16..32).
38
+ * `4..6` chainDepth 6..10 lazy on, from `6` one literal block split,
39
+ * `7..11` chainDepth 64..128 with the search ended by a 32..128-byte match).
39
40
  *
40
41
  * ## Static dictionary
41
42
  *
@@ -83,7 +84,6 @@
83
84
  * @property {(data: Uint8Array, opts?: object) => Promise<Uint8Array>} brotliDecompress
84
85
  * @property {BrotliCompressStreamCtor} BrotliCompressStream
85
86
  * @property {BrotliDecompressStreamCtor} BrotliDecompressStream
86
- * @property {object} _internal
87
87
  */
88
88
 
89
89
  import { bitstream } from './bitstream.js';
@@ -407,6 +407,7 @@ export const brotli = {
407
407
 
408
408
  // Compressed meta-block: header + body
409
409
  const h = _readCompressedMetaBlockHeader(r, state.largeWindow);
410
+ _reserveOutput(state, mlen);
410
411
  _decodeCompressedBody(r, h, state, mlen);
411
412
  return { done: islast === 1, last: islast === 1 };
412
413
  }
@@ -459,6 +460,9 @@ export const brotli = {
459
460
  return {
460
461
  read(_r) { return symbol; },
461
462
  singleSymbol: symbol,
463
+ // Same shape as a table decoder; `table: null` tells the
464
+ // decoder's inlined literal read to call `read`.
465
+ table: null, mask: 0, maxBits: 0,
462
466
  };
463
467
  }
464
468
 
@@ -491,6 +495,9 @@ export const brotli = {
491
495
  return entry >>> 4;
492
496
  },
493
497
  alphabetSize,
498
+ // Read inline by the literal loop of `_decodeCompressedBody`,
499
+ // which repeats `read`'s steps on a local bit position.
500
+ table, mask, maxBits,
494
501
  };
495
502
  }
496
503
 
@@ -551,7 +558,7 @@ export const brotli = {
551
558
  }
552
559
 
553
560
  function _readComplexPrefixCode(r, alphabetSize, hskip) {
554
- // --- Phase 1: read code lengths for the CL alphabet (§3.5) ---
561
+ // --- Part 1: read code lengths for the CL alphabet (§3.5) ---
555
562
  //
556
563
  // The CL alphabet has 18 symbols (0-15 = literal CL, 16/17 =
557
564
  // repeat opcodes). Their CL-of-CL values ∈ [0, 5] are stored in
@@ -596,7 +603,7 @@ export const brotli = {
596
603
  return _makeSingleSymbolDecoder(sym);
597
604
  })();
598
605
 
599
- // --- Phase 2: read RLE-encoded code lengths for the target alphabet ---
606
+ // --- Part 2: read RLE-encoded code lengths for the target alphabet ---
600
607
 
601
608
  const lens = new u8(alphabetSize);
602
609
  let i = 0;
@@ -866,6 +873,15 @@ export const brotli = {
866
873
  70, 102, 134, 198, 326, 582, 1094, 2118,
867
874
  ]);
868
875
 
876
+ // `_splitIacSym` per symbol, tabulated once (704 entries each).
877
+ const _IAC_INS = new u8(704), _IAC_COPY = new u8(704), _IAC_DZ = new u8(704);
878
+ for (let sym = 0; sym < 704; ++sym) {
879
+ const cell = sym >> 6;
880
+ _IAC_INS[sym] = _IAC_I_BASE[cell] + ((sym >> 3) & 7);
881
+ _IAC_COPY[sym] = _IAC_C_BASE[cell] + (sym & 7);
882
+ _IAC_DZ[sym] = cell < 2 ? 1 : 0;
883
+ }
884
+
869
885
  function _splitIacSym(iacSym) {
870
886
  const cell = iacSym >> 6;
871
887
  if (cell >= 11) _err('EBADSTREAM', 'iac symbol ' + iacSym + ' out of range');
@@ -876,12 +892,6 @@ export const brotli = {
876
892
  };
877
893
  }
878
894
 
879
- function _readLength(r, baseArr, extraArr, code) {
880
- const eb = extraArr[code];
881
- const extra = eb <= 16 ? _readBits(r, eb) : _readBitsBig(r, eb);
882
- return baseArr[code] + extra;
883
- }
884
-
885
895
  // --- §4 - Distance decoding ---
886
896
  //
887
897
  // Special symbols 0..15 reference past distances with offsets.
@@ -1023,10 +1033,35 @@ export const brotli = {
1023
1033
 
1024
1034
  // --- Output buffer growth ---
1025
1035
 
1036
+ // `state.limit` is `maxOutput` (Infinity without a cap): past it the
1037
+ // decoder throws EMAXOUT before growing, and never grows beyond it.
1038
+ /**
1039
+ * Grow the output once for a meta-block of `mlen` bytes (doubling,
1040
+ * capped at the limit), so the body's per-command `_ensureCapacity`
1041
+ * calls find the room already there. It never throws: whether the
1042
+ * limit is exceeded is still decided byte by byte, where it was.
1043
+ * @param {object} state
1044
+ * @param {number} mlen
1045
+ */
1046
+ function _reserveOutput(state, mlen) {
1047
+ const need = Math.min(state.outLen + mlen, state.limit);
1048
+ if (need <= state.out.length) return;
1049
+ let newSize = state.out.length || 1024;
1050
+ while (newSize < need) newSize *= 2;
1051
+ newSize = Math.min(newSize, state.limit);
1052
+ const grown = new u8(newSize);
1053
+ grown.set(state.out.subarray(0, state.outLen));
1054
+ state.out = grown;
1055
+ }
1056
+
1026
1057
  function _ensureCapacity(state, additional) {
1058
+ if (state.outLen + additional > state.limit) {
1059
+ _err('EMAXOUT', 'output limit exceeded (maxOutput ' + state.limit + ')');
1060
+ }
1027
1061
  if (state.outLen + additional > state.out.length) {
1028
- let newSize = state.out.length;
1062
+ let newSize = state.out.length || 1024;
1029
1063
  while (newSize < state.outLen + additional) newSize *= 2;
1064
+ newSize = Math.min(newSize, state.limit);
1030
1065
  const grown = new u8(newSize);
1031
1066
  grown.set(state.out.subarray(0, state.outLen));
1032
1067
  state.out = grown;
@@ -1048,6 +1083,86 @@ export const brotli = {
1048
1083
 
1049
1084
  // --- §10 - Command loop for one compressed meta-block ---
1050
1085
 
1086
+ /**
1087
+ * A static-dictionary reference's word (RFC 7932 §8, or the RFC 9841
1088
+ * §3.1 hook), written to the output: out of `_decodeCompressedBody`,
1089
+ * whose hot loop JavaScriptCore optimises less, and less steadily, as it
1090
+ * grows.
1091
+ * @param {object} r
1092
+ * @param {object} h
1093
+ * @param {object} state
1094
+ * @param {number} wordId
1095
+ * @param {number} clen
1096
+ * @param {number} remaining
1097
+ * @param {number} btypeL
1098
+ */
1099
+ function _copyStaticDictRef(r, h, state, wordId, clen, remaining, btypeL) {
1100
+ let transformed;
1101
+
1102
+ if (state.resolveStaticDictRef) {
1103
+ // Extension hook (RFC 9841 §3.1 custom-dict path,
1104
+ // owned by `brotli_shared`). The callback handles
1105
+ // length bounds, dict selection, transform
1106
+ // application - brotli.js stays RFC 7932 here.
1107
+ const cidL = _contextIdLit(h.cmode[btypeL], state.p1, state.p2);
1108
+ transformed = state.resolveStaticDictRef(state, wordId, clen, cidL, r);
1109
+ } else {
1110
+ // RFC 7932 §8 - built-in static dictionary.
1111
+ if (clen < 4 || clen > 24) {
1112
+ _err('EBADSTREAM', 'static dict ref length ' + clen + ' not in [4, 24]', r.p);
1113
+ }
1114
+ _ensureDictLoaded(r);
1115
+ const nw = brotliDict.NWORDS(clen);
1116
+ const index = wordId % nw;
1117
+ const transformId = (wordId - index) / nw;
1118
+ if (transformId >= 121) _err('EBADSTREAM', 'static dict transform id ' + transformId + ' >= 121', r.p);
1119
+ const baseWord = brotliDict.lookupWord(clen, index);
1120
+ transformed = brotliDict.applyTransform(transformId, baseWord);
1121
+ }
1122
+
1123
+ const writeLen = transformed.length < remaining ? transformed.length : remaining;
1124
+ _ensureCapacity(state, writeLen);
1125
+ // A word is 4-24 bytes plus its transform's affixes: a
1126
+ // plain loop, where a `subarray` + `set` pair cost more
1127
+ // than the copy (44 % of a text decode under V8).
1128
+ const out = state.out;
1129
+ let outLen = state.outLen;
1130
+ for (let k = 0; k < writeLen; ++k) out[outLen++] = transformed[k];
1131
+ state.outLen = outLen;
1132
+ }
1133
+
1134
+ /**
1135
+ * An RFC 9841 §3.2 LZ77-dictionary reference, written to the output
1136
+ * (see `_copyStaticDictRef` for why it is a function).
1137
+ * @param {object} state
1138
+ * @param {number} distance
1139
+ * @param {number} maxAllowed
1140
+ * @param {number} lz77DictLen
1141
+ * @param {number} clen
1142
+ * @param {number} remaining
1143
+ */
1144
+ function _copyLz77DictRef(state, distance, maxAllowed, lz77DictLen, clen, remaining) {
1145
+ // RFC 9841 §3.2: dictionary_address = L + maxAllowed - distance
1146
+ // First copy from lz77Dict[dictAddr..L), then if more
1147
+ // is needed continue from output[windowStart..) (the
1148
+ // oldest byte still in the regular LZ77 window).
1149
+ const dictAddr = lz77DictLen + maxAllowed - distance;
1150
+ const fromDictBytes = lz77DictLen - dictAddr;
1151
+ const writeLen = clen < remaining ? clen : remaining;
1152
+ _ensureCapacity(state, writeLen);
1153
+ const outStart = state.outLen;
1154
+ const windowStart = outStart > state.windowSize ? outStart - state.windowSize : 0;
1155
+ let k = 0;
1156
+ while (k < writeLen && k < fromDictBytes) {
1157
+ state.out[state.outLen++] = state.lz77Dict[dictAddr + k];
1158
+ ++k;
1159
+ }
1160
+ while (k < writeLen) {
1161
+ state.out[state.outLen++] = state.out[windowStart + (k - fromDictBytes)];
1162
+ ++k;
1163
+ }
1164
+ }
1165
+
1051
1166
  function _decodeCompressedBody(r, h, state, mlen) {
1052
1167
  const startLen = state.outLen;
1053
1168
 
@@ -1057,20 +1172,68 @@ export const brotli = {
1057
1172
  let btypeD = 0, prevBtypeD = 1;
1058
1173
  let blenL = h.blenL, blenI = h.blenI, blenD = h.blenD;
1059
1174
 
1175
+ // The command's reads - its insert-and-copy symbol, the two
1176
+ // lengths' extra bits, the literals, the distance symbol and its
1177
+ // extra bits - run on a local bit position `bp`, as
1178
+ // `_makeTableDecoder`'s `read` and `_readBits` would, step for
1179
+ // step (a call per read cost about a sixth of a json decode).
1180
+ // `r.p` is synced around every call that reads the stream or
1181
+ // throws, and when the loop ends. A throw leaves `state` at the
1182
+ // command's start, which the stream's meta-block snapshot
1183
+ // restores anyway.
1184
+ const d = r.d, eofBits = r.eofBits, canMore = r.canExpectMore;
1185
+ const htreeI = h.htreeI, htreeD = h.htreeD, cmapD = h.cmapD;
1186
+ const npostfix = h.npostfix, ndirect = h.ndirect, lastDist = state.lastDist;
1187
+ let bp = r.p;
1188
+
1060
1189
  while (state.outLen - startLen < mlen) {
1061
1190
  // --- Block-switch for IAC ---
1062
1191
  if (blenI === 0) {
1192
+ r.p = bp;
1063
1193
  const nb = _decodeBlockType(h.htreeBtypeI, h.nbltypesI, btypeI, prevBtypeI, r);
1064
1194
  prevBtypeI = btypeI; btypeI = nb;
1065
1195
  blenI = _readBlockCount(r, h.htreeBlenI);
1196
+ bp = r.p;
1066
1197
  }
1067
1198
  blenI--;
1068
1199
 
1069
1200
  // --- IAC sym → ILEN, CLEN, distZero ---
1070
- const iacSym = h.htreeI[btypeI].read(r);
1071
- const { insertCode, copyCode, distZero } = _splitIacSym(iacSym);
1072
- const ilen = _readLength(r, _INSERT_BASE, _INSERT_EXTRA, insertCode);
1073
- const clen = _readLength(r, _COPY_BASE, _COPY_EXTRA, copyCode);
1201
+ const treeI = htreeI[btypeI];
1202
+ const tableI = treeI.table;
1203
+ let iacSym;
1204
+ if (tableI === null) {
1205
+ r.p = bp; iacSym = treeI.read(r); bp = r.p;
1206
+ } else {
1207
+ if (canMore && bp + treeI.maxBits > eofBits) { r.p = bp; _eofThrow(r); }
1208
+ const o = bp >> 3;
1209
+ const entry = tableI[((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >>> (bp & 7)) & treeI.mask];
1210
+ const len = entry & 0x0F;
1211
+ if (len === 0) _err('EBADSTREAM', 'undefined prefix code', bp);
1212
+ bp += len;
1213
+ if (bp > eofBits) { r.p = bp; _eofThrow(r); }
1214
+ iacSym = entry >>> 4;
1215
+ }
1216
+ if (iacSym >= 704) _err('EBADSTREAM', 'iac symbol ' + iacSym + ' out of range');
1217
+ const distZero = _IAC_DZ[iacSym] === 1;
1218
+ // The extra bits: at most 24 each, a 4-byte load at any
1219
+ // shift (the reader buffer is padded by 4 zero bytes).
1220
+ const icode = _IAC_INS[iacSym], ccode = _IAC_COPY[iacSym];
1221
+ let ilen = _INSERT_BASE[icode];
1222
+ const ie = _INSERT_EXTRA[icode];
1223
+ if (ie > 0) {
1224
+ if (bp + ie > eofBits) { r.p = bp; _eofThrow(r); }
1225
+ const o = bp >> 3;
1226
+ ilen += ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16) | (d[o + 3] << 24)) >>> (bp & 7)) & ((1 << ie) - 1);
1227
+ bp += ie;
1228
+ }
1229
+ let clen = _COPY_BASE[ccode];
1230
+ const ce = _COPY_EXTRA[ccode];
1231
+ if (ce > 0) {
1232
+ if (bp + ce > eofBits) { r.p = bp; _eofThrow(r); }
1233
+ const o = bp >> 3;
1234
+ clen += ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16) | (d[o + 3] << 24)) >>> (bp & 7)) & ((1 << ce) - 1);
1235
+ bp += ce;
1236
+ }
1074
1237
 
1075
1238
  // --- Insert ILEN literals ---
1076
1239
  // §10: "if number of uncompressed bytes produced in the
@@ -1081,22 +1244,46 @@ export const brotli = {
1081
1244
  // read every literal, write only as many as fit in MLEN.
1082
1245
  if (ilen > 0) {
1083
1246
  _ensureCapacity(state, ilen);
1247
+ // The loop runs once per literal: its state in locals,
1248
+ // written back after it.
1249
+ const out = state.out, stop = startLen + mlen;
1250
+ const htreeL = h.htreeL, cmapL = h.cmapL;
1251
+ let outLen = state.outLen, p1 = state.p1, p2 = state.p2;
1252
+ let cmode = h.cmode[btypeL], cbase = 64 * btypeL;
1084
1253
  for (let k = 0; k < ilen; ++k) {
1085
1254
  if (blenL === 0) {
1255
+ r.p = bp;
1086
1256
  const nb = _decodeBlockType(h.htreeBtypeL, h.nbltypesL, btypeL, prevBtypeL, r);
1087
1257
  prevBtypeL = btypeL; btypeL = nb;
1088
1258
  blenL = _readBlockCount(r, h.htreeBlenL);
1259
+ bp = r.p;
1260
+ cmode = h.cmode[btypeL]; cbase = 64 * btypeL;
1089
1261
  }
1090
1262
  blenL--;
1091
1263
 
1092
- const cidL = _contextIdLit(h.cmode[btypeL], state.p1, state.p2);
1093
- const treeIdx = h.cmapL[64 * btypeL + cidL];
1094
- const lit = h.htreeL[treeIdx].read(r);
1095
- if (state.outLen - startLen < mlen) {
1096
- state.out[state.outLen++] = lit;
1097
- state.p2 = state.p1; state.p1 = lit;
1264
+ const cidL = cmode === 2 ? (_LUT0[p1] | _LUT1[p2]) : _contextIdLit(cmode, p1, p2);
1265
+ const tree = htreeL[cmapL[cbase + cidL]];
1266
+ let lit;
1267
+ const table = tree.table;
1268
+ if (table === null) {
1269
+ r.p = bp; lit = tree.read(r); bp = r.p;
1270
+ } else {
1271
+ // `read` of `_makeTableDecoder`, step for step.
1272
+ if (canMore && bp + tree.maxBits > eofBits) { r.p = bp; _eofThrow(r); }
1273
+ const o = bp >> 3;
1274
+ const entry = table[((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >>> (bp & 7)) & tree.mask];
1275
+ const len = entry & 0x0F;
1276
+ if (len === 0) _err('EBADSTREAM', 'undefined prefix code', bp);
1277
+ bp += len;
1278
+ if (bp > eofBits) { r.p = bp; _eofThrow(r); }
1279
+ lit = entry >>> 4;
1280
+ }
1281
+ if (outLen < stop) {
1282
+ out[outLen++] = lit;
1283
+ p2 = p1; p1 = lit;
1098
1284
  }
1099
1285
  }
1286
+ state.outLen = outLen; state.p1 = p1; state.p2 = p2;
1100
1287
  }
1101
1288
 
1102
1289
  // --- Last command's copy is ignored if we've reached MLEN ---
@@ -1105,19 +1292,54 @@ export const brotli = {
1105
1292
  // --- Resolve distance ---
1106
1293
  let distance, dsym = 0;
1107
1294
  if (distZero) {
1108
- distance = state.lastDist[0];
1295
+ distance = lastDist[0];
1109
1296
  } else {
1110
1297
  if (blenD === 0) {
1298
+ r.p = bp;
1111
1299
  const nb = _decodeBlockType(h.htreeBtypeD, h.nbltypesD, btypeD, prevBtypeD, r);
1112
1300
  prevBtypeD = btypeD; btypeD = nb;
1113
1301
  blenD = _readBlockCount(r, h.htreeBlenD);
1302
+ bp = r.p;
1114
1303
  }
1115
1304
  blenD--;
1116
1305
 
1117
1306
  const cidD = clen > 4 ? 3 : clen - 2;
1118
- const treeIdx = h.cmapD[4 * btypeD + cidD];
1119
- dsym = h.htreeD[treeIdx].read(r);
1120
- distance = _decodeDistanceSymbol(r, dsym, state.lastDist, h.npostfix, h.ndirect);
1307
+ const treeD = htreeD[cmapD[4 * btypeD + cidD]];
1308
+ const tableD = treeD.table;
1309
+ if (tableD === null) {
1310
+ r.p = bp; dsym = treeD.read(r); bp = r.p;
1311
+ } else {
1312
+ if (canMore && bp + treeD.maxBits > eofBits) { r.p = bp; _eofThrow(r); }
1313
+ const o = bp >> 3;
1314
+ const entry = tableD[((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >>> (bp & 7)) & treeD.mask];
1315
+ const len = entry & 0x0F;
1316
+ if (len === 0) _err('EBADSTREAM', 'undefined prefix code', bp);
1317
+ bp += len;
1318
+ if (bp > eofBits) { r.p = bp; _eofThrow(r); }
1319
+ dsym = entry >>> 4;
1320
+ }
1321
+ // `_decodeDistanceSymbol`'s two common paths inline: a
1322
+ // cache code, and a coded distance of at most 24 extra
1323
+ // bits; the rest through the function.
1324
+ const ndistbits = dsym >= 16 + ndirect ? 1 + ((dsym - ndirect - 16) >> (npostfix + 1)) : 0;
1325
+ if (dsym < 16) {
1326
+ distance = lastDist[_SPECIAL_DIST[dsym * 2]] + _SPECIAL_DIST[dsym * 2 + 1];
1327
+ if (distance <= 0) _err('EBADSTREAM', 'special distance code ' + dsym + ' resolved to non-positive ' + distance, bp);
1328
+ } else if (ndistbits === 0) {
1329
+ distance = dsym - 15;
1330
+ } else if (ndistbits <= 24) {
1331
+ if (bp + ndistbits > eofBits) { r.p = bp; _eofThrow(r); }
1332
+ const o = bp >> 3;
1333
+ const dextra = ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16) | (d[o + 3] << 24)) >>> (bp & 7)) & ((1 << ndistbits) - 1);
1334
+ bp += ndistbits;
1335
+ const dcOffset = dsym - ndirect - 16;
1336
+ const offset = ((2 + ((dcOffset >> npostfix) & 1)) << ndistbits) - 4;
1337
+ distance = ((offset + dextra) << npostfix) + (dcOffset & ((1 << npostfix) - 1)) + ndirect + 1;
1338
+ } else {
1339
+ r.p = bp;
1340
+ distance = _decodeDistanceSymbol(r, dsym, lastDist, npostfix, ndirect);
1341
+ bp = r.p;
1342
+ }
1121
1343
  }
1122
1344
 
1123
1345
  const maxAllowed = state.outLen < state.windowSize ? state.outLen : state.windowSize;
@@ -1143,61 +1365,26 @@ export const brotli = {
1143
1365
  // is interpreted permissively: clamp to remaining MLEN.
1144
1366
  const remaining = mlen - (state.outLen - startLen);
1145
1367
  if (isStaticDictRef) {
1146
- const wordId = distance - maxAllowed - 1 - lz77DictLen;
1147
- let transformed;
1148
-
1149
- if (state.resolveStaticDictRef) {
1150
- // Extension hook (RFC 9841 §3.1 custom-dict path,
1151
- // owned by `brotli_shared`). The callback handles
1152
- // length bounds, dict selection, transform
1153
- // application - brotli.js stays RFC 7932 here.
1154
- const cidL = _contextIdLit(h.cmode[btypeL], state.p1, state.p2);
1155
- transformed = state.resolveStaticDictRef(state, wordId, clen, cidL, r);
1156
- } else {
1157
- // RFC 7932 §8 - built-in static dictionary.
1158
- if (clen < 4 || clen > 24) {
1159
- _err('EBADSTREAM', 'static dict ref length ' + clen + ' not in [4, 24]', r.p);
1160
- }
1161
- _ensureDictLoaded(r);
1162
- const nw = brotliDict.NWORDS(clen);
1163
- const index = wordId % nw;
1164
- const transformId = (wordId - index) / nw;
1165
- if (transformId >= 121) _err('EBADSTREAM', 'static dict transform id ' + transformId + ' >= 121', r.p);
1166
- const baseWord = brotliDict.lookupWord(clen, index);
1167
- transformed = brotliDict.applyTransform(transformId, baseWord);
1168
- }
1169
-
1170
- const writeLen = transformed.length < remaining ? transformed.length : remaining;
1171
- _ensureCapacity(state, writeLen);
1172
- state.out.set(transformed.subarray(0, writeLen), state.outLen);
1173
- state.outLen += writeLen;
1368
+ r.p = bp;
1369
+ _copyStaticDictRef(r, h, state, distance - maxAllowed - 1 - lz77DictLen, clen, remaining, btypeL);
1174
1370
  } else if (isLz77DictRef) {
1175
- // RFC 9841 §3.2: dictionary_address = L + maxAllowed - distance
1176
- // First copy from lz77Dict[dictAddr..L), then if more
1177
- // is needed continue from output[windowStart..) (the
1178
- // oldest byte still in the regular LZ77 window).
1179
- const dictAddr = lz77DictLen + maxAllowed - distance;
1180
- const fromDictBytes = lz77DictLen - dictAddr;
1181
- const writeLen = clen < remaining ? clen : remaining;
1182
- _ensureCapacity(state, writeLen);
1183
- const outStart = state.outLen;
1184
- const windowStart = outStart > state.windowSize ? outStart - state.windowSize : 0;
1185
- let k = 0;
1186
- while (k < writeLen && k < fromDictBytes) {
1187
- state.out[state.outLen++] = state.lz77Dict[dictAddr + k];
1188
- ++k;
1189
- }
1190
- while (k < writeLen) {
1191
- state.out[state.outLen++] = state.out[windowStart + (k - fromDictBytes)];
1192
- ++k;
1193
- }
1371
+ _copyLz77DictRef(state, distance, maxAllowed, lz77DictLen, clen, remaining);
1194
1372
  } else {
1195
1373
  const writeLen = clen < remaining ? clen : remaining;
1196
- _ensureCapacity(state, writeLen);
1197
- for (let k = 0; k < writeLen; ++k) {
1198
- state.out[state.outLen] = state.out[state.outLen - distance];
1199
- state.outLen++;
1374
+ let outLen = state.outLen;
1375
+ // `_ensureCapacity`'s two tests, the call only on a miss.
1376
+ if (outLen + writeLen > state.out.length || outLen + writeLen > state.limit) _ensureCapacity(state, writeLen);
1377
+ const out = state.out;
1378
+ if (writeLen >= 32 && distance >= writeLen) {
1379
+ // A long copy whose source and destination do not overlap.
1380
+ out.copyWithin(outLen, outLen - distance, outLen - distance + writeLen);
1381
+ outLen += writeLen;
1382
+ } else {
1383
+ for (let k = 0; k < writeLen; ++k, ++outLen) out[outLen] = out[outLen - distance];
1200
1384
  }
1385
+ state.outLen = outLen;
1386
+ // A copy follows at least one byte (distance >= 1).
1387
+ if (outLen >= 2) { state.p1 = out[outLen - 1]; state.p2 = out[outLen - 2]; continue; }
1201
1388
  }
1202
1389
 
1203
1390
  // Update p1, p2 from last 2 emitted bytes
@@ -1209,13 +1396,27 @@ export const brotli = {
1209
1396
  state.p1 = state.out[state.outLen - 1];
1210
1397
  }
1211
1398
  }
1399
+ r.p = bp;
1212
1400
  }
1213
1401
 
1214
1402
  // --- Public decompressor ---
1215
1403
 
1404
+ /**
1405
+ * `opts.maxOutput` (bytes) as a decoder limit: `Infinity` when absent.
1406
+ * @param {object} [opts]
1407
+ * @returns {number}
1408
+ */
1409
+ function _limitOf(opts) {
1410
+ const m = opts ? opts.maxOutput : undefined;
1411
+ if (m === undefined || m === null) return Infinity;
1412
+ if (!(Number.isSafeInteger(m) && m >= 0)) _err('EBADARG', 'maxOutput must be a non-negative integer');
1413
+ return m;
1414
+ }
1415
+
1216
1416
  function brotliDecompressSync(data, opts) {
1217
1417
  if (!(data instanceof u8)) _err('EBADARG', 'expected Uint8Array');
1218
1418
  if (data.length === 0) _err('EBADSTREAM', 'empty input');
1419
+ const limit = _limitOf(opts);
1219
1420
 
1220
1421
  // `opts._ext` is the private extension protocol consumed by
1221
1422
  // `brotli_shared`. brotli.js itself accepts only RFC 7932 opts
@@ -1236,8 +1437,9 @@ export const brotli = {
1236
1437
  // `brotli_shared` for RFC 9841 §3.1 / §3.2 - when absent the
1237
1438
  // decoder behaves as a pure RFC 7932 implementation.
1238
1439
  const state = {
1239
- out: new u8(Math.max(data.length * 4, 1024)),
1440
+ out: new u8(Math.min(Math.max(data.length * 4, 1024), limit)),
1240
1441
  outLen: 0,
1442
+ limit,
1241
1443
  p1: 0,
1242
1444
  p2: 0,
1243
1445
  lastDist: new Int32Array([4, 11, 15, 16]),
@@ -1283,11 +1485,11 @@ export const brotli = {
1283
1485
  function _encodeUncompressed(data) {
1284
1486
  if (data.length === 0) return new u8([0x06]);
1285
1487
 
1286
- // Conservative size: WBITS + per-chunk headers (≤4 bytes each
1287
- // counting alignment) + data + final empty meta-block. The
1288
- // exact bit math is handled by the writer below.
1488
+ // Exact size: every chunk header takes 3 bytes once aligned (the
1489
+ // first one's 21 bits include WBITS, the others' 20), then the
1490
+ // payload; the final empty meta-block's 2 bits take 1 byte.
1289
1491
  const numChunks = Math.ceil(data.length / 65536);
1290
- const buf = new u8(data.length + 5 + numChunks * 4);
1492
+ const buf = new u8(data.length + 3 * numChunks + 1);
1291
1493
  let p = 0;
1292
1494
 
1293
1495
  // WBITS = 16 → 1 bit "0" (buf already zero-filled)
@@ -1315,7 +1517,7 @@ export const brotli = {
1315
1517
  p += 2;
1316
1518
  p = (p + 7) & ~7;
1317
1519
 
1318
- return buf.slice(0, p >> 3);
1520
+ return (p >> 3) === buf.length ? buf : buf.slice(0, p >> 3);
1319
1521
  }
1320
1522
 
1321
1523
  // --- Step 9 - LZ77 + dynamic Huffman encoder ---
@@ -1354,6 +1556,38 @@ export const brotli = {
1354
1556
  return null;
1355
1557
  }
1356
1558
 
1559
+ /**
1560
+ * The distance-cache code (0-15, RFC 7932 §4) the decoder would
1561
+ * resolve to `distance` from the ring `ld`, lowest first, or -1.
1562
+ * @param {number} distance
1563
+ * @param {number[]} ld Last four distances, newest first.
1564
+ * @param {number} allowed Bit mask of the codes that may be used.
1565
+ * @returns {number}
1566
+ */
1567
+ function _cacheCodeFor(distance, ld, allowed) {
1568
+ // The codes in increasing order, as `_SPECIAL_DIST` lists them:
1569
+ // 0-3 the four distances, 4-9 the last ±1..3, 10-15 the one
1570
+ // before ±1..3 (-1, +1, -2, +2, -3, +3).
1571
+ if (distance === ld[0] && (allowed & 1)) return 0;
1572
+ if (distance === ld[1] && (allowed & 2)) return 1;
1573
+ if (distance === ld[2] && (allowed & 4)) return 2;
1574
+ if (distance === ld[3] && (allowed & 8)) return 3;
1575
+ const d0 = distance - ld[0];
1576
+ if (d0 !== 0 && d0 >= -3 && d0 <= 3) {
1577
+ const code = 4 + _NEAR_CODE[d0 + 3];
1578
+ if ((allowed >> code) & 1) return code;
1579
+ }
1580
+ const d1 = distance - ld[1];
1581
+ if (d1 !== 0 && d1 >= -3 && d1 <= 3) {
1582
+ const code = 10 + _NEAR_CODE[d1 + 3];
1583
+ if ((allowed >> code) & 1) return code;
1584
+ }
1585
+ return -1;
1586
+ }
1587
+
1588
+ /** Offset −3..+3 (index + 3) → its position among a code group's six (−1, +1, −2, +2, −3, +3). */
1589
+ const _NEAR_CODE = new Int8Array([4, 2, 0, -1, 1, 3, 5]);
1590
+
1357
1591
  function _findIacSym(iCode, cCode, distZero) {
1358
1592
  const iHi = iCode >> 3, iLo = iCode & 7;
1359
1593
  const cHi = cCode >> 3, cLo = cCode & 7;
@@ -1385,27 +1619,15 @@ export const brotli = {
1385
1619
  const lcodeMask = (1 << npostfix) - 1;
1386
1620
  const lcode = dPrime & lcodeMask;
1387
1621
  const rest = dPrime >> npostfix;
1388
- for (let k = 1; k <= 24; ++k) {
1389
- // hbit=0 bucket: offset = ((2 + 0) << k) - 4 = (1<<(k+1)) - 4
1390
- const evenLo = (1 << (k + 1)) - 4;
1391
- const evenHi = evenLo + (1 << k) - 1;
1392
- if (rest >= evenLo && rest <= evenHi) {
1393
- const dextra = rest - evenLo;
1394
- const hcode = (k - 1) * 2;
1395
- const dcOffset = (hcode << npostfix) | lcode;
1396
- return { dsym: 16 + ndirect + dcOffset, extra: dextra, extraBits: k };
1397
- }
1398
- // hbit=1 bucket: offset = ((2 + 1) << k) - 4 = (3<<k) - 4
1399
- const oddLo = (3 << k) - 4;
1400
- const oddHi = oddLo + (1 << k) - 1;
1401
- if (rest >= oddLo && rest <= oddHi) {
1402
- const dextra = rest - oddLo;
1403
- const hcode = (k - 1) * 2 + 1;
1404
- const dcOffset = (hcode << npostfix) | lcode;
1405
- return { dsym: 16 + ndirect + dcOffset, extra: dextra, extraBits: k };
1406
- }
1407
- }
1408
- return null;
1622
+ // The buckets of k extra bits are contiguous: `rest + 4` lies in
1623
+ // [2^(k+1), 3·2^k) for hbit 0 and [3·2^k, 2^(k+2)) for hbit 1, so
1624
+ // k is read off the top bit instead of searched for (k = 1..24).
1625
+ const v = rest + 4;
1626
+ const k = 30 - Math.clz32(v);
1627
+ if (k > 24) return null;
1628
+ const hbit = (v >> k) & 1;
1629
+ const hcode = (k - 1) * 2 + hbit;
1630
+ return { dsym: 16 + ndirect + ((hcode << npostfix) | lcode), extra: v - ((2 + hbit) << k), extraBits: k };
1409
1631
  }
1410
1632
 
1411
1633
  function _makeWriter(initialCapacity) {
@@ -1424,6 +1646,16 @@ export const brotli = {
1424
1646
  return {
1425
1647
  bits(n, v) {
1426
1648
  ensure(n);
1649
+ // `writeBits16` ORs into a 3-byte window: a field wider
1650
+ // than 16 bits (distance extras up to 24, the 24-bit
1651
+ // extra of insert code 23, MLEN on 20 or 24) goes in two
1652
+ // writes, or its top bits are lost past bit 24.
1653
+ if (n > 16) {
1654
+ bitstream.writeBits16(buf, bp, v & 0xFFFF);
1655
+ bp += 16;
1656
+ n -= 16;
1657
+ v >>>= 16;
1658
+ }
1427
1659
  bitstream.writeBits16(buf, bp, v & ((1 << n) - 1));
1428
1660
  bp += n;
1429
1661
  },
@@ -1644,6 +1876,12 @@ export const brotli = {
1644
1876
  // OmitFirstK k values, matching `_OF_TID_BY_K` below.
1645
1877
  const _OF_K_VALUES = [1, 2, 3, 4, 5, 6, 7, 9];
1646
1878
 
1879
+ /** Bloom-filter bit (of 2^18) for a 32-bit dictionary key. */
1880
+ function _bloomBit(h) { return Math.imul(h, 0x9E3779B1) >>> 14; }
1881
+
1882
+ /** Whether the Bloom filter `bits` may hold the key `h`. */
1883
+ function _bloomHas(bits, h) { const b = _bloomBit(h); return (bits[b >>> 3] >> (b & 7)) & 1; }
1884
+
1647
1885
  function _getStaticDictHash() {
1648
1886
  if (_staticDictHash !== null) return _staticDictHash;
1649
1887
  if (_staticDictHashTried) return null;
@@ -1678,7 +1916,19 @@ export const brotli = {
1678
1916
  }
1679
1917
  }
1680
1918
  }
1681
- _staticDictHash = { table, words, ofTables };
1919
+ // A 2^18-bit Bloom filter per table in front of `Map.get`: most
1920
+ // positions of most inputs start no dictionary word, and the
1921
+ // filter answers "absent" without the lookup (it never answers
1922
+ // "absent" for a present key, so the matches found are the same).
1923
+ const bloomOf = (m) => {
1924
+ const bits = new u8(1 << 15);
1925
+ for (const key of m.keys()) { const b = _bloomBit(key); bits[b >>> 3] |= 1 << (b & 7); }
1926
+ return bits;
1927
+ };
1928
+ const bloom = bloomOf(table);
1929
+ const ofBlooms = new Array(10);
1930
+ for (const k of _OF_K_VALUES) ofBlooms[k] = bloomOf(ofTables[k]);
1931
+ _staticDictHash = { table, words, ofTables, bloom, ofBlooms };
1682
1932
  return _staticDictHash;
1683
1933
  }
1684
1934
 
@@ -1749,9 +1999,18 @@ export const brotli = {
1749
1999
  groups.sort((a, b) => a.prefix.length - b.prefix.length);
1750
2000
  return groups;
1751
2001
  };
1752
- _idTransformGroups = finalize(idByPrefix);
1753
- _ffTransformGroups = finalize(ffByPrefix);
1754
- _faTransformGroups = finalize(faByPrefix);
2002
+ // Indexed by the input's first byte: the groups whose prefix is
2003
+ // empty or starts with that byte, in their sorted order — the
2004
+ // only groups the scan can match there, met in the same order,
2005
+ // so ties between equal-length matches resolve as before.
2006
+ const byFirst = (groups) => {
2007
+ const idx = new Array(256);
2008
+ for (let b = 0; b < 256; ++b) idx[b] = groups.filter((g) => g.prefix.length === 0 || g.prefix[0] === b);
2009
+ return idx;
2010
+ };
2011
+ _idTransformGroups = byFirst(finalize(idByPrefix));
2012
+ _ffTransformGroups = byFirst(finalize(ffByPrefix));
2013
+ _faTransformGroups = byFirst(finalize(faByPrefix));
1755
2014
  for (const arr of olByK.values()) {
1756
2015
  arr.sort((a, b) => b.suffix.length - a.suffix.length);
1757
2016
  }
@@ -1784,7 +2043,7 @@ export const brotli = {
1784
2043
  // the hot path branchless.)
1785
2044
 
1786
2045
  // --- Identity scan (+ OmitLastK on partial body match) ---
1787
- const idGroups = _idTransformGroups;
2046
+ const idGroups = _idTransformGroups[data[pos]];
1788
2047
  for (let gi = 0; gi < idGroups.length; ++gi) {
1789
2048
  const g = idGroups[gi];
1790
2049
  const pre = g.prefix;
@@ -1796,6 +2055,7 @@ export const brotli = {
1796
2055
 
1797
2056
  const hashStart = pos + preLen;
1798
2057
  const h = (data[hashStart] | (data[hashStart + 1] << 8) | (data[hashStart + 2] << 16) | (data[hashStart + 3] << 24)) >>> 0;
2058
+ if (!_bloomHas(dictHash.bloom, h)) continue;
1799
2059
  const bucket = dictHash.table.get(h);
1800
2060
  if (!bucket) continue;
1801
2061
 
@@ -1867,7 +2127,7 @@ export const brotli = {
1867
2127
  // We un-ferment the affected byte to recover the dict-side key,
1868
2128
  // then verify the first codepoint bytes exactly before walking
1869
2129
  // the rest of the body verbatim.
1870
- const ffGroups = _ffTransformGroups;
2130
+ const ffGroups = _ffTransformGroups[data[pos]];
1871
2131
  for (let gi = 0; gi < ffGroups.length; ++gi) {
1872
2132
  const g = ffGroups[gi];
1873
2133
  const pre = g.prefix;
@@ -1904,6 +2164,7 @@ export const brotli = {
1904
2164
  }
1905
2165
 
1906
2166
  const h = (u0 | (u1 << 8) | (u2 << 16) | (u3 << 24)) >>> 0;
2167
+ if (!_bloomHas(dictHash.bloom, h)) continue;
1907
2168
  const bucket = dictHash.table.get(h);
1908
2169
  if (!bucket) continue;
1909
2170
 
@@ -1954,7 +2215,7 @@ export const brotli = {
1954
2215
  // walk input bytes 0..3 and compute un-fermented values
1955
2216
  // (= dict bytes) for the hash key, then verify the body by
1956
2217
  // walking dict codepoints and applying the same rule.
1957
- const faGroups = _faTransformGroups;
2218
+ const faGroups = _faTransformGroups[data[pos]];
1958
2219
  for (let gi = 0; gi < faGroups.length; ++gi) {
1959
2220
  const g = faGroups[gi];
1960
2221
  const pre = g.prefix;
@@ -2074,6 +2335,7 @@ export const brotli = {
2074
2335
  if (!validCp || !hasFermented) continue;
2075
2336
 
2076
2337
  const h = (u0 | (u1 << 8) | (u2 << 16) | (u3 << 24)) >>> 0;
2338
+ if (!_bloomHas(dictHash.bloom, h)) continue;
2077
2339
  const bucket = dictHash.table.get(h);
2078
2340
  if (!bucket) continue;
2079
2341
 
@@ -2147,6 +2409,7 @@ export const brotli = {
2147
2409
  const k = _OF_K_VALUES[ki];
2148
2410
  const ofTable = dictHash.ofTables[k];
2149
2411
  if (!ofTable) continue;
2412
+ if (!_bloomHas(dictHash.ofBlooms[k], h)) continue;
2150
2413
  const bucket = ofTable.get(h);
2151
2414
  if (!bucket) continue;
2152
2415
  const ofTid = _OF_TID_BY_K.get(k);
@@ -2176,9 +2439,10 @@ export const brotli = {
2176
2439
  // Walk the LZ77-produced commands and split literal runs whenever
2177
2440
  // a long-enough static-dict match is found. Replaces "N literals
2178
2441
  // then a copy" with "K literals + dict-ref-copy", followed by the
2179
- // remainder. Threshold of 6 bytes is empirical - shorter matches
2180
- // typically don't beat Huffman-coded literals once IAC + distance
2181
- // overhead is paid.
2442
+ // remainder. The minimum word length is empirical: 4 bytes for the
2443
+ // built-in dictionary (text 2.7 % smaller at q6 than with 6,
2444
+ // json and source no larger), 6 for a custom one (RFC 9841), whose
2445
+ // words carry no measurement here.
2182
2446
  // Augment LZ77 commands with static-dict references. The match
2183
2447
  // finder is either:
2184
2448
  // - the built-in RFC 7932 Appendix A/B scan (`_findStaticDictMatchAt`,
@@ -2193,7 +2457,7 @@ export const brotli = {
2193
2457
  function _augmentWithStaticDictRefs(commands, data, dictHash, windowSize, customMatchFinder, lz77PrefixLen) {
2194
2458
  const augmented = [];
2195
2459
  let outPos = 0;
2196
- const MIN_DICT_MATCH = 6;
2460
+ const MIN_DICT_MATCH = customMatchFinder ? 6 : 4;
2197
2461
  const L = lz77PrefixLen | 0;
2198
2462
 
2199
2463
  for (let ci = 0; ci < commands.length; ++ci) {
@@ -2325,13 +2589,10 @@ export const brotli = {
2325
2589
  return kl > 0.3 ? { splitBytePos: half } : null;
2326
2590
  }
2327
2591
 
2328
- function _pickDistParams(cmds) {
2329
- // Collect distances from commands (skip insert-only & special).
2330
- const distances = [];
2331
- for (let i = 0; i < cmds.length; ++i) {
2332
- const c = cmds[i];
2333
- if (c.copyLen > 0 && c.distance > 0) distances.push(c.distance);
2334
- }
2592
+ // `_pickDistParams` takes the distances collected by
2593
+ // `_assignDistanceCache`: a filter inside its own loop made
2594
+ // JavaScriptCore compile the whole function three times slower.
2595
+ function _pickDistParams(distances) {
2335
2596
  if (distances.length === 0) {
2336
2597
  return { npostfix: 0, ndirect: 0, distAlphabet: 64 };
2337
2598
  }
@@ -2347,11 +2608,25 @@ export const brotli = {
2347
2608
  const cnt = new Int32Array(alpha);
2348
2609
  let extraBitsSum = 0;
2349
2610
  let valid = true;
2350
- for (const d of distances) {
2351
- const enc = _distanceCodeFor(d, np, nd);
2352
- if (!enc || enc.dsym >= alpha) { valid = false; break; }
2353
- ++cnt[enc.dsym];
2354
- extraBitsSum += enc.extraBits;
2611
+ // `_distanceCodeFor`'s symbol and extra-bit count, inline and
2612
+ // allocation-free (this loop runs 7 times per distance).
2613
+ const lmask = (1 << np) - 1;
2614
+ for (let di = 0; di < distances.length; ++di) {
2615
+ const d = distances[di];
2616
+ let dsym, ebits;
2617
+ if (d <= nd) {
2618
+ dsym = 16 + d - 1;
2619
+ ebits = 0;
2620
+ } else {
2621
+ const dPrime = d - nd - 1;
2622
+ const v = (dPrime >> np) + 4;
2623
+ ebits = 30 - Math.clz32(v);
2624
+ if (ebits > 24) { valid = false; break; }
2625
+ dsym = 16 + nd + (((((ebits - 1) * 2) + ((v >> ebits) & 1)) << np) | (dPrime & lmask));
2626
+ }
2627
+ if (dsym >= alpha) { valid = false; break; }
2628
+ ++cnt[dsym];
2629
+ extraBitsSum += ebits;
2355
2630
  }
2356
2631
  if (!valid) continue;
2357
2632
  // Entropy in bits + extras + alphabet overhead.
@@ -2374,6 +2649,195 @@ export const brotli = {
2374
2649
  return { npostfix: bestNpost, ndirect: bestNdir, distAlphabet: bestAlpha };
2375
2650
  }
2376
2651
 
2652
+ /**
2653
+ * Whether LZ77 found (almost) nothing to copy and the bytes look
2654
+ * uniformly distributed: matches covering under 1 % of the input,
2655
+ * at most one command per 256 bytes, and an order-0 entropy of at
2656
+ * least 7.9 bits a byte over every 16th byte. Such input costs more
2657
+ * compressed than stored (the Huffman codes cannot go below ~8 bits a
2658
+ * literal, and the headers come on top), so the encoder stores it.
2659
+ * With 16 samples a KiB the estimate of a short input stays below the
2660
+ * threshold (log2 of the sample count), which keeps the test
2661
+ * conservative there.
2662
+ *
2663
+ * @param {Uint8Array} data
2664
+ * @param {Array<{insertLen: number}>} commands The LZ77 commands of `data`.
2665
+ * @returns {boolean}
2666
+ */
2667
+ function _looksIncompressible(data, commands) {
2668
+ const len = data.length;
2669
+ if (commands.length > (len >> 8) + 2) return false;
2670
+ let literals = 0;
2671
+ for (let i = 0; i < commands.length; ++i) literals += commands[i].insertLen;
2672
+ if (literals < len * 0.99) return false;
2673
+ return _sampledEntropyHigh(data);
2674
+ }
2675
+
2676
+ /**
2677
+ * Order-0 entropy of every 16th byte of `data` at least 7.9 bits a
2678
+ * byte (below the threshold for any input under ~4 KiB: the estimate
2679
+ * cannot exceed log2 of the sample count).
2680
+ * @param {Uint8Array} data
2681
+ * @returns {boolean}
2682
+ */
2683
+ function _sampledEntropyHigh(data) {
2684
+ const len = data.length;
2685
+ const hist = new Int32Array(256);
2686
+ let n = 0;
2687
+ for (let i = 0; i < len; i += 16) { ++hist[data[i]]; ++n; }
2688
+ let bits = 0;
2689
+ for (let b = 0; b < 256; ++b) {
2690
+ const c = hist[b];
2691
+ if (c) bits -= c * Math.log2(c / n);
2692
+ }
2693
+ return bits >= 7.9 * n;
2694
+ }
2695
+
2696
+ /**
2697
+ * Bytes covered by repeats found through content-defined anchors — a
2698
+ * lower bound of what LZ77 would copy, in one cheap pass. A position
2699
+ * is an anchor when its 4-byte key hashes to 0 in 4 chosen bits
2700
+ * (about 1 in 16); only anchors touch the one-slot table (key and
2701
+ * position side by side), so the pass is mostly arithmetic. Both
2702
+ * copies of a repeated block carry the same anchors, so the second
2703
+ * finds the first; the match is then extended byte by byte and
2704
+ * skipped. With 2^16 slots each holding one anchor in 16 positions, a
2705
+ * repeat about 1 MiB back still survives in ~1 slot in 8 — any
2706
+ * repeat of a few hundred bytes is seen.
2707
+ * @param {Uint8Array} data
2708
+ * @returns {number}
2709
+ */
2710
+ function _probeRepeats(data) {
2711
+ const len = data.length;
2712
+ const slots = new Int32Array(2 << 16).fill(-1);
2713
+ let covered = 0;
2714
+ let i = 0;
2715
+ let key = len >= 4 ? data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24) : 0;
2716
+ while (i + 4 <= len) {
2717
+ const hv = Math.imul(key, 0x9E3779B1);
2718
+ if (((hv >>> 8) & 15) === 0) {
2719
+ const h = (hv >>> 16) << 1;
2720
+ const c = slots[h + 1];
2721
+ const hit = c >= 0 && slots[h] === key;
2722
+ slots[h] = key;
2723
+ slots[h + 1] = i;
2724
+ if (hit) {
2725
+ let m = 4;
2726
+ while (i + m < len && data[c + m] === data[i + m]) ++m;
2727
+ covered += m;
2728
+ i += m;
2729
+ if (i + 4 <= len) key = data[i] | (data[i + 1] << 8) | (data[i + 2] << 16) | (data[i + 3] << 24);
2730
+ continue;
2731
+ }
2732
+ }
2733
+ ++i;
2734
+ if (i + 4 <= len) key = (key >>> 8) | (data[i + 3] << 24);
2735
+ }
2736
+ return covered;
2737
+ }
2738
+
2739
+ /**
2740
+ * The distance-cache code (RFC 7932 §4) of every command, or -1: the
2741
+ * last four distances, as the decoder keeps them. A copy whose
2742
+ * distance is one of them, or the last or the one before ±1..3,
2743
+ * takes its code 0-15 (no extra bits); code 0 rides on an
2744
+ * implicit-distance insert-and-copy symbol when the lengths allow.
2745
+ * The ring moves exactly as the decoder's: not on code 0, not on a
2746
+ * static-dict ref. A code is worth its place in the distance
2747
+ * alphabet only if it saves more than the symbol costs in the header:
2748
+ * a first pass tallies, per code, the extra bits its uses would save
2749
+ * over full coding; codes below CACHE_MIN_SAVING are dropped and the
2750
+ * ring replayed. (Kept out of `_encodeCompressed`: grown past a size,
2751
+ * that function is optimised less by JavaScriptCore — 25 % slower.)
2752
+ * Also returns the distances still coded in full (copies only, the
2753
+ * dictionary refs included), for `_pickDistParams`.
2754
+ *
2755
+ * With `data`, a copy no cached distance names still takes a cached
2756
+ * distance whose bytes are the same (lowest code first, within the
2757
+ * window and the output so far): the parse and the output do not
2758
+ * change, the distance costs a cache code instead of a full one
2759
+ * (json 0.6 % smaller at q6). `data` is the output itself, so
2760
+ * it is passed only when no LZ77 prefix precedes it.
2761
+ * @param {Array<{insertLen: number, copyLen: number, distance: number}>} cmds
2762
+ * @param {Uint8Array|null} [data]
2763
+ * @param {number} [maxDistance] The window: a larger distance is a dictionary ref.
2764
+ * @returns {{ cacheCodes: Int8Array, distances: number[] }}
2765
+ */
2766
+ function _assignDistanceCache(cmds, data, maxDistance) {
2767
+ const CACHE_MIN_SAVING = 128;
2768
+ const n = cmds.length;
2769
+ const cacheCodes = new Int8Array(n).fill(-1);
2770
+ // Each pass starts from the parse's distances: a substitution
2771
+ // made under one code mask may not hold under the next. (Int32:
2772
+ // a double stored back into `distance` changes the commands'
2773
+ // field representation, and JavaScriptCore deoptimises every
2774
+ // reader of it - 50 % slower on source.)
2775
+ const parsed = new Int32Array(n);
2776
+ for (let ci = 0; ci < n; ++ci) parsed[ci] = cmds[ci].distance;
2777
+ let distances = [];
2778
+ const assign = (allowed) => {
2779
+ const ld = [4, 11, 15, 16];
2780
+ const saved = new Int32Array(16);
2781
+ distances = [];
2782
+ let pos = 0;
2783
+ for (let ci = 0; ci < n; ++ci) {
2784
+ const c = cmds[ci];
2785
+ cacheCodes[ci] = -1;
2786
+ pos += c.insertLen;
2787
+ if (c.copyLen === 0) continue;
2788
+ // @ts-ignore - isDictRef and dictOutputLen are present on dictionary refs only
2789
+ if (c.isDictRef) { pos += c.dictOutputLen != null ? c.dictOutputLen : c.copyLen; if (c.distance > 0) distances.push(c.distance); continue; }
2790
+ c.distance = parsed[ci];
2791
+ let code = _cacheCodeFor(c.distance, ld, allowed);
2792
+ if (code < 0 && data) code = _sameBytesCacheCode(c, data, pos, ld, allowed, maxDistance);
2793
+ pos += c.copyLen;
2794
+ if (code < 0 && c.distance > 0) distances.push(c.distance);
2795
+ cacheCodes[ci] = code;
2796
+ // Extra bits of the full code (NPOSTFIX 0, NDIRECT 0):
2797
+ // `_distanceCodeFor`'s k, for d - 1 + 4.
2798
+ if (code >= 0) saved[code] += 30 - Math.clz32(c.distance + 3);
2799
+ if (code !== 0) { ld[3] = ld[2]; ld[2] = ld[1]; ld[1] = ld[0]; ld[0] = c.distance; }
2800
+ }
2801
+ return saved;
2802
+ };
2803
+ const saved = assign(0xFFFF);
2804
+ let allowed = 0;
2805
+ for (let code = 0; code < 16; ++code) if (saved[code] >= CACHE_MIN_SAVING) allowed |= 1 << code;
2806
+ if (allowed !== 0xFFFF) assign(allowed);
2807
+ return { cacheCodes, distances };
2808
+ }
2809
+
2810
+ /**
2811
+ * The lowest allowed cache code whose distance copies the same bytes
2812
+ * as `c` at output position `pos`, or -1; on a hit `c.distance`
2813
+ * becomes that distance.
2814
+ * @param {{copyLen: number, distance: number}} c
2815
+ * @param {Uint8Array} data
2816
+ * @param {number} pos
2817
+ * @param {number[]} ld
2818
+ * @param {number} allowed
2819
+ * @param {number} maxDistance
2820
+ * @returns {number}
2821
+ */
2822
+ function _sameBytesCacheCode(c, data, pos, ld, allowed, maxDistance) {
2823
+ const len = c.copyLen;
2824
+ for (let k = 0; k < 16; ++k) {
2825
+ if (!((allowed >> k) & 1)) continue;
2826
+ const cd = ld[_SPECIAL_DIST[k * 2]] + _SPECIAL_DIST[k * 2 + 1];
2827
+ if (cd <= 0 || cd > pos || cd > maxDistance || cd === c.distance) continue;
2828
+ let m = 0;
2829
+ while (m < len && data[pos + m] === data[pos - cd + m]) ++m;
2830
+ if (m === len) { c.distance = cd; return k; }
2831
+ }
2832
+ return -1;
2833
+ }
2834
+
2835
+ /**
2836
+ * @param {Uint8Array} data
2837
+ * @param {object} [opts]
2838
+ * @returns {Uint8Array|null} The compressed stream, or `null` when
2839
+ * the input looks incompressible (the caller stores it).
2840
+ */
2377
2841
  function _encodeCompressed(data, opts) {
2378
2842
  const len = data.length;
2379
2843
  const ntreesL = _NTREESL_OPT;
@@ -2396,11 +2860,6 @@ export const brotli = {
2396
2860
  ? Math.pow(2, wbits) - 16
2397
2861
  : (1 << wbits) - 16;
2398
2862
 
2399
- // Pick best CMODE for this input (RFC 7932 §7.1). The same
2400
- // CMODE drives both the frequency-collection pass and the
2401
- // bit-writing pass; we emit it in the meta-block header.
2402
- const cmode = _pickCMode(data);
2403
-
2404
2863
  // Extension hook: `opts._ext.lz77Prefix` (Uint8Array) is a
2405
2864
  // virtual prefix to the input, used so that LZ77 can find
2406
2865
  // matches into a shared dictionary. The decoder side (when
@@ -2428,6 +2887,16 @@ export const brotli = {
2428
2887
  inputBuf.set(data, prefixLen);
2429
2888
  }
2430
2889
 
2890
+ // --- 0. Incompressible input, decided before LZ77 when the
2891
+ // bytes look uniform and a quick repeat probe finds
2892
+ // nothing: the caller stores it (RFC 7932 §9.2).
2893
+ if (prefixLen === 0 && _sampledEntropyHigh(data) && _probeRepeats(data) < len / 100) return null;
2894
+
2895
+ // Pick best CMODE for this input (RFC 7932 §7.1). The same
2896
+ // CMODE drives both the frequency-collection pass and the
2897
+ // bit-writing pass; we emit it in the meta-block header.
2898
+ const cmode = _pickCMode(data);
2899
+
2431
2900
  // --- 1. LZ77 commands --------------------------------------
2432
2901
  const commands = [];
2433
2902
  let insertStart = 0;
@@ -2442,28 +2911,36 @@ export const brotli = {
2442
2911
  quality <= 1 ? { chainDepth: 2, lazy: false } :
2443
2912
  quality <= 3 ? { chainDepth: 4, lazy: false } :
2444
2913
  quality <= 5 ? { chainDepth: 6, lazy: true } :
2445
- quality <= 7 ? { chainDepth: 10, lazy: true } :
2446
- quality <= 9 ? { chainDepth: 16, lazy: true } :
2447
- { chainDepth: 32, lazy: true };
2448
- lz77.encode(inputBuf, { windowBits: 21, minMatch: 4, ...qParams }, {
2449
- literal(pos) {
2450
- if (pos < prefixLen) return; // dict prefix, not output
2451
- const dpos = pos - prefixLen;
2452
- if (insertLen === 0) insertStart = dpos;
2453
- insertLen++;
2454
- },
2455
- match(pos, mlen, dist) {
2456
- if (pos < prefixLen) return; // match fully inside dict, not output
2457
- while (insertLen > 22593) {
2458
- commands.push({ insertStart, insertLen: 22593, copyLen: 2, distance: 1 });
2459
- insertStart += 22593;
2460
- insertLen -= 22593;
2914
+ // q6, the default, keeps its speed; q7 trades encode time for
2915
+ // ratio (json 2 % smaller, 20-50 % slower at 256 KiB).
2916
+ quality <= 6 ? { chainDepth: 10, lazy: true } :
2917
+ quality <= 7 ? { chainDepth: 64, lazy: true, niceLength: 32, goodLength: 8, maxLazy: 16 } :
2918
+ quality <= 9 ? { chainDepth: 64, lazy: true, niceLength: 64, goodLength: 16, maxLazy: 32 } :
2919
+ { chainDepth: 128, lazy: true, niceLength: 128, goodLength: 32, maxLazy: 64 };
2920
+ // The token stream `lz77.encode` would replay through callbacks,
2921
+ // read straight from the packed pairs (same commands, no call
2922
+ // per token).
2923
+ const scan = lz77.encodeTokens(inputBuf, { windowBits: 21, minMatch: 4, ...qParams });
2924
+ const tokens = scan.tokens;
2925
+ for (let k = 0, p = 0, pos = 0; k < scan.count; ++k, p += 2) {
2926
+ const mlen = tokens[p];
2927
+ if (mlen === 0) {
2928
+ if (pos >= prefixLen) { // a dict-prefix literal is not output
2929
+ if (insertLen === 0) insertStart = pos - prefixLen;
2930
+ insertLen++;
2461
2931
  }
2462
- commands.push({ insertStart, insertLen, copyLen: mlen, distance: dist });
2932
+ pos += 1;
2933
+ continue;
2934
+ }
2935
+ if (pos >= prefixLen) { // a match fully inside the dict prefix is not output
2936
+ // Any insert length fits one command: insert code 23
2937
+ // reaches 22594 + 2^24 - 1 (RFC 7932 §5).
2938
+ commands.push({ insertStart, insertLen, copyLen: mlen, distance: tokens[p + 1] });
2463
2939
  insertStart = 0;
2464
2940
  insertLen = 0;
2465
- },
2466
- });
2941
+ }
2942
+ pos += mlen;
2943
+ }
2467
2944
  if (insertLen > 0) {
2468
2945
  commands.push({ insertStart, insertLen, copyLen: 0, distance: 0 });
2469
2946
  }
@@ -2471,6 +2948,12 @@ export const brotli = {
2471
2948
  commands.push({ insertStart: 0, insertLen: 0, copyLen: 0, distance: 0 });
2472
2949
  }
2473
2950
 
2951
+ // --- 1a. Incompressible input: the caller emits uncompressed
2952
+ // meta-blocks (RFC 7932 §9.2), before the dictionary
2953
+ // scan and the entropy coding would spend their time on
2954
+ // bytes they cannot shrink.
2955
+ if (_looksIncompressible(data, commands)) return null;
2956
+
2474
2957
  // --- 1b. Augment with static-dict references.
2475
2958
  // Priority: custom-dict hook (RFC 9841 §3.1) over built-in
2476
2959
  // RFC 7932 dict. When neither is usable, leave commands as-is.
@@ -2480,9 +2963,12 @@ export const brotli = {
2480
2963
  ? _augmentWithStaticDictRefs(commands, data, dictHash, windowSize, customMatchFinder, prefixLen)
2481
2964
  : commands;
2482
2965
 
2966
+ // --- 1b'. Distance cache (RFC 7932 §4): see `_assignDistanceCache`.
2967
+ const { cacheCodes, distances: fullDistances } = _assignDistanceCache(cmds, prefixLen === 0 ? data : null, windowSize);
2968
+
2483
2969
  // --- 1c. Pick distance encoding params (NPOSTFIX, NDIRECT)
2484
- // based on the actual distance distribution.
2485
- const distParams = _pickDistParams(cmds);
2970
+ // based on the distances still coded in full.
2971
+ const distParams = _pickDistParams(fullDistances);
2486
2972
  const npostfix = distParams.npostfix;
2487
2973
  const ndirect = distParams.ndirect;
2488
2974
  const distAlphabet = distParams.distAlphabet;
@@ -2542,17 +3028,23 @@ export const brotli = {
2542
3028
  const cc = _copyCodeFor(effCopyLen);
2543
3029
  if (!ic || !cc) _err('EINTERNAL', 'cannot encode I=' + c.insertLen + ' C=' + effCopyLen);
2544
3030
 
2545
- const iacSym = _findIacSym(ic.code, cc.code, false);
3031
+ const cacheCode = cacheCodes[ci];
3032
+ // Code 0 needs no distance symbol at all when an implicit-
3033
+ // distance cell holds the lengths (insert code < 8, copy < 16).
3034
+ const implicit = cacheCode === 0 && _findIacSym(ic.code, cc.code, true) >= 0;
3035
+ const iacSym = _findIacSym(ic.code, cc.code, implicit);
2546
3036
  if (iacSym < 0) _err('EINTERNAL', 'no IAC sym for I=' + ic.code + ' C=' + cc.code);
2547
3037
  ++iacFreq[iacSym];
2548
3038
 
2549
3039
  let distEnc = null;
2550
3040
  if (!isLastNoCopy) {
2551
- distEnc = _distanceCodeFor(c.distance, npostfix, ndirect);
2552
- if (!distEnc || distEnc.dsym >= distAlphabet) {
3041
+ distEnc = implicit ? null
3042
+ : cacheCode >= 0 ? { dsym: cacheCode, extra: 0, extraBits: 0 }
3043
+ : _distanceCodeFor(c.distance, npostfix, ndirect);
3044
+ if (!implicit && (!distEnc || distEnc.dsym >= distAlphabet)) {
2553
3045
  _err('EINTERNAL', 'distance ' + c.distance + ' outside alphabet');
2554
3046
  }
2555
- ++distFreq[distEnc.dsym];
3047
+ if (distEnc) ++distFreq[distEnc.dsym];
2556
3048
 
2557
3049
  // Advance p1, p2 across the copy.
2558
3050
  // - Static dict ref: copied bytes = data[inputPos + k]
@@ -2759,6 +3251,10 @@ export const brotli = {
2759
3251
  if (aux.distEnc) {
2760
3252
  w.bits(distLens[aux.distEnc.dsym], distMap[aux.distEnc.dsym]);
2761
3253
  if (aux.distEnc.extraBits > 0) w.bits(aux.distEnc.extraBits, aux.distEnc.extra);
3254
+ }
3255
+ // The copy moves the context bytes whether or not a distance
3256
+ // symbol was written (an implicit-distance command has none).
3257
+ if (c.copyLen > 0) {
2762
3258
  // @ts-ignore - isDictRef/dictOutputLen are present when isDictRef===true; TS cannot narrow union from this field
2763
3259
  if (c.isDictRef) {
2764
3260
  const inputPos = c.insertStart + c.insertLen;
@@ -2802,6 +3298,7 @@ export const brotli = {
2802
3298
  try {
2803
3299
  const compressed = _encodeCompressed(data, opts);
2804
3300
  const trivial = _encodeUncompressed(data);
3301
+ if (compressed === null) return trivial;
2805
3302
  return compressed.length <= trivial.length ? compressed : trivial;
2806
3303
  } catch (e) {
2807
3304
  if (e.code === 'EINTERNAL') return _encodeUncompressed(data);
@@ -2955,9 +3452,11 @@ export const brotli = {
2955
3452
  const wbits = wbitsInfo.wbits;
2956
3453
  const windowSize = wbits >= 31 ? Math.pow(2, wbits) - 16 : (1 << wbits) - 16;
2957
3454
 
3455
+ const limit = _limitOf(this._opts);
2958
3456
  this._state = {
2959
- out: new u8(1024),
3457
+ out: new u8(Math.min(1024, limit)),
2960
3458
  outLen: 0,
3459
+ limit,
2961
3460
  p1: 0,
2962
3461
  p2: 0,
2963
3462
  lastDist: new Int32Array([4, 11, 15, 16]),
@@ -3032,18 +3531,19 @@ export const brotli = {
3032
3531
  }
3033
3532
  };
3034
3533
 
3035
- return {
3534
+ return Object.defineProperty({
3036
3535
  brotliCompressSync,
3037
3536
  brotliDecompressSync,
3038
3537
  brotliCompress,
3039
3538
  brotliDecompress,
3040
3539
  BrotliCompressStream,
3041
3540
  BrotliDecompressStream,
3541
+ }, Symbol.for('@awacloud/fw/internal'), {
3042
3542
  // Internal primitives shared with the codec's own tests and
3043
3543
  // potentially with future companion modules (e.g. a brotli
3044
- // inspector / debugger). Same `_internal` convention as
3544
+ // inspector / debugger). The internal slot (core/internal.js), as
3045
3545
  // chacha20, sha256, argon2, etc.
3046
- _internal: {
3546
+ value: {
3047
3547
  makeReader: _makeReader,
3048
3548
  readBit: _readBit,
3049
3549
  readBits: _readBits,
@@ -3067,7 +3567,7 @@ export const brotli = {
3067
3567
  COPY_BASE: _COPY_BASE,
3068
3568
  COPY_EXTRA: _COPY_EXTRA,
3069
3569
  encodeUncompressed: _encodeUncompressed,
3070
- },
3071
- };
3570
+ }
3571
+ });
3072
3572
  }
3073
3573
  };