@focus-at/zs3 0.0.0-stage → 0.0.5

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.
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/dist/zeros3.js ADDED
@@ -0,0 +1,5 @@
1
+ var y="HMAC",m="SHA256",b="AWS4",U=[b,y,m].join("-"),M=/[:-]|\.\d{3}/g,W=/<(\w)([-\w]*)(?:\/|[^>]*>((?:(?!<\1\2)[\s\S])*)<\/\1\2)>/gm,v=/\B[A-Z]/g,X=/[!'()*]/g,k=/^\/*/,H=new TextEncoder,{subtle:A}=crypto,S=(e)=>e instanceof ArrayBuffer?e:e?.buffer?.constructor===ArrayBuffer?e.buffer:H.encode(e==null?"":`${e}`).buffer,I=(e)=>Array.from(new Uint8Array(e)).map((n)=>n.toString(16).padStart(2,"0")).join(""),u=async(e,n)=>{let r=await A.importKey("raw",S(e),{name:y,hash:m},!1,["sign"]);return new Uint8Array(await A.sign(y,r,H.encode(n)))},j=async(e)=>I(await A.digest(m,S(e))),C=(e,n,r)=>{if(n)Object.keys(n).forEach((t)=>{let s=(r+(t==="expires"?t:t.replace(v,"-$&"))).toLowerCase();if(n[t]&&typeof n[t]!=="object")e[s]=`${n[t]}`});return e},Q=(e)=>encodeURIComponent(e).replace(X,(n)=>`%${n.charCodeAt(0).toString(16).toUpperCase()}`),T=(e)=>{let n={"":"",true:!0,false:!1},r=[...e.matchAll(W)];return r.length?r.reduce((t,[,s="",a="",i=""])=>{let o=s.toLowerCase()+a,c=n[i]??(isNaN(+i)?T(i):+i);return t[o]=Array.isArray(t[o])?[...t[o],c]:t[o]!=null?[t[o],c]:o==="contents"?[c]:c,t},{}):e};class B extends TransformStream{constructor(){let e=new TextDecoder,n="";super({transform(r){n+=e.decode(r,{stream:!0})},flush(r){let t=T((n+e.decode()).trim());r.enqueue(t?.listBucketResult||t)}})}}function Y(e){let n={region:"us-east-1",bucket:"",...e},r=async(t,s,a=null,i={})=>{let{endpoint:o,bucket:c,region:w,accessKeyId:G,secretAccessKey:K}=n,h=new URL(o.startsWith("http")?o:`https://${o.replace("://","")}`),l=new Date().toISOString().replace(M,""),x=l.slice(0,8),E=c?`/${c}/${s.replace(k,"")}`:s,R=a&&typeof a.getReader==="function",D=R?"UNSIGNED-PAYLOAD":await j(a||""),f=C(C({host:h.host,"x-amz-date":l,"x-amz-content-sha256":D,...a&&!R?{"content-length":`${S(a).byteLength}`}:{}},i.headers,""),i.meta,"x-amz-meta-"),[N,L=""]=E.split("?"),d=Object.keys(f).map((p)=>p.toLowerCase()).sort(),z=L?L.split("&").sort().join("&"):"",O=[t,N||"/",z,d.map((p)=>`${p}:${f[p]?.trim()}`).join(`
2
+ `)+`
3
+ `,d.join(";"),D].join(`
4
+ `),_=`${x}/${w}/s3/aws4_request`,q=await u(await u(await u(await u(`${b}${K}`,x),w),"s3"),"aws4_request"),P=I(await u(q,[U,l,_,await j(O)].join(`
5
+ `)));f.Authorization=`${U} Credential=${G}/${_}, SignedHeaders=${d.join(";")}, Signature=${P}`;let g=await fetch(new URL(E,h),{method:t,headers:f,body:a});if(!g.ok)throw Error(`S3 Error: ${g.status} - ${await g.text()}`);return t==="HEAD"?{size:+g.headers.get("content-length"),mtime:new Date(g.headers.get("last-modified")),...Object.fromEntries(g.headers)}:g};return{get:async(t,s={})=>{if(typeof t!=="object"||t===null)return r("GET",t,null,s);let a=`?list-type=2&max-keys=${t.maxKeys||1000}&prefix=${Q(t.prefix||"")}`;return(await(await r("GET",a,null,s)).body?.pipeThrough(new B).getReader()?.read()).value},put:(t,s=null,a={})=>r("PUT",t,s,a),del:(t,s={})=>r("DELETE",t,null,s),stat:(t,s={})=>r("HEAD",t,null,s),execute:r,config:n}}export{B as S3XmlTransformStream,j as hash,u as hmac,I as toHex,Y as zs3};
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,68 @@
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.5",
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
+ "files": [
56
+ "dist",
57
+ "index.ts",
58
+ "README.md",
59
+ "LICENSE"
60
+ ],
61
+ "type": "module",
62
+ "devDependencies": {
63
+ "@types/bun": "latest"
64
+ },
65
+ "peerDependencies": {
66
+ "typescript": "^5"
67
+ }
68
+ }