@adep/runtime 0.1.1 → 0.1.3

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/dist/index.d.ts CHANGED
@@ -28,6 +28,7 @@ export { createDbCapability, type CreateDbCapabilityOptions } from './database/s
28
28
  export { createCloudDb, type CreateCloudDbOptions } from './database/builder';
29
29
  export { createStorageCapability } from './storage/cloud';
30
30
  export { createLocalStorageDriver, type LocalStorageOptions } from './storage/driver/local';
31
+ export { createS3StorageDriver, type S3StorageOptions } from './storage/driver/s3';
31
32
  export type { StorageDriver, StoredFileMeta, FileVisibility } from './storage/driver';
32
33
  export { StorageError, STORAGE_CODES } from './storage/driver';
33
34
  export { signDownloadUrl, verifyDownloadSignature } from './storage/signature';
package/dist/index.js CHANGED
@@ -1545,6 +1545,324 @@ function createLocalStorageDriver(options) {
1545
1545
  };
1546
1546
  }
1547
1547
 
1548
+ // packages/runtime/src/storage/driver/s3.ts
1549
+ var DEFAULT_REGION = "us-east-1";
1550
+ var SERVICE = "s3";
1551
+ var LIST_PAGE_LIMIT = 1e3;
1552
+ var HEAD_CONCURRENCY = 8;
1553
+ var objectKey = (projectId, path) => `${projectId}/${path}`;
1554
+ var projectPrefix = (projectId) => `${projectId}/`;
1555
+ function hex(bytes) {
1556
+ let out = "";
1557
+ for (const byte of bytes) out += byte.toString(16).padStart(2, "0");
1558
+ return out;
1559
+ }
1560
+ function utf8(text) {
1561
+ return new TextEncoder().encode(text);
1562
+ }
1563
+ function sha256Hex(data) {
1564
+ return hex(sha256(data));
1565
+ }
1566
+ function s3Encode(value) {
1567
+ return encodeURIComponent(value).replace(
1568
+ /[!'()*]/g,
1569
+ (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`
1570
+ );
1571
+ }
1572
+ function encodeKeyPath(key) {
1573
+ return key.split("/").map(s3Encode).join("/");
1574
+ }
1575
+ function isoFromHttpDate(value) {
1576
+ if (value === null || value.length === 0) return (/* @__PURE__ */ new Date(0)).toISOString();
1577
+ const parsed = Date.parse(value);
1578
+ return Number.isNaN(parsed) ? (/* @__PURE__ */ new Date(0)).toISOString() : new Date(parsed).toISOString();
1579
+ }
1580
+ function xmlUnescape(value) {
1581
+ return value.replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'");
1582
+ }
1583
+ function amzTime(now) {
1584
+ const iso = now.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}/, "");
1585
+ return { amzDate: iso, dateStamp: iso.slice(0, 8) };
1586
+ }
1587
+ function parseListXml(xml) {
1588
+ const keys = [];
1589
+ const contentsRe = /<Contents>([\s\S]*?)<\/Contents>/g;
1590
+ let match;
1591
+ while ((match = contentsRe.exec(xml)) !== null) {
1592
+ const block = match[1] ?? "";
1593
+ const key = /<Key>([\s\S]*?)<\/Key>/.exec(block)?.[1];
1594
+ if (key === void 0) continue;
1595
+ const lastModified = /<LastModified>([\s\S]*?)<\/LastModified>/.exec(block)?.[1];
1596
+ keys.push({
1597
+ key: xmlUnescape(key),
1598
+ size: Number(/<Size>(\d+)<\/Size>/.exec(block)?.[1] ?? 0),
1599
+ ...lastModified === void 0 ? {} : { lastModified }
1600
+ });
1601
+ }
1602
+ const truncated = /<IsTruncated>true<\/IsTruncated>/.test(xml);
1603
+ const nextToken = /<NextContinuationToken>([\s\S]*?)<\/NextContinuationToken>/.exec(xml)?.[1];
1604
+ return {
1605
+ keys,
1606
+ truncated,
1607
+ ...nextToken === void 0 ? {} : { nextToken }
1608
+ };
1609
+ }
1610
+ async function mapLimit(items, limit, fn) {
1611
+ const results = Array.from({ length: items.length });
1612
+ let next = 0;
1613
+ const workerCount = Math.min(limit, items.length);
1614
+ if (workerCount === 0) return results;
1615
+ const workers = Array.from({ length: workerCount }, async () => {
1616
+ while (next < items.length) {
1617
+ const index = next;
1618
+ next += 1;
1619
+ results[index] = await fn(items[index]);
1620
+ }
1621
+ });
1622
+ await Promise.all(workers);
1623
+ return results;
1624
+ }
1625
+ function signV4(input) {
1626
+ const headerNames = Object.keys(input.headers).toSorted();
1627
+ const canonicalHeaders = headerNames.map((name) => `${name}:${input.headers[name]}`).join("\n") + "\n";
1628
+ const signedHeaders = headerNames.join(";");
1629
+ const canonicalRequest = [
1630
+ input.method,
1631
+ input.canonicalUri,
1632
+ input.canonicalQuery,
1633
+ canonicalHeaders,
1634
+ signedHeaders,
1635
+ input.payloadHash
1636
+ ].join("\n");
1637
+ const scope = `${input.dateStamp}/${input.region}/${SERVICE}/aws4_request`;
1638
+ const stringToSign = [
1639
+ "AWS4-HMAC-SHA256",
1640
+ input.amzDate,
1641
+ scope,
1642
+ sha256Hex(utf8(canonicalRequest))
1643
+ ].join("\n");
1644
+ const kDate = hmacSha256(utf8(`AWS4${input.secretKey}`), input.dateStamp);
1645
+ const kRegion = hmacSha256(kDate, input.region);
1646
+ const kService = hmacSha256(kRegion, SERVICE);
1647
+ const kSigning = hmacSha256(kService, "aws4_request");
1648
+ const signature = hex(hmacSha256(kSigning, stringToSign));
1649
+ return `AWS4-HMAC-SHA256 Credential=${input.accessKey}/${scope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;
1650
+ }
1651
+ var mapError = async (res, message) => {
1652
+ let code = "";
1653
+ try {
1654
+ const xml = await res.text();
1655
+ code = /<Code>([\s\S]*?)<\/Code>/.exec(xml)?.[1] ?? "";
1656
+ } catch {
1657
+ }
1658
+ if (res.status === 404 && (code === "NoSuchKey" || code === "NoSuchBucket" || code === "")) {
1659
+ throw new StorageError(404, STORAGE_CODES.notFound, message);
1660
+ }
1661
+ if (res.status === 403 || res.status === 401) {
1662
+ throw new StorageError(
1663
+ res.status,
1664
+ "STORAGE_ACCESS_DENIED",
1665
+ `\u5BF9\u8C61\u5B58\u50A8\u8BBF\u95EE\u88AB\u62D2\u7EDD\uFF08HTTP ${res.status} ${code || "AccessDenied"}\uFF09\uFF1A${message}`
1666
+ );
1667
+ }
1668
+ throw new StorageError(
1669
+ 502,
1670
+ "STORAGE_BACKEND_ERROR",
1671
+ `\u5BF9\u8C61\u5B58\u50A8\u540E\u7AEF\u9519\u8BEF\uFF08HTTP ${res.status} ${code || ""}\uFF09\uFF1A${message}`
1672
+ );
1673
+ };
1674
+ var assertPrefix = (prefix) => {
1675
+ if (prefix !== void 0 && prefix !== "") {
1676
+ const segments = prefix.split("/");
1677
+ if (prefix.startsWith("/") || /[\\]/.test(prefix) || segments.some((segment) => segment === "..")) {
1678
+ throw new StorageError(
1679
+ 400,
1680
+ STORAGE_CODES.invalidPath,
1681
+ `\u975E\u6CD5\u524D\u7F00 "${prefix}"\uFF08\u7981\u6B62 / \u5F00\u5934\u3001\u53CD\u659C\u6760\u6216 .. \u7A7F\u8D8A\uFF09`
1682
+ );
1683
+ }
1684
+ }
1685
+ return prefix ?? "";
1686
+ };
1687
+ function createS3StorageDriver(options) {
1688
+ const region = options.region ?? DEFAULT_REGION;
1689
+ const quotaBytes = options.quotaBytes ?? PROJECT_QUOTA_BYTES;
1690
+ const endpoint = options.endpoint.replace(/\/+$/, "");
1691
+ const bucket = options.bucket;
1692
+ const buildUrl = (objectKeyValue, query) => {
1693
+ const base = objectKeyValue === void 0 ? `${endpoint}/${bucket}` : `${endpoint}/${bucket}/${encodeKeyPath(objectKeyValue)}`;
1694
+ const names = Object.keys(query).toSorted();
1695
+ if (names.length === 0) return base;
1696
+ const queryString = names.map((name) => `${s3Encode(name)}=${s3Encode(query[name])}`).join("&");
1697
+ return `${base}?${queryString}`;
1698
+ };
1699
+ const request = async (reqOpts) => {
1700
+ const body = reqOpts.body ?? new Uint8Array();
1701
+ const payloadHash = sha256Hex(body);
1702
+ const now = /* @__PURE__ */ new Date();
1703
+ const { amzDate, dateStamp } = amzTime(now);
1704
+ const query = reqOpts.query ?? {};
1705
+ const url = buildUrl(reqOpts.objectKey, query);
1706
+ const parsed = new URL(url);
1707
+ const headers = {
1708
+ host: parsed.host,
1709
+ "x-amz-date": amzDate,
1710
+ "x-amz-content-sha256": payloadHash,
1711
+ ...reqOpts.headers
1712
+ };
1713
+ const canonicalQuery = Object.keys(query).toSorted().map((name) => `${s3Encode(name)}=${s3Encode(query[name])}`).join("&");
1714
+ const authorization = signV4({
1715
+ method: reqOpts.method,
1716
+ canonicalUri: parsed.pathname,
1717
+ canonicalQuery,
1718
+ headers,
1719
+ payloadHash,
1720
+ amzDate,
1721
+ dateStamp,
1722
+ region,
1723
+ accessKey: options.accessKey,
1724
+ secretKey: options.secretKey
1725
+ });
1726
+ const hasBody = reqOpts.method === "PUT";
1727
+ return fetch(url, {
1728
+ method: reqOpts.method,
1729
+ headers: { ...headers, Authorization: authorization },
1730
+ ...hasBody ? { body } : {}
1731
+ });
1732
+ };
1733
+ const metaFromResponse = (path, res) => {
1734
+ const contentType = res.headers.get("content-type") ?? void 0;
1735
+ return {
1736
+ path,
1737
+ size: Number(res.headers.get("content-length") ?? 0),
1738
+ visibility: res.headers.get("x-amz-meta-visibility") === "public" ? "public" : "private",
1739
+ updatedAt: isoFromHttpDate(res.headers.get("last-modified")),
1740
+ ...contentType === void 0 || contentType.length === 0 ? {} : { contentType }
1741
+ };
1742
+ };
1743
+ let bucketReady = false;
1744
+ const ensureBucket = async () => {
1745
+ if (bucketReady) return;
1746
+ const head = await request({ method: "HEAD" });
1747
+ if (head.ok || head.status === 403) {
1748
+ bucketReady = true;
1749
+ return;
1750
+ }
1751
+ if (head.status === 404) {
1752
+ const create = await request({ method: "PUT" });
1753
+ if (create.ok || create.status === 409) {
1754
+ bucketReady = true;
1755
+ return;
1756
+ }
1757
+ await mapError(create, `\u521B\u5EFA\u6876 "${bucket}" \u5931\u8D25`);
1758
+ }
1759
+ await mapError(head, `\u6876 "${bucket}" \u4E0D\u53EF\u8BBF\u95EE`);
1760
+ };
1761
+ const headMeta = async (projectId, path) => {
1762
+ const res = await request({ method: "HEAD", objectKey: objectKey(projectId, path) });
1763
+ if (!res.ok) await mapError(res, `\u6587\u4EF6 "${path}" \u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u8BFB`);
1764
+ return metaFromResponse(path, res);
1765
+ };
1766
+ const listAllKeys = async (prefix) => {
1767
+ const out = [];
1768
+ let token;
1769
+ for (; ; ) {
1770
+ const query = { "list-type": "2", prefix };
1771
+ if (token !== void 0) query["continuation-token"] = token;
1772
+ const res = await request({ method: "GET", query });
1773
+ if (!res.ok) await mapError(res, `\u5217\u4E3E\u5BF9\u8C61 "${prefix}" \u5931\u8D25`);
1774
+ const xml = await res.text();
1775
+ const page = parseListXml(xml);
1776
+ out.push(...page.keys);
1777
+ if (!page.truncated || page.nextToken === void 0) break;
1778
+ token = page.nextToken;
1779
+ if (out.length > LIST_PAGE_LIMIT * 10) {
1780
+ throw new StorageError(
1781
+ 502,
1782
+ "STORAGE_BACKEND_ERROR",
1783
+ "\u5BF9\u8C61\u5217\u8868\u5206\u9875\u5F02\u5E38\uFF08\u8D85\u8FC7 10000 \u6761\u4ECD\u622A\u65AD\uFF09"
1784
+ );
1785
+ }
1786
+ }
1787
+ return out;
1788
+ };
1789
+ const usageOf = async (projectId) => {
1790
+ const keys = await listAllKeys(projectPrefix(projectId));
1791
+ return keys.reduce((total, entry) => total + entry.size, 0);
1792
+ };
1793
+ return {
1794
+ async put(projectId, path, data, putOptions) {
1795
+ assertSafeStoragePath(path);
1796
+ if (!(data instanceof Uint8Array)) {
1797
+ throw new StorageError(400, "STORAGE_INVALID_PAYLOAD", "\u5199\u5165\u5185\u5BB9\u5FC5\u987B\u662F\u5B57\u8282\u6570\u7EC4");
1798
+ }
1799
+ await ensureBucket();
1800
+ const used = await usageOf(projectId);
1801
+ let existingSize = 0;
1802
+ try {
1803
+ existingSize = (await headMeta(projectId, path)).size;
1804
+ } catch {
1805
+ existingSize = 0;
1806
+ }
1807
+ const projected = used - existingSize + data.byteLength;
1808
+ if (options.quotaCheck !== void 0) {
1809
+ await options.quotaCheck(projectId, projected);
1810
+ } else if (projected > quotaBytes) {
1811
+ throw new StorageError(
1812
+ 413,
1813
+ STORAGE_CODES.quotaExceeded,
1814
+ `\u9879\u76EE\u5B58\u50A8\u7A7A\u95F4\u4E0D\u8DB3\uFF1A\u914D\u989D ${quotaBytes} \u5B57\u8282\u5DF2\u7528\u5C3D\uFF08STORAGE_QUOTA_EXCEEDED\uFF09`
1815
+ );
1816
+ }
1817
+ const res = await request({
1818
+ method: "PUT",
1819
+ objectKey: objectKey(projectId, path),
1820
+ headers: {
1821
+ "content-type": putOptions.contentType ?? "application/octet-stream",
1822
+ "x-amz-meta-visibility": putOptions.visibility
1823
+ },
1824
+ body: data
1825
+ });
1826
+ if (!res.ok) await mapError(res, `\u4E0A\u4F20\u6587\u4EF6 "${path}" \u5931\u8D25`);
1827
+ return headMeta(projectId, path);
1828
+ },
1829
+ async get(projectId, path) {
1830
+ assertSafeStoragePath(path);
1831
+ const res = await request({ method: "GET", objectKey: objectKey(projectId, path) });
1832
+ if (!res.ok) await mapError(res, `\u6587\u4EF6 "${path}" \u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u8BFB`);
1833
+ const data = new Uint8Array(await res.arrayBuffer());
1834
+ const meta = metaFromResponse(path, res);
1835
+ return { data, meta };
1836
+ },
1837
+ async getMeta(projectId, path) {
1838
+ assertSafeStoragePath(path);
1839
+ return headMeta(projectId, path);
1840
+ },
1841
+ async remove(projectId, path) {
1842
+ assertSafeStoragePath(path);
1843
+ const res = await request({ method: "DELETE", objectKey: objectKey(projectId, path) });
1844
+ if (!res.ok) await mapError(res, `\u6587\u4EF6 "${path}" \u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u5220\u9664`);
1845
+ },
1846
+ async list(projectId, prefix) {
1847
+ const normalized = assertPrefix(prefix);
1848
+ const keys = await listAllKeys(`${projectId}/${normalized}`);
1849
+ const metas = await mapLimit(keys, HEAD_CONCURRENCY, async (entry) => {
1850
+ const path = entry.key.slice(projectId.length + 1);
1851
+ try {
1852
+ const meta = await headMeta(projectId, path);
1853
+ return { ...meta, size: meta.size, updatedAt: meta.updatedAt };
1854
+ } catch {
1855
+ return null;
1856
+ }
1857
+ });
1858
+ return metas.filter((meta) => meta !== null).toSorted((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
1859
+ },
1860
+ async usage(projectId) {
1861
+ return usageOf(projectId);
1862
+ }
1863
+ };
1864
+ }
1865
+
1548
1866
  // packages/runtime/src/sim/sql-engine.ts
1549
1867
  var SimDbError = class extends Error {
1550
1868
  constructor(code, message) {
@@ -2120,6 +2438,7 @@ export {
2120
2438
  createCloudDb,
2121
2439
  createDbCapability,
2122
2440
  createLocalStorageDriver,
2441
+ createS3StorageDriver,
2123
2442
  createSimRealtimeCapability,
2124
2443
  createStorageCapability,
2125
2444
  hmacSha256,
@@ -0,0 +1,16 @@
1
+ import type { StorageDriver } from '../driver';
2
+ export interface S3StorageOptions {
3
+ /** S3/MinIO endpoint,如 `http://minio:9000`(zod: url)。不支持路径前缀的 URL。 */
4
+ endpoint: string;
5
+ accessKey: string;
6
+ secretKey: string;
7
+ /** 桶名(对象键前缀 = `{projectId}/{path}`)。 */
8
+ bucket: string;
9
+ /** SigV4 region;MinIO 默认 us-east-1。 */
10
+ region?: string;
11
+ /** 项目配额字节;缺省 1GiB(PRD §2.4)。 */
12
+ quotaBytes?: number;
13
+ /** BILL-005:项目级配额回调(billing 域注入)。 */
14
+ quotaCheck?: (projectId: string, projectedBytes: number) => Promise<void>;
15
+ }
16
+ export declare function createS3StorageDriver(options: S3StorageOptions): StorageDriver;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adep/runtime",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -21,7 +21,7 @@
21
21
  "dist"
22
22
  ],
23
23
  "dependencies": {
24
- "@adep/types": "0.1.1"
24
+ "@adep/types": "0.1.4"
25
25
  },
26
26
  "scripts": {
27
27
  "test": "vitest run",