Vize

use-compression-stream

Compress data with the Compression Streams API.

Package @vizejs/composable/use-compression-stream
Own the source vize lib pull composable:use-compression-stream
Runtime exports compress, decompress, decompressText, useCompressionStream
Gzip budget 2304 B

Minimal setup

Use a Vue 3.5+ project with Vue SFC compilation configured (see Vite+ integration).

vp install @vizejs/composable

Import the entry directly. Call lifecycle-bound utilities inside <script setup> so cleanup follows the component scope; consult the runtime contract for this entry's SSR and hydration behavior.

import { compress, decompress, decompressText, useCompressionStream } from "@vizejs/composable/use-compression-stream";

Try it

Compress text before uploading it

Compress and decompress data with the browser's built-in gzip and deflate streams.

Open the interactive example

What to observe: Compress and restore shows the original and gzip sizes and confirms the text is restored exactly.

compress accepts strings, Blobs and byte arrays. supported is false in browsers without CompressionStream.

Compare the initial and interacted states
Compress text before uploading it: initial state
Initial state
Compress text before uploading it: state after the verified interactions
After the verified interactions

Copy the example

Save this complete SFC in your Vue project. Its public imports and source are the same ones executed in the preview.

<script setup lang="ts">
import { ref } from "vue";
import { useCompressionStream } from "@vizejs/composable/use-compression-stream";

const { compress, decompressText, pending } = useCompressionStream({ format: "gzip" });
const text = ref("Vue ".repeat(200));
const summary = ref("Not compressed yet.");

async function roundTrip() {
  const bytes = await compress(text.value);
  const restored = await decompressText(bytes);
  summary.value = `${new TextEncoder().encode(text.value).length} bytes → ${bytes.length} bytes gzip · restored ${restored === text.value ? "exactly" : "with differences"}`;
}
</script>

<template>
  <div class="composable-example">
    <p>Compress text in the browser before uploading it, and check it restores exactly.</p>
    <label>
      Text to compress
      <textarea v-model="text" rows="2"></textarea>
    </label>
    <button type="button" :disabled="pending" @click="roundTrip">Compress and restore</button>
    <output aria-live="polite">{{ summary }}</output>
  </div>
</template>

Runtime contract

Utility Category Stability SSR Hydration Cleanup Targets Host globals Uses
compress system experimental deterministic-fallback not-applicable none web, desktop Blob, ReadableStream, TextDecoder, TextEncoder, window —
decompress system experimental deterministic-fallback not-applicable none web, desktop Blob, ReadableStream, TextDecoder, TextEncoder, window —
decompressText system experimental deterministic-fallback not-applicable none web, desktop Blob, ReadableStream, TextDecoder, TextEncoder, window —
useCompressionStream system experimental deterministic-fallback caller-managed none web, desktop Blob, ReadableStream, TextDecoder, TextEncoder, window compress, decompress, decompressText

API

compress

Compress data with the Compression Streams API. Strings are UTF-8 encoded first. Rejects with a tagged TypeError for an unknown format or when no CompressionStream is available (always on the server unless one is injected).

function compress( data: CompressionInput, format: CompressionFormatName = "gzip", options: CompressOptions = {}, ): Promise<Uint8Array<ArrayBuffer>>
const gzipped = await compress(JSON.stringify(state), "gzip");

decompress

Decompress data with the Compression Streams API. Rejects with a tagged TypeError for an unknown format or when no DecompressionStream is available, and with the stream's error for corrupt input.

function decompress( data: CompressionInput, format: CompressionFormatName = "gzip", options: DecompressOptions = {}, ): Promise<Uint8Array<ArrayBuffer>>
const bytes = await decompress(await response.blob(), "gzip");

decompressText

Decompress data and decode the result as UTF-8 text. Rejects exactly like decompress.

async function decompressText( data: CompressionInput, format: CompressionFormatName = "gzip", options: DecompressOptions = {}, ): Promise<string>
const json = JSON.parse(await decompressText(bytes, "deflate"));

useCompressionStream

Reactive wrapper around compress, decompress and decompressText. Tracks whether an action is in flight and records the last failure in error; actions still reject so callers can handle failures inline. Nothing needs cleanup. Server rendering: supported is false and actions reject with the tagged unsupported error unless constructors are injected. Inside a component supported turns true only after mounting, so hydration renders this server state first.

function useCompressionStream( options: UseCompressionStreamOptions = {}, ): CompressionStreamControls
const { compress, decompressText, pending } = useCompressionStream({ format: "deflate" });
const packed = await compress(draft.value);

Types

CompressionTransformLike

Transform stream created by a (de)compression constructor.

Member Type Description
readable ReadableStream<Uint8Array> Transformed output.
writable WritableStream<BufferSource> Raw input.

CompressOptions

Options for compress.

Member Type Description
CompressionStream? CompressionStreamConstructor | null | undefined Compression stream constructor.

DecompressOptions

Options for decompress and decompressText.

Member Type Description
DecompressionStream? CompressionStreamConstructor | null | undefined Decompression stream constructor.

UseCompressionStreamOptions

Options for useCompressionStream.

Member Type Description
CompressionStream? MaybeRef<CompressionStreamConstructor | null | undefined> Compression stream constructor. A ref (not a getter) because the host is a constructor function.
DecompressionStream? MaybeRef<CompressionStreamConstructor | null | undefined> Decompression stream constructor.
format? CompressionFormatName Format used when an action is called without one.

CompressionStreamControls

Reactive state and actions returned by useCompressionStream.

Member Type Description
supported ComputedRef<boolean> Whether both CompressionStream and DecompressionStream are available.
pending Readonly<Ref<boolean>> Whether an action is in flight.
error Readonly<ShallowRef<unknown>> Most recent failure, cleared by the next successful action.
compress ( data: CompressionInput, format?: CompressionFormatName, ) => Promise<Uint8Array<ArrayBuffer>> Compress data; rejects like compress.
decompress ( data: CompressionInput, format?: CompressionFormatName, ) => Promise<Uint8Array<ArrayBuffer>> Decompress data; rejects like decompress.
decompressText ( data: CompressionInput, format?: CompressionFormatName, ) => Promise<string> Decompress data and decode it as UTF-8.