@focus-at/zs3 0.0.0-stage → 0.0.4

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.
@@ -0,0 +1,28 @@
1
+ name: Publish to NPM
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+
7
+ jobs:
8
+ publish:
9
+ runs-on: ubuntu-latest
10
+ steps:
11
+ - name: Checkout repository
12
+ uses: actions/checkout@v4
13
+
14
+ - name: Setup Bun
15
+ uses: oven-sh/setup-bun@v1
16
+ with:
17
+ bun-version: latest
18
+
19
+ - name: Install dependencies
20
+ run: bun install --frozen-lockfile
21
+
22
+ - name: Build Library and CLI
23
+ run: bun run build
24
+
25
+ - name: Publish Package
26
+ run: bun publish --access=public
27
+ env:
28
+ NPM_CONFIG_TOKEN: ${{ secrets.NPM_TOKEN }}
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dmitry Zimin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,49 @@
1
- # Temporary Holding Version
1
+ # ZeroS3
2
+ ![GitHub License](https://img.shields.io/github/license/focus-at/zs3)
3
+ ![GitHub Stars](https://img.shields.io/github/stars/focus-at/zs3)
2
4
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
5
+ An ultra-lightweight (~3 KB) and high-performance client for S3-compatible cloud storage (AWS S3, MinIO, Cloudflare R2, Backblaze B2), built purely on modern Web Standards (`fetch`, `crypto.subtle`).
6
+
7
+ **Zero external dependencies.** Engineered for custom JS runtimes, Edge functions, Serverless environments, or any setup highly sensitive to bundle size and cold-start times.
8
+
9
+ ## Installation
10
+
11
+ ```js
12
+ import { zs3 } from 'zeros3';
13
+ ```
14
+
15
+ ## Quick Start
16
+
17
+ ```js
18
+ const storage = zs3({
19
+ endpoint: '127.0.0.1:9000',
20
+ accessKeyId: 'your-access-key-id',
21
+ secretAccessKey: 'your-secret-access-key',
22
+ bucket: 'production-assets'
23
+ });
24
+
25
+ // 1. Upload a file (String, Buffer, or Web Stream)
26
+ await storage.put('bundles/app.tar', tarStream, {
27
+ headers: { contentType: 'application/x-tar' }
28
+ });
29
+
30
+ // 2. Download a file (returns fetch Response, stream is in .body)
31
+ const res = await storage.get('bundles/app.tar');
32
+ const downloadStream = res.body;
33
+
34
+ // 3. List files (pass an object containing a prefix)
35
+ const files = await storage.get({ prefix: 'bundles/' });
36
+ console.log(files.contents);
37
+
38
+ // 4. Retrieve metadata (HEAD request)
39
+ const meta = await storage.stat('bundles/app.tar');
40
+ console.log(meta.size, meta['x-amz-meta-version']);
41
+
42
+ // 5. Delete an object
43
+ await storage.del('bundles/app.tar');
44
+ ```
45
+
46
+ ## Features
47
+ - **Closure-Based Design (No `this`)**: Every single client method can be safely destructured and decoupled without losing context: `const { get, put } = zs3(opts);`.
48
+ - **Inlined Micro XML Parser**: Seamlessly converts S3 object listings without bloating your `node_modules` or running a heavy general-purpose parser.
49
+ - **Robust AWS v4 Signatures**: Automatically manages query parameter alphabetical sorting, whitespace trimming, and strict URI hex-encoding under the hood.
package/index.ts ADDED
@@ -0,0 +1,152 @@
1
+ export interface S3Config {
2
+ endpoint: string;
3
+ accessKeyId: string;
4
+ secretAccessKey: string;
5
+ bucket?: string;
6
+ region?: string;
7
+ [key: string]: any;
8
+ }
9
+
10
+ export interface S3Options {
11
+ headers?: Record<string, string>;
12
+ meta?: Record<string, string>;
13
+ }
14
+
15
+ export interface ListOptions {
16
+ prefix?: string;
17
+ maxKeys?: number;
18
+ }
19
+
20
+ export interface S3StatResponse extends Record<string, any> {
21
+ size: number;
22
+ mtime: Date;
23
+ }
24
+
25
+ const ALG_NAME = ('HMAC' + '');
26
+ const ALG_HASH = ('SHA256' + '');
27
+ const AWS4 = ('AWS4' + '');
28
+ const SIGN_P = [AWS4, ALG_NAME, ALG_HASH].join('-');
29
+ const RE_ISO_DATE = /[:-]|\.\d{3}/g;
30
+ const RE_XML_TAGS = /<(\w)([-\w]*)(?:\/|[^>]*>((?:(?!<\1\2)[\s\S])*)<\/\1\2)>/gm;
31
+ const RE_DASH_CASE = /\B[A-Z]/g;
32
+ const RE_ENCODE_URI = /[!'()*]/g;
33
+ const RE_LEADING_SLASHES = /^\/*/;
34
+
35
+ const enc = new TextEncoder();
36
+ const { subtle } = crypto;
37
+
38
+ const toArrayBuffer = (d: any): ArrayBuffer =>
39
+ d instanceof ArrayBuffer ? d : d?.buffer?.constructor === ArrayBuffer ? d.buffer : enc.encode(d == null ? '' : `${d}`).buffer;
40
+
41
+ export const toHex = (buf: ArrayBuffer | Uint8Array):string =>
42
+ Array.from(new Uint8Array(buf)).map(b => b.toString(16).padStart(2, '0')).join('');
43
+
44
+ export const hmac = async (key: string | Uint8Array | ArrayBuffer, data: string): Promise<Uint8Array> => {
45
+ const cryptoKey = await subtle.importKey('raw', toArrayBuffer(key), { name: ALG_NAME, hash: ALG_HASH}, false, ['sign']);
46
+ return new Uint8Array(await subtle.sign(ALG_NAME, cryptoKey, enc.encode(data)));
47
+ };
48
+
49
+ export const hash = async (data: any) => toHex(await subtle.digest(ALG_HASH, toArrayBuffer(data)));
50
+
51
+ const assignDashCase = (target: Record<string, string>, source: Record<string, any> | undefined, prefix: string): Record<string, string> => {
52
+ if (source) Object.keys(source).forEach(key => {
53
+ const name = (prefix + (key === "expires" ? key : key.replace(RE_DASH_CASE, "-$&"))).toLowerCase();
54
+ if (source[key] && typeof source[key] !== 'object') target[name] = `${source[key]}`;
55
+ });
56
+ return target;
57
+ };
58
+
59
+ const awsEncodeURI = (str: string): string =>
60
+ encodeURIComponent(str).replace(RE_ENCODE_URI, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
61
+
62
+ const parseXml = (str: string): any => {
63
+ const types: Record<string, any> = { "": "", "true": true, "false": false };
64
+ const m = [...str.matchAll(RE_XML_TAGS)];
65
+ return m.length ? m.reduce((acc: any, [, tag = '', suffix = '', content = '']) => {
66
+ const k = tag.toLowerCase() + suffix;
67
+ const v = types[content] ?? (isNaN(+content) ? parseXml(content) : +content);
68
+ acc[k] = Array.isArray(acc[k]) ? [...acc[k], v] : acc[k] != null ? [acc[k], v] : k === "contents" ? [v] : v;
69
+ return acc;
70
+ }, {}) : str;
71
+ };
72
+
73
+ export class S3XmlTransformStream extends TransformStream<Uint8Array, any> {
74
+ constructor() {
75
+ const decoder = new TextDecoder();
76
+ let acc = "";
77
+ super({
78
+ transform(chunk) { acc += decoder.decode(chunk, { stream: true }); },
79
+ flush(c) {
80
+ const res = parseXml((acc + decoder.decode()).trim());
81
+ c.enqueue(res?.listBucketResult || res);
82
+ }
83
+ });
84
+ }
85
+ }
86
+
87
+ export function zs3(opts: S3Config) {
88
+ const config = { region: 'us-east-1', bucket: '', ...opts };
89
+ const execute = async (method: string, path: string, body: any = null, options: S3Options = {}): Promise<Response | any> => {
90
+ const {
91
+ endpoint,
92
+ bucket,
93
+ region,
94
+ accessKeyId,
95
+ secretAccessKey
96
+ } = config;
97
+ const base = new URL(endpoint.startsWith('http') ? endpoint : `https://${endpoint.replace('://', '')}`);
98
+ const isoDate = new Date().toISOString().replace(RE_ISO_DATE, '');
99
+ const sDate = isoDate.slice(0, 8);
100
+ const pathname = bucket ? `/${bucket}/${path.replace(RE_LEADING_SLASHES, '')}` : path;
101
+ const isStream = body && typeof body.getReader === 'function';
102
+ const payloadHash = isStream ? 'UNSIGNED-PAYLOAD' : await hash(body || '');
103
+
104
+ const headers: Record<string, string> = assignDashCase(assignDashCase({
105
+ host: base.host,
106
+ 'x-amz-date': isoDate,
107
+ 'x-amz-content-sha256': payloadHash,
108
+ ...(body && !isStream ? { 'content-length': `${toArrayBuffer(body).byteLength}` } : {})
109
+ }, options.headers, ""), options.meta, "x-amz-meta-");
110
+
111
+ const [uri, query = ''] = pathname.split('?');
112
+ const sortedHeaders = Object.keys(headers).map(k => k.toLowerCase()).sort();
113
+ const sortedQuery = query ? query.split('&').sort().join('&') : '';
114
+
115
+ const canonical = [method, uri || '/', sortedQuery, sortedHeaders.map(k => `${k}:${headers[k]?.trim()}`).join('\n') + '\n', sortedHeaders.join(';'), payloadHash].join('\n');
116
+ const scope = `${sDate}/${region}/s3/aws4_request`;
117
+
118
+ const kSign = await hmac(await hmac(await hmac(await hmac(`${AWS4}${secretAccessKey}`, sDate), region), 's3'), 'aws4_request');
119
+ const signature = toHex(await hmac(kSign, [SIGN_P, isoDate, scope, await hash(canonical)].join('\n')));
120
+
121
+ headers['Authorization'] = `${SIGN_P} Credential=${accessKeyId}/${scope}, SignedHeaders=${sortedHeaders.join(';')}, Signature=${signature}`;
122
+
123
+ const res = await fetch(new URL(pathname, base), { method, headers, body });
124
+ if (!res.ok) throw new Error(`S3 Error: ${res.status} - ${await res.text()}`);
125
+
126
+ return method === 'HEAD' ? {
127
+ size: +res.headers.get("content-length")!,
128
+ mtime: new Date(res.headers.get("last-modified")!),
129
+ ...Object.fromEntries(res.headers)
130
+ } : res;
131
+ };
132
+
133
+ return {
134
+ get: async (keyOrOpts: string | ListOptions, options: S3Options = {}) => {
135
+ if (typeof keyOrOpts !== 'object' || keyOrOpts === null) {
136
+ return execute('GET', keyOrOpts, null, options);
137
+ }
138
+
139
+ const query = `?list-type=2&max-keys=${keyOrOpts.maxKeys || 1000}&prefix=${awsEncodeURI(keyOrOpts.prefix || '')}`;
140
+ const res = await execute('GET', query, null, options);
141
+
142
+ const reader = res.body?.pipeThrough(new S3XmlTransformStream()).getReader();
143
+
144
+ return (await reader?.read()).value
145
+ },
146
+ put: (path: string, body: any = null, options: S3Options = {}) => execute('PUT', path, body, options),
147
+ del: (path: string, options: S3Options = {}) => execute('DELETE', path, null, options),
148
+ stat: (path: string, options: S3Options = {}) => execute('HEAD', path, null, options),
149
+ execute,
150
+ config
151
+ };
152
+ }
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "@focus-at/zs3",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.4",
4
+ "description": "Zero-dependency micro S3 client built on Web Standards",
5
+ "homepage": "https://github.com/focus-at/zs3#readme",
6
+ "module": "index.ts",
7
+ "main": "./dist/zeros3.js",
8
+ "types": "./index.ts",
9
+ "bin": {
10
+ "zs3": "./dist/zs3.js"
11
+ },
12
+ "exports": {
13
+ ".": {
14
+ "types": "./index.ts",
15
+ "import": {
16
+ "typescript": "./index.ts",
17
+ "default": "./dist/zeros3.js"
18
+ }
19
+ }
20
+ },
21
+ "scripts": {
22
+ "build": "bun build --minify ./index.ts --outfile=dist/zeros3.js",
23
+ "release": "npm version patch && git push origin main --tags",
24
+ "postinstall": "node -e \"if(!process.env.DISABLE_OPENCOLLECTIVE && !process.env.CI){process.stdout.write('\\u001b[35mThanks for installing ZeroS3! Consider giving it a star on GitHub: https://github.com\\u001b[0m\\n')}\""
25
+ },
26
+ "keywords": [
27
+ "s3",
28
+ "aws-s3",
29
+ "zeros3",
30
+ "zs3",
31
+ "micro",
32
+ "zero-dependency",
33
+ "web-standards",
34
+ "fetch",
35
+ "runtime",
36
+ "browser",
37
+ "cloudflare-workers",
38
+ "esm"
39
+ ],
40
+ "author": "Dmitry Zimin",
41
+ "license": "MIT",
42
+ "repository": {
43
+ "type": "git",
44
+ "url": "git@github.com:focus-at/zs3.git"
45
+ },
46
+ "bugs": {
47
+ "url": "https://github.com/focus-at/zs3/issues"
48
+ },
49
+ "funding": [
50
+ {
51
+ "type": "github",
52
+ "url": "https://github.com/focus-at/zs3/issues"
53
+ }
54
+ ],
55
+ "type": "module",
56
+ "devDependencies": {
57
+ "@types/bun": "latest"
58
+ },
59
+ "peerDependencies": {
60
+ "typescript": "^5"
61
+ }
62
+ }
@@ -0,0 +1,141 @@
1
+ import { describe, test, expect, afterEach, beforeEach } from "bun:test";
2
+ import { zs3, hash, hmac, toHex } from "../index.ts";
3
+
4
+ describe("ZeroS3 / zs3 Core Tests", () => {
5
+ const originalFetch = globalThis.fetch;
6
+
7
+ // Объявляем переменную для хранения инстанса
8
+ let storage: ReturnType<typeof zs3>;
9
+ let lastRequest = { url: null as URL | null, headers: {} as Record<string, string> };
10
+
11
+ const mockFetch = (xmlContent = "", status = 200) => {
12
+ globalThis.fetch = (async (url: URL, init?: RequestInit) => {
13
+ lastRequest.url = url;
14
+ lastRequest.headers = (init?.headers as Record<string, string>) || {};
15
+ return new Response(xmlContent, { status });
16
+ }) as unknown as typeof fetch;
17
+ };
18
+
19
+ // ИСПРАВЛЕНО: Сбрасываем и пересоздаем инстанс перед КАЖДЫМ тестом
20
+ beforeEach(() => {
21
+ storage = zs3({
22
+ endpoint: "127.0.0.1:9000",
23
+ accessKeyId: "mock-access-key",
24
+ secretAccessKey: "mock-secret-key",
25
+ bucket: "test-bucket",
26
+ });
27
+ });
28
+
29
+ // Хук afterEach гарантирует, что после каждого теста fetch вернется в исходное состояние
30
+ afterEach(() => {
31
+ globalThis.fetch = originalFetch;
32
+ });
33
+
34
+ test("should correctly export core cryptographic utilities with strict check", async () => {
35
+ const signature = await hmac("secret", "data");
36
+ expect(signature).toBeInstanceOf(Uint8Array);
37
+ expect(toHex(signature)).toBe("1b2c16b75bd2a870c114153ccda5bcfca63314bc722fa160d690de133ccbb9db");
38
+ expect(await hash("hello zeros3")).toBe("dea9a435609aadbdaf641ddb2b0d1ad1d97263798769b6e43188d0ba57b79fad");
39
+ });
40
+
41
+ test("should correctly merge config defaults and reactively update on changes", async () => {
42
+ expect(storage.config.region).toBe("us-east-1");
43
+ expect(storage.config.bucket).toBe("test-bucket");
44
+
45
+ mockFetch();
46
+
47
+ // 1. Проверяем генерацию путей со старым конфигом
48
+ await storage.stat("file.txt");
49
+ expect(lastRequest.url?.pathname).toBe("/test-bucket/file.txt");
50
+ expect(lastRequest.url?.host).toBe("127.0.0.1:9000");
51
+ expect(lastRequest.headers["Authorization"]).toContain("/us-east-1/s3/aws4_request");
52
+
53
+ // 2. Меняем конфиг, подсовывая кривой эндпоинт с ://
54
+ storage.config.bucket = "dynamic-bucket";
55
+ storage.config.endpoint = "://zone.com";
56
+ storage.config.region = "eu-west-1";
57
+
58
+ // 3. Вызываем деструктурированный put — он обязан отработать реактивно
59
+ await storage.put("image.png", "payload");
60
+
61
+ expect(lastRequest.url?.host).toBe("zone.com");
62
+ expect(lastRequest.url?.protocol).toBe("https:");
63
+ expect(lastRequest.url?.pathname).toBe("/dynamic-bucket/image.png");
64
+ expect(lastRequest.headers["Authorization"]).toContain("/eu-west-1/s3/aws4_request");
65
+ });
66
+
67
+ test("should perfectly stream and parse large XML data and empty tags", async () => {
68
+ const xmlMock = `
69
+ <ListBucketResult>
70
+ <Name>test-bucket</Name>
71
+ <Prefix>production/</Prefix>
72
+ <MaxKeys>1000</MaxKeys>
73
+ <IsTruncated>false</IsTruncated>
74
+ <Marker></Marker>
75
+ <NextMarker/>
76
+ <Contents>
77
+ <Key>production/app.tar</Key>
78
+ <Size>31457280</Size>
79
+ </Contents>
80
+ <Contents>
81
+ <Key>production/config.json</Key>
82
+ <Size>2048</Size>
83
+ </Contents>
84
+ </ListBucketResult>
85
+ `;
86
+
87
+ globalThis.fetch = (async () => new Response(xmlMock, { status: 200 })) as unknown as typeof fetch;
88
+
89
+ const result = await storage.get({ prefix: "production/" });
90
+
91
+ // Top Level
92
+ expect(result.name).toBe("test-bucket");
93
+ expect(result.marker).toBe("");
94
+ expect(result.nextMarker).toBe("");
95
+ expect(result.isTruncated).toBe(false);
96
+ expect(result.maxKeys).toBe(1000);
97
+
98
+ // Array
99
+ expect(result.contents).toBeInstanceOf(Array);
100
+ expect(result.contents.length).toBe(2);
101
+ expect(result.contents[0].key).toBe("production/app.tar");
102
+ expect(result.contents[0].size).toBe(31457280);
103
+ expect(result.contents[1].key).toBe("production/config.json");
104
+ expect(result.contents[1].size).toBe(2048);
105
+ });
106
+
107
+ test("should perfectly stream and parse large XML data, empty tags and clean root prefix", async () => {
108
+ mockFetch(`
109
+ <ListBucketResult>
110
+ <Name>test-bucket</Name>
111
+ <Prefix></Prefix>
112
+ <MaxKeys>1000</MaxKeys>
113
+ <IsTruncated>false</IsTruncated>
114
+ <Marker></Marker>
115
+ <NextMarker/>
116
+ <Contents>
117
+ <Key>production/app.tar</Key>
118
+ <Size>31457280</Size>
119
+ </Contents>
120
+ </ListBucketResult>
121
+ `)
122
+
123
+ // Вызываем с ПУСТЫМ префиксом
124
+ const result = await storage.get({ prefix: "" });
125
+
126
+ // 1. ПРОВЕРКА ПРЕФИКСА В URL (убеждаемся, что пустой префикс не сломал строку)
127
+ expect(lastRequest.url?.search).toContain("prefix=");
128
+ expect(lastRequest.url?.pathname).toBe("/test-bucket/"); // Без двойных слэшей на конце!
129
+
130
+ // 2. ПРОВЕРКА ПУСТЫХ ТЕГОВ (убеждаемся, что они не стали числами 0 или null)
131
+ expect(result.prefix).toBe("");
132
+ expect(result.marker).toBe("");
133
+ expect(result.nextMarker).toBe("");
134
+
135
+ // 3. ПРОВЕРКА ТИПОВ И СТРУКТУРЫ ДАННЫХ
136
+ expect(result.isTruncated).toBe(false);
137
+ expect(result.maxKeys).toBe(1000);
138
+ expect(result.contents[0].key).toBe("production/app.tar");
139
+ expect(result.contents[0].size).toBe(31457280);
140
+ });
141
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,29 @@
1
+ {
2
+ "compilerOptions": {
3
+ // Environment setup & latest features
4
+ "lib": ["ESNext"],
5
+ "target": "ESNext",
6
+ "module": "Preserve",
7
+ "moduleDetection": "force",
8
+ "jsx": "react-jsx",
9
+ "allowJs": true,
10
+
11
+ // Bundler mode
12
+ "moduleResolution": "bundler",
13
+ "allowImportingTsExtensions": true,
14
+ "verbatimModuleSyntax": true,
15
+ "noEmit": true,
16
+
17
+ // Best practices
18
+ "strict": true,
19
+ "skipLibCheck": true,
20
+ "noFallthroughCasesInSwitch": true,
21
+ "noUncheckedIndexedAccess": true,
22
+ "noImplicitOverride": true,
23
+
24
+ // Some stricter flags (disabled by default)
25
+ "noUnusedLocals": false,
26
+ "noUnusedParameters": false,
27
+ "noPropertyAccessFromIndexSignature": false
28
+ }
29
+ }