Skip to content

Commit 9cdde36

Browse files
committed
feat(zip): windows and linux support
Adds index.windows.ts and index.linux.ts on top of a shared, platform independent ZIP reader/writer (zip-archive.ts). The platforms only provide raw DEFLATE: System.IO.Compression.DeflateStream on Windows, the system zlib on Linux. - WinZip AES-256 for password protected archives (matches iOS/Android); AES and legacy ZipCrypto archives can be extracted - ZIP64, UTF-8 names (incl. Info-ZIP unicode path extra), progress, overwrite - entries escaping the destination and symlinks are skipped
1 parent 6a2496f commit 9cdde36

5 files changed

Lines changed: 1390 additions & 3 deletions

File tree

‎packages/zip/README.md‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ A plugin to zip and unzip files.
1111
* [Zip a folder](#zip-a-folder)
1212
* [Get zip request progress](#get-zip-request-progress)
1313
* [Get unzip request progress](#get-unzip-request-progress)
14+
* [Platform notes](#platform-notes)
1415
* [API](#api)
1516
* [Zip class](#zip-class)
1617
* [debugEnabled](#debugenabled)
@@ -113,6 +114,17 @@ function onUnZipProgress(percent: number) {
113114
}
114115
```
115116

117+
## Platform notes
118+
119+
Supported on iOS, macOS, Android, Windows and Linux.
120+
121+
On **Windows** and **Linux** the plugin reads and writes the ZIP format itself. Compression comes from the platform: .NET's `System.IO.Compression.DeflateStream` on Windows, and the system `zlib` on Linux. It needs no extra native dependencies. Details:
122+
123+
- Archives created with a `password` use WinZip AES-256 encryption, the same as iOS and Android. When unzipping, both AES and legacy ZipCrypto (PKWARE) archives are supported.
124+
- ZIP64 is supported for archives with more than 65,535 entries or larger than 4 GB.
125+
- Each entry is compressed in memory, and when unzipping the whole archive is read into memory. Very large single files (close to 2 GB) are not supported on these platforms.
126+
- Entries whose paths would escape the destination folder (`../`, absolute paths) are skipped. Symbolic links are skipped as well.
127+
116128
## API
117129

118130
### Zip class
@@ -163,7 +175,7 @@ Extracts all the files from the zip file specified in the `archive` property of
163175
| `directory` | `string`| _Optional_: The path to extract the files to.
164176
| `archive` | `string` | _Optional_: The path of the zip file.
165177
| `onProgress` | `(progress: number) => void` | _Optional_: Unzip request progress listener.
166-
| `overwrite`| `boolean` | _Optional_: (`iOS-only`)
178+
| `overwrite`| `boolean` | _Optional_: Overwrite existing files (default `true`). Supported on iOS, macOS, Windows and Linux.
167179
| `password`| `string` | _Optional_: The password used to protect the zip file.
168180

169181
## License

‎packages/zip/index.linux.ts‎

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
import { DesktopZip, ZipCodec } from './zip-archive';
2+
3+
// zlib comes with the Linux SDK metadata; its typings ship in @nativescript/linux (c!zlib.d.ts).
4+
declare const z_stream: any;
5+
declare const ZLIB_VERSION: string;
6+
declare function deflateInit2_(strm: any, level: number, method: number, windowBits: number, memLevel: number, strategy: number, version: string, streamSize: number): number;
7+
declare function deflate(strm: any, flush: number): number;
8+
declare function deflateEnd(strm: any): number;
9+
declare function deflateBound(strm: any, sourceLen: number): number;
10+
declare function inflateInit2_(strm: any, windowBits: number, version: string, streamSize: number): number;
11+
declare function inflate(strm: any, flush: number): number;
12+
declare function inflateEnd(strm: any): number;
13+
declare function crc32(crc: number, buf: ArrayBufferView, len: number): number;
14+
15+
// zlib.h constants (macros, not part of the metadata).
16+
const Z_OK = 0;
17+
const Z_STREAM_END = 1;
18+
const Z_BUF_ERROR = -5;
19+
const Z_NO_FLUSH = 0;
20+
const Z_FINISH = 4;
21+
const Z_DEFLATED = 8;
22+
const Z_DEFAULT_COMPRESSION = -1;
23+
const Z_DEFAULT_STRATEGY = 0;
24+
const RAW_WINDOW_BITS = -15;
25+
const MEM_LEVEL = 8;
26+
const CHUNK = 64 * 1024;
27+
28+
function zlibError(operation: string, code: number, stream: any): Error {
29+
let message = '';
30+
try {
31+
const msg = stream?.msg;
32+
message = msg ? (typeof msg === 'string' ? msg : (interop as any).stringFromCString(msg)) : '';
33+
} catch (e) {
34+
// ignore
35+
}
36+
return new Error(`zlib ${operation} failed (${code})${message ? `: ${message}` : ''}`);
37+
}
38+
39+
const codec: ZipCodec = {
40+
deflateRaw(data: Uint8Array): Uint8Array {
41+
// One z_stream per call; zlib checks that the state points back at the same struct, and the
42+
// struct's memory never moves, so keep passing this exact object.
43+
const stream = new z_stream();
44+
let rc = deflateInit2_(stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, RAW_WINDOW_BITS, MEM_LEVEL, Z_DEFAULT_STRATEGY, ZLIB_VERSION, interop.sizeof(z_stream));
45+
if (rc !== Z_OK) {
46+
throw zlibError('deflateInit2', rc, stream);
47+
}
48+
try {
49+
// The bound is enough for a single Z_FINISH call to complete.
50+
const output = new Uint8Array(Number(deflateBound(stream, data.length)) + 16);
51+
stream.next_in = data;
52+
stream.avail_in = data.length;
53+
stream.next_out = output;
54+
stream.avail_out = output.length;
55+
rc = deflate(stream, Z_FINISH);
56+
if (rc !== Z_STREAM_END) {
57+
throw zlibError('deflate', rc, stream);
58+
}
59+
return output.subarray(0, Number(stream.total_out));
60+
} finally {
61+
deflateEnd(stream);
62+
}
63+
},
64+
65+
inflateRaw(data: Uint8Array, size: number): Uint8Array {
66+
const stream = new z_stream();
67+
let rc = inflateInit2_(stream, RAW_WINDOW_BITS, ZLIB_VERSION, interop.sizeof(z_stream));
68+
if (rc !== Z_OK) {
69+
throw zlibError('inflateInit2', rc, stream);
70+
}
71+
try {
72+
// `size` comes from the archive; grow if it lies.
73+
let output = new Uint8Array(Math.max(size, 1));
74+
stream.next_in = data;
75+
stream.avail_in = data.length;
76+
let produced = 0;
77+
for (;;) {
78+
if (produced === output.length) {
79+
const grown = new Uint8Array(output.length + Math.max(CHUNK, output.length));
80+
grown.set(output);
81+
output = grown;
82+
}
83+
const window = output.subarray(produced);
84+
stream.next_out = window;
85+
stream.avail_out = window.length;
86+
rc = inflate(stream, Z_NO_FLUSH);
87+
produced = output.length - Number(stream.avail_out);
88+
if (rc === Z_STREAM_END) {
89+
break;
90+
}
91+
if (rc === Z_BUF_ERROR && Number(stream.avail_out) > 0) {
92+
throw zlibError('inflate', rc, stream); // truncated input
93+
}
94+
if (rc !== Z_OK && rc !== Z_BUF_ERROR) {
95+
throw zlibError('inflate', rc, stream);
96+
}
97+
}
98+
return produced === output.length ? output : output.slice(0, produced);
99+
} finally {
100+
inflateEnd(stream);
101+
}
102+
},
103+
104+
crc32(data: Uint8Array): number {
105+
return data.length === 0 ? 0 : Number(crc32(0, data, data.length)) >>> 0;
106+
},
107+
};
108+
109+
export class Zip extends DesktopZip {
110+
protected static codec = codec;
111+
}

‎packages/zip/index.windows.ts‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
import { DesktopZip, ZipCodec } from './zip-archive';
2+
3+
// .NET namespaces are globals on the Windows runtime (dotnet-bridge).
4+
declare const System: any;
5+
declare const NSWinRT: any;
6+
7+
let compressionLoaded = false;
8+
9+
/** System.IO.Compression lives in the shared framework folder, which the bridge does not search. */
10+
function ensureCompressionAssembly() {
11+
if (compressionLoaded) {
12+
return;
13+
}
14+
try {
15+
const dir = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory();
16+
NSWinRT.dotnet.loadAssembly(System.IO.Path.Combine(dir, 'System.IO.Compression.dll'));
17+
} catch (e) {
18+
// Already loaded by the host, or resolvable without help; a failure surfaces on first use.
19+
}
20+
compressionLoaded = true;
21+
}
22+
23+
const codec: ZipCodec = {
24+
// DeflateStream reads/writes raw DEFLATE (RFC 1951), which is exactly what ZIP entries contain.
25+
// Byte arrays cross the bridge by value, so all streams are .NET-side MemoryStreams and the
26+
// result comes back through ToArray().
27+
deflateRaw(data: Uint8Array): Uint8Array {
28+
ensureCompressionAssembly();
29+
const Compression = System.IO.Compression;
30+
const source = new System.IO.MemoryStream(data);
31+
const target = new System.IO.MemoryStream();
32+
const deflater = new Compression.DeflateStream(target, Compression.CompressionLevel.Optimal, true);
33+
try {
34+
source.CopyTo(deflater);
35+
} finally {
36+
deflater.Dispose();
37+
source.Dispose();
38+
}
39+
try {
40+
return toBytes(target.ToArray());
41+
} finally {
42+
target.Dispose();
43+
}
44+
},
45+
46+
inflateRaw(data: Uint8Array, _size: number): Uint8Array {
47+
ensureCompressionAssembly();
48+
const Compression = System.IO.Compression;
49+
const source = new System.IO.MemoryStream(data);
50+
const inflater = new Compression.DeflateStream(source, Compression.CompressionMode.Decompress);
51+
const target = new System.IO.MemoryStream();
52+
try {
53+
inflater.CopyTo(target);
54+
return toBytes(target.ToArray());
55+
} finally {
56+
inflater.Dispose();
57+
source.Dispose();
58+
target.Dispose();
59+
}
60+
},
61+
};
62+
63+
function toBytes(value: any): Uint8Array {
64+
if (value instanceof Uint8Array) {
65+
return value;
66+
}
67+
if (ArrayBuffer.isView(value)) {
68+
return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
69+
}
70+
if (value instanceof ArrayBuffer) {
71+
return new Uint8Array(value);
72+
}
73+
return Uint8Array.from(value ?? []);
74+
}
75+
76+
export class Zip extends DesktopZip {
77+
protected static codec = codec;
78+
}

‎packages/zip/package.json‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@
88
"platforms": {
99
"ios": "6.0.0",
1010
"macos": "6.0.0",
11-
"android": "6.0.0"
11+
"android": "6.0.0",
12+
"windows": "9.1.0",
13+
"linux": "0.1.0-alpha.2"
1214
}
1315
},
1416
"repository": {
@@ -21,7 +23,9 @@
2123
"TypeScript",
2224
"iOS",
2325
"macOS",
24-
"Android"
26+
"Android",
27+
"Windows",
28+
"Linux"
2529
],
2630
"author": {
2731
"name": "NativeScript",

0 commit comments

Comments
 (0)