This commit is contained in:
+547
@@ -0,0 +1,547 @@
|
||||
'use strict';
|
||||
|
||||
const destr = require('destr');
|
||||
const utils = require('./shared/unstorage.D3XyewAC.cjs');
|
||||
|
||||
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
|
||||
|
||||
const destr__default = /*#__PURE__*/_interopDefaultCompat(destr);
|
||||
|
||||
function defineDriver(factory) {
|
||||
return factory;
|
||||
}
|
||||
|
||||
const DRIVER_NAME = "memory";
|
||||
const memory = defineDriver(() => {
|
||||
const data = /* @__PURE__ */ new Map();
|
||||
return {
|
||||
name: DRIVER_NAME,
|
||||
getInstance: () => data,
|
||||
hasItem(key) {
|
||||
return data.has(key);
|
||||
},
|
||||
getItem(key) {
|
||||
return data.get(key) ?? null;
|
||||
},
|
||||
getItemRaw(key) {
|
||||
return data.get(key) ?? null;
|
||||
},
|
||||
setItem(key, value) {
|
||||
data.set(key, value);
|
||||
},
|
||||
setItemRaw(key, value) {
|
||||
data.set(key, value);
|
||||
},
|
||||
removeItem(key) {
|
||||
data.delete(key);
|
||||
},
|
||||
getKeys() {
|
||||
return [...data.keys()];
|
||||
},
|
||||
clear() {
|
||||
data.clear();
|
||||
},
|
||||
dispose() {
|
||||
data.clear();
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
function createStorage(options = {}) {
|
||||
const context = {
|
||||
mounts: { "": options.driver || memory() },
|
||||
mountpoints: [""],
|
||||
watching: false,
|
||||
watchListeners: [],
|
||||
unwatch: {}
|
||||
};
|
||||
const normalizeItemKey = (key) => {
|
||||
const normalizedKey = utils.normalizeKey(key);
|
||||
if (!normalizedKey || utils.hasDotSegment(normalizedKey)) {
|
||||
throw new Error(`[unstorage] Invalid key: ${JSON.stringify(key)}`);
|
||||
}
|
||||
return normalizedKey;
|
||||
};
|
||||
const normalizeBase = (base) => {
|
||||
const normalizedBase = utils.normalizeBaseKey(base);
|
||||
if (utils.hasDotSegment(normalizedBase)) {
|
||||
throw new Error(`[unstorage] Invalid base: ${JSON.stringify(base)}`);
|
||||
}
|
||||
return normalizedBase;
|
||||
};
|
||||
const getMount = (key) => {
|
||||
for (const base of context.mountpoints) {
|
||||
if (key.startsWith(base)) {
|
||||
return {
|
||||
base,
|
||||
relativeKey: key.slice(base.length),
|
||||
driver: context.mounts[base]
|
||||
};
|
||||
}
|
||||
}
|
||||
return {
|
||||
base: "",
|
||||
relativeKey: key,
|
||||
driver: context.mounts[""]
|
||||
};
|
||||
};
|
||||
const getMounts = (base, includeParent) => {
|
||||
return context.mountpoints.filter(
|
||||
(mountpoint) => mountpoint.startsWith(base) || includeParent && base.startsWith(mountpoint)
|
||||
).map((mountpoint) => ({
|
||||
relativeBase: base.length > mountpoint.length ? base.slice(mountpoint.length) : void 0,
|
||||
mountpoint,
|
||||
driver: context.mounts[mountpoint]
|
||||
}));
|
||||
};
|
||||
const onChange = (event, key) => {
|
||||
if (!context.watching) {
|
||||
return;
|
||||
}
|
||||
key = utils.normalizeKey(key);
|
||||
for (const listener of context.watchListeners) {
|
||||
listener(event, key);
|
||||
}
|
||||
};
|
||||
const startWatch = async () => {
|
||||
if (context.watching) {
|
||||
return;
|
||||
}
|
||||
context.watching = true;
|
||||
for (const mountpoint in context.mounts) {
|
||||
context.unwatch[mountpoint] = await watch(
|
||||
context.mounts[mountpoint],
|
||||
onChange,
|
||||
mountpoint
|
||||
);
|
||||
}
|
||||
};
|
||||
const stopWatch = async () => {
|
||||
if (!context.watching) {
|
||||
return;
|
||||
}
|
||||
for (const mountpoint in context.unwatch) {
|
||||
await context.unwatch[mountpoint]();
|
||||
}
|
||||
context.unwatch = {};
|
||||
context.watching = false;
|
||||
};
|
||||
const runBatch = (items, commonOptions, cb) => {
|
||||
const batches = /* @__PURE__ */ new Map();
|
||||
const getBatch = (mount) => {
|
||||
let batch = batches.get(mount.base);
|
||||
if (!batch) {
|
||||
batch = {
|
||||
driver: mount.driver,
|
||||
base: mount.base,
|
||||
items: []
|
||||
};
|
||||
batches.set(mount.base, batch);
|
||||
}
|
||||
return batch;
|
||||
};
|
||||
for (const item of items) {
|
||||
const isStringItem = typeof item === "string";
|
||||
const key = normalizeItemKey(isStringItem ? item : item.key);
|
||||
const value = isStringItem ? void 0 : item.value;
|
||||
const options2 = isStringItem || !item.options ? commonOptions : { ...commonOptions, ...item.options };
|
||||
const mount = getMount(key);
|
||||
getBatch(mount).items.push({
|
||||
key,
|
||||
value,
|
||||
relativeKey: mount.relativeKey,
|
||||
options: options2
|
||||
});
|
||||
}
|
||||
return Promise.all([...batches.values()].map((batch) => cb(batch))).then(
|
||||
(r) => r.flat()
|
||||
);
|
||||
};
|
||||
const storage = {
|
||||
// Item
|
||||
async hasItem(key, opts = {}) {
|
||||
key = normalizeItemKey(key);
|
||||
const { relativeKey, driver } = getMount(key);
|
||||
return utils.asyncCall(driver.hasItem, relativeKey, opts);
|
||||
},
|
||||
async getItem(key, opts = {}) {
|
||||
key = normalizeItemKey(key);
|
||||
const { relativeKey, driver } = getMount(key);
|
||||
return utils.asyncCall(driver.getItem, relativeKey, opts).then(
|
||||
(value) => destr__default(value)
|
||||
);
|
||||
},
|
||||
async getItems(items, commonOptions = {}) {
|
||||
return runBatch(items, commonOptions, (batch) => {
|
||||
if (batch.driver.getItems) {
|
||||
return utils.asyncCall(
|
||||
batch.driver.getItems,
|
||||
batch.items.map((item) => ({
|
||||
key: item.relativeKey,
|
||||
options: item.options
|
||||
})),
|
||||
commonOptions
|
||||
).then(
|
||||
(r) => r.map((item) => ({
|
||||
key: utils.joinKeys(batch.base, item.key),
|
||||
value: destr__default(item.value)
|
||||
}))
|
||||
);
|
||||
}
|
||||
return Promise.all(
|
||||
batch.items.map((item) => {
|
||||
return utils.asyncCall(
|
||||
batch.driver.getItem,
|
||||
item.relativeKey,
|
||||
item.options
|
||||
).then((value) => ({
|
||||
key: item.key,
|
||||
value: destr__default(value)
|
||||
}));
|
||||
})
|
||||
);
|
||||
});
|
||||
},
|
||||
async getItemRaw(key, opts = {}) {
|
||||
key = normalizeItemKey(key);
|
||||
const { relativeKey, driver } = getMount(key);
|
||||
if (driver.getItemRaw) {
|
||||
return utils.asyncCall(driver.getItemRaw, relativeKey, opts);
|
||||
}
|
||||
return utils.asyncCall(driver.getItem, relativeKey, opts).then(
|
||||
(value) => utils.deserializeRaw(value)
|
||||
);
|
||||
},
|
||||
async setItem(key, value, opts = {}) {
|
||||
if (value === void 0) {
|
||||
return storage.removeItem(key);
|
||||
}
|
||||
key = normalizeItemKey(key);
|
||||
const { relativeKey, driver } = getMount(key);
|
||||
if (!driver.setItem) {
|
||||
return;
|
||||
}
|
||||
await utils.asyncCall(driver.setItem, relativeKey, utils.stringify(value), opts);
|
||||
if (!driver.watch) {
|
||||
onChange("update", key);
|
||||
}
|
||||
},
|
||||
async setItems(items, commonOptions) {
|
||||
await runBatch(items, commonOptions, async (batch) => {
|
||||
if (batch.driver.setItems) {
|
||||
return utils.asyncCall(
|
||||
batch.driver.setItems,
|
||||
batch.items.map((item) => ({
|
||||
key: item.relativeKey,
|
||||
value: utils.stringify(item.value),
|
||||
options: item.options
|
||||
})),
|
||||
commonOptions
|
||||
);
|
||||
}
|
||||
if (!batch.driver.setItem) {
|
||||
return;
|
||||
}
|
||||
await Promise.all(
|
||||
batch.items.map((item) => {
|
||||
return utils.asyncCall(
|
||||
batch.driver.setItem,
|
||||
item.relativeKey,
|
||||
utils.stringify(item.value),
|
||||
item.options
|
||||
);
|
||||
})
|
||||
);
|
||||
});
|
||||
},
|
||||
async setItemRaw(key, value, opts = {}) {
|
||||
if (value === void 0) {
|
||||
return storage.removeItem(key, opts);
|
||||
}
|
||||
key = normalizeItemKey(key);
|
||||
const { relativeKey, driver } = getMount(key);
|
||||
if (driver.setItemRaw) {
|
||||
await utils.asyncCall(driver.setItemRaw, relativeKey, value, opts);
|
||||
} else if (driver.setItem) {
|
||||
await utils.asyncCall(driver.setItem, relativeKey, utils.serializeRaw(value), opts);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
if (!driver.watch) {
|
||||
onChange("update", key);
|
||||
}
|
||||
},
|
||||
async removeItem(key, opts = {}) {
|
||||
if (typeof opts === "boolean") {
|
||||
opts = { removeMeta: opts };
|
||||
}
|
||||
key = normalizeItemKey(key);
|
||||
const { relativeKey, driver } = getMount(key);
|
||||
if (!driver.removeItem) {
|
||||
return;
|
||||
}
|
||||
await utils.asyncCall(driver.removeItem, relativeKey, opts);
|
||||
if (opts.removeMeta || opts.removeMata) {
|
||||
await utils.asyncCall(driver.removeItem, relativeKey + "$", opts);
|
||||
}
|
||||
if (!driver.watch) {
|
||||
onChange("remove", key);
|
||||
}
|
||||
},
|
||||
// Meta
|
||||
async getMeta(key, opts = {}) {
|
||||
if (typeof opts === "boolean") {
|
||||
opts = { nativeOnly: opts };
|
||||
}
|
||||
key = normalizeItemKey(key);
|
||||
const { relativeKey, driver } = getMount(key);
|
||||
const meta = /* @__PURE__ */ Object.create(null);
|
||||
if (driver.getMeta) {
|
||||
Object.assign(meta, await utils.asyncCall(driver.getMeta, relativeKey, opts));
|
||||
}
|
||||
if (!opts.nativeOnly) {
|
||||
const value = await utils.asyncCall(
|
||||
driver.getItem,
|
||||
relativeKey + "$",
|
||||
opts
|
||||
).then((value_) => destr__default(value_));
|
||||
if (value && typeof value === "object") {
|
||||
if (typeof value.atime === "string") {
|
||||
value.atime = new Date(value.atime);
|
||||
}
|
||||
if (typeof value.mtime === "string") {
|
||||
value.mtime = new Date(value.mtime);
|
||||
}
|
||||
Object.assign(meta, value);
|
||||
}
|
||||
}
|
||||
return meta;
|
||||
},
|
||||
async setMeta(key, value, opts = {}) {
|
||||
return this.setItem(normalizeItemKey(key) + "$", value, opts);
|
||||
},
|
||||
async removeMeta(key, opts = {}) {
|
||||
return this.removeItem(normalizeItemKey(key) + "$", opts);
|
||||
},
|
||||
// Keys
|
||||
async getKeys(base, opts = {}) {
|
||||
base = normalizeBase(base);
|
||||
const mounts = getMounts(base, true);
|
||||
let maskedMounts = [];
|
||||
const allKeys = [];
|
||||
let allMountsSupportMaxDepth = true;
|
||||
for (const mount of mounts) {
|
||||
if (!mount.driver.flags?.maxDepth) {
|
||||
allMountsSupportMaxDepth = false;
|
||||
}
|
||||
const rawKeys = await utils.asyncCall(
|
||||
mount.driver.getKeys,
|
||||
mount.relativeBase,
|
||||
opts
|
||||
);
|
||||
for (const key of rawKeys) {
|
||||
const fullKey = mount.mountpoint + utils.normalizeKey(key);
|
||||
if (!maskedMounts.some((p) => fullKey.startsWith(p))) {
|
||||
allKeys.push(fullKey);
|
||||
}
|
||||
}
|
||||
maskedMounts = [
|
||||
mount.mountpoint,
|
||||
...maskedMounts.filter((p) => !p.startsWith(mount.mountpoint))
|
||||
];
|
||||
}
|
||||
const shouldFilterByDepth = opts.maxDepth !== void 0 && !allMountsSupportMaxDepth;
|
||||
return allKeys.filter(
|
||||
(key) => (!shouldFilterByDepth || utils.filterKeyByDepth(key, opts.maxDepth)) && utils.filterKeyByBase(key, base)
|
||||
);
|
||||
},
|
||||
// Utils
|
||||
async clear(base, opts = {}) {
|
||||
base = normalizeBase(base);
|
||||
await Promise.all(
|
||||
getMounts(base, false).map(async (m) => {
|
||||
if (m.driver.clear) {
|
||||
return utils.asyncCall(m.driver.clear, m.relativeBase, opts);
|
||||
}
|
||||
if (m.driver.removeItem) {
|
||||
const keys = await m.driver.getKeys(m.relativeBase || "", opts);
|
||||
return Promise.all(
|
||||
keys.map((key) => m.driver.removeItem(key, opts))
|
||||
);
|
||||
}
|
||||
})
|
||||
);
|
||||
},
|
||||
async dispose() {
|
||||
await Promise.all(
|
||||
Object.values(context.mounts).map((driver) => dispose(driver))
|
||||
);
|
||||
},
|
||||
async watch(callback) {
|
||||
await startWatch();
|
||||
context.watchListeners.push(callback);
|
||||
return async () => {
|
||||
context.watchListeners = context.watchListeners.filter(
|
||||
(listener) => listener !== callback
|
||||
);
|
||||
if (context.watchListeners.length === 0) {
|
||||
await stopWatch();
|
||||
}
|
||||
};
|
||||
},
|
||||
async unwatch() {
|
||||
context.watchListeners = [];
|
||||
await stopWatch();
|
||||
},
|
||||
// Mount
|
||||
mount(base, driver) {
|
||||
base = normalizeBase(base);
|
||||
if (base && context.mounts[base]) {
|
||||
throw new Error(`already mounted at ${base}`);
|
||||
}
|
||||
if (base) {
|
||||
context.mountpoints.push(base);
|
||||
context.mountpoints.sort((a, b) => b.length - a.length);
|
||||
}
|
||||
context.mounts[base] = driver;
|
||||
if (context.watching) {
|
||||
Promise.resolve(watch(driver, onChange, base)).then((unwatcher) => {
|
||||
context.unwatch[base] = unwatcher;
|
||||
}).catch(console.error);
|
||||
}
|
||||
return storage;
|
||||
},
|
||||
async unmount(base, _dispose = true) {
|
||||
base = utils.normalizeBaseKey(base);
|
||||
if (!base || !context.mounts[base]) {
|
||||
return;
|
||||
}
|
||||
if (context.watching && base in context.unwatch) {
|
||||
context.unwatch[base]?.();
|
||||
delete context.unwatch[base];
|
||||
}
|
||||
if (_dispose) {
|
||||
await dispose(context.mounts[base]);
|
||||
}
|
||||
context.mountpoints = context.mountpoints.filter((key) => key !== base);
|
||||
delete context.mounts[base];
|
||||
},
|
||||
getMount(key = "") {
|
||||
key = utils.normalizeKey(key) + ":";
|
||||
const m = getMount(key);
|
||||
return {
|
||||
driver: m.driver,
|
||||
base: m.base
|
||||
};
|
||||
},
|
||||
getMounts(base = "", opts = {}) {
|
||||
base = utils.normalizeKey(base);
|
||||
const mounts = getMounts(base, opts.parents);
|
||||
return mounts.map((m) => ({
|
||||
driver: m.driver,
|
||||
base: m.mountpoint
|
||||
}));
|
||||
},
|
||||
// Aliases
|
||||
keys: (base, opts = {}) => storage.getKeys(base, opts),
|
||||
get: (key, opts = {}) => storage.getItem(key, opts),
|
||||
set: (key, value, opts = {}) => storage.setItem(key, value, opts),
|
||||
has: (key, opts = {}) => storage.hasItem(key, opts),
|
||||
del: (key, opts = {}) => storage.removeItem(key, opts),
|
||||
remove: (key, opts = {}) => storage.removeItem(key, opts)
|
||||
};
|
||||
return storage;
|
||||
}
|
||||
async function snapshot(storage, base) {
|
||||
base = utils.normalizeBaseKey(base);
|
||||
const keys = await storage.getKeys(base);
|
||||
const snapshot2 = {};
|
||||
await Promise.all(
|
||||
keys.map(async (key) => {
|
||||
snapshot2[key.slice(base.length)] = await storage.getItem(key);
|
||||
})
|
||||
);
|
||||
return snapshot2;
|
||||
}
|
||||
async function restoreSnapshot(driver, snapshot2, base = "") {
|
||||
base = utils.normalizeBaseKey(base);
|
||||
await Promise.all(
|
||||
Object.entries(snapshot2).map((e) => driver.setItem(base + e[0], e[1]))
|
||||
);
|
||||
}
|
||||
function watch(driver, onChange, base) {
|
||||
return driver.watch ? driver.watch((event, key) => onChange(event, base + key)) : () => {
|
||||
};
|
||||
}
|
||||
async function dispose(driver) {
|
||||
if (typeof driver.dispose === "function") {
|
||||
await utils.asyncCall(driver.dispose);
|
||||
}
|
||||
}
|
||||
|
||||
const builtinDrivers = {
|
||||
"azure-app-configuration": "unstorage/drivers/azure-app-configuration",
|
||||
"azureAppConfiguration": "unstorage/drivers/azure-app-configuration",
|
||||
"azure-cosmos": "unstorage/drivers/azure-cosmos",
|
||||
"azureCosmos": "unstorage/drivers/azure-cosmos",
|
||||
"azure-key-vault": "unstorage/drivers/azure-key-vault",
|
||||
"azureKeyVault": "unstorage/drivers/azure-key-vault",
|
||||
"azure-storage-blob": "unstorage/drivers/azure-storage-blob",
|
||||
"azureStorageBlob": "unstorage/drivers/azure-storage-blob",
|
||||
"azure-storage-table": "unstorage/drivers/azure-storage-table",
|
||||
"azureStorageTable": "unstorage/drivers/azure-storage-table",
|
||||
"capacitor-preferences": "unstorage/drivers/capacitor-preferences",
|
||||
"capacitorPreferences": "unstorage/drivers/capacitor-preferences",
|
||||
"cloudflare-kv-binding": "unstorage/drivers/cloudflare-kv-binding",
|
||||
"cloudflareKVBinding": "unstorage/drivers/cloudflare-kv-binding",
|
||||
"cloudflare-kv-http": "unstorage/drivers/cloudflare-kv-http",
|
||||
"cloudflareKVHttp": "unstorage/drivers/cloudflare-kv-http",
|
||||
"cloudflare-r2-binding": "unstorage/drivers/cloudflare-r2-binding",
|
||||
"cloudflareR2Binding": "unstorage/drivers/cloudflare-r2-binding",
|
||||
"db0": "unstorage/drivers/db0",
|
||||
"deno-kv-node": "unstorage/drivers/deno-kv-node",
|
||||
"denoKVNode": "unstorage/drivers/deno-kv-node",
|
||||
"deno-kv": "unstorage/drivers/deno-kv",
|
||||
"denoKV": "unstorage/drivers/deno-kv",
|
||||
"fs-lite": "unstorage/drivers/fs-lite",
|
||||
"fsLite": "unstorage/drivers/fs-lite",
|
||||
"fs": "unstorage/drivers/fs",
|
||||
"github": "unstorage/drivers/github",
|
||||
"http": "unstorage/drivers/http",
|
||||
"indexedb": "unstorage/drivers/indexedb",
|
||||
"localstorage": "unstorage/drivers/localstorage",
|
||||
"lru-cache": "unstorage/drivers/lru-cache",
|
||||
"lruCache": "unstorage/drivers/lru-cache",
|
||||
"memory": "unstorage/drivers/memory",
|
||||
"mongodb": "unstorage/drivers/mongodb",
|
||||
"netlify-blobs": "unstorage/drivers/netlify-blobs",
|
||||
"netlifyBlobs": "unstorage/drivers/netlify-blobs",
|
||||
"null": "unstorage/drivers/null",
|
||||
"overlay": "unstorage/drivers/overlay",
|
||||
"planetscale": "unstorage/drivers/planetscale",
|
||||
"redis": "unstorage/drivers/redis",
|
||||
"s3": "unstorage/drivers/s3",
|
||||
"session-storage": "unstorage/drivers/session-storage",
|
||||
"sessionStorage": "unstorage/drivers/session-storage",
|
||||
"uploadthing": "unstorage/drivers/uploadthing",
|
||||
"upstash": "unstorage/drivers/upstash",
|
||||
"vercel-blob": "unstorage/drivers/vercel-blob",
|
||||
"vercelBlob": "unstorage/drivers/vercel-blob",
|
||||
"vercel-kv": "unstorage/drivers/vercel-kv",
|
||||
"vercelKV": "unstorage/drivers/vercel-kv",
|
||||
"vercel-runtime-cache": "unstorage/drivers/vercel-runtime-cache",
|
||||
"vercelRuntimeCache": "unstorage/drivers/vercel-runtime-cache"
|
||||
};
|
||||
|
||||
exports.filterKeyByBase = utils.filterKeyByBase;
|
||||
exports.filterKeyByDepth = utils.filterKeyByDepth;
|
||||
exports.hasDotSegment = utils.hasDotSegment;
|
||||
exports.joinKeys = utils.joinKeys;
|
||||
exports.normalizeBaseKey = utils.normalizeBaseKey;
|
||||
exports.normalizeKey = utils.normalizeKey;
|
||||
exports.prefixStorage = utils.prefixStorage;
|
||||
exports.builtinDrivers = builtinDrivers;
|
||||
exports.createStorage = createStorage;
|
||||
exports.defineDriver = defineDriver;
|
||||
exports.restoreSnapshot = restoreSnapshot;
|
||||
exports.snapshot = snapshot;
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
import { D as Driver, S as StorageValue, a as Storage } from './shared/unstorage.DqlWKU2I.cjs';
|
||||
export { b as DriverFlags, G as GetKeysOptions, c as StorageMeta, T as TransactionOptions, U as Unwatch, W as WatchCallback, d as WatchEvent } from './shared/unstorage.DqlWKU2I.cjs';
|
||||
import { AzureAppConfigurationOptions } from 'unstorage/drivers/azure-app-configuration';
|
||||
import { AzureCosmosOptions } from 'unstorage/drivers/azure-cosmos';
|
||||
import { AzureKeyVaultOptions } from 'unstorage/drivers/azure-key-vault';
|
||||
import { AzureStorageBlobOptions } from 'unstorage/drivers/azure-storage-blob';
|
||||
import { AzureStorageTableOptions } from 'unstorage/drivers/azure-storage-table';
|
||||
import { CapacitorPreferencesOptions } from 'unstorage/drivers/capacitor-preferences';
|
||||
import { KVOptions } from 'unstorage/drivers/cloudflare-kv-binding';
|
||||
import { KVHTTPOptions } from 'unstorage/drivers/cloudflare-kv-http';
|
||||
import { CloudflareR2Options } from 'unstorage/drivers/cloudflare-r2-binding';
|
||||
import { DB0DriverOptions } from 'unstorage/drivers/db0';
|
||||
import { DenoKvNodeOptions } from 'unstorage/drivers/deno-kv-node';
|
||||
import { DenoKvOptions } from 'unstorage/drivers/deno-kv';
|
||||
import { FSStorageOptions } from 'unstorage/drivers/fs-lite';
|
||||
import { FSStorageOptions as FSStorageOptions$1 } from 'unstorage/drivers/fs';
|
||||
import { GithubOptions } from 'unstorage/drivers/github';
|
||||
import { HTTPOptions } from 'unstorage/drivers/http';
|
||||
import { IDBKeyvalOptions } from 'unstorage/drivers/indexedb';
|
||||
import { LocalStorageOptions } from 'unstorage/drivers/localstorage';
|
||||
import { LRUDriverOptions } from 'unstorage/drivers/lru-cache';
|
||||
import { MongoDbOptions } from 'unstorage/drivers/mongodb';
|
||||
import { NetlifyStoreOptions } from 'unstorage/drivers/netlify-blobs';
|
||||
import { OverlayStorageOptions } from 'unstorage/drivers/overlay';
|
||||
import { PlanetscaleDriverOptions } from 'unstorage/drivers/planetscale';
|
||||
import { RedisOptions } from 'unstorage/drivers/redis';
|
||||
import { S3DriverOptions } from 'unstorage/drivers/s3';
|
||||
import { SessionStorageOptions } from 'unstorage/drivers/session-storage';
|
||||
import { UploadThingOptions } from 'unstorage/drivers/uploadthing';
|
||||
import { UpstashOptions } from 'unstorage/drivers/upstash';
|
||||
import { VercelBlobOptions } from 'unstorage/drivers/vercel-blob';
|
||||
import { VercelKVOptions } from 'unstorage/drivers/vercel-kv';
|
||||
import { VercelCacheOptions } from 'unstorage/drivers/vercel-runtime-cache';
|
||||
|
||||
interface CreateStorageOptions {
|
||||
driver?: Driver;
|
||||
}
|
||||
declare function createStorage<T extends StorageValue>(options?: CreateStorageOptions): Storage<T>;
|
||||
type Snapshot<T = string> = Record<string, T>;
|
||||
declare function snapshot(storage: Storage, base: string): Promise<Snapshot<string>>;
|
||||
declare function restoreSnapshot(driver: Storage, snapshot: Snapshot<StorageValue>, base?: string): Promise<void>;
|
||||
|
||||
declare function prefixStorage<T extends StorageValue>(storage: Storage<T> | Storage<any>, base: string): Storage<T>;
|
||||
declare function normalizeKey(key?: string): string;
|
||||
/**
|
||||
* Check if a normalized key has `.` or `..` segments, which drivers mapping
|
||||
* keys to paths or URLs would resolve (and could escape their base with)
|
||||
*/
|
||||
declare function hasDotSegment(key: string): boolean;
|
||||
declare function joinKeys(...keys: string[]): string;
|
||||
declare function normalizeBaseKey(base?: string): string;
|
||||
declare function filterKeyByDepth(key: string, depth: number | undefined): boolean;
|
||||
declare function filterKeyByBase(key: string, base: string | undefined): boolean;
|
||||
|
||||
type DriverFactory<OptionsT, InstanceT> = (opts: OptionsT) => Driver<OptionsT, InstanceT>;
|
||||
declare function defineDriver<OptionsT = any, InstanceT = never>(factory: DriverFactory<OptionsT, InstanceT>): DriverFactory<OptionsT, InstanceT>;
|
||||
|
||||
type BuiltinDriverName = "azure-app-configuration" | "azureAppConfiguration" | "azure-cosmos" | "azureCosmos" | "azure-key-vault" | "azureKeyVault" | "azure-storage-blob" | "azureStorageBlob" | "azure-storage-table" | "azureStorageTable" | "capacitor-preferences" | "capacitorPreferences" | "cloudflare-kv-binding" | "cloudflareKVBinding" | "cloudflare-kv-http" | "cloudflareKVHttp" | "cloudflare-r2-binding" | "cloudflareR2Binding" | "db0" | "deno-kv-node" | "denoKVNode" | "deno-kv" | "denoKV" | "fs-lite" | "fsLite" | "fs" | "github" | "http" | "indexedb" | "localstorage" | "lru-cache" | "lruCache" | "memory" | "mongodb" | "netlify-blobs" | "netlifyBlobs" | "null" | "overlay" | "planetscale" | "redis" | "s3" | "session-storage" | "sessionStorage" | "uploadthing" | "upstash" | "vercel-blob" | "vercelBlob" | "vercel-kv" | "vercelKV" | "vercel-runtime-cache" | "vercelRuntimeCache";
|
||||
type BuiltinDriverOptions = {
|
||||
"azure-app-configuration": AzureAppConfigurationOptions;
|
||||
"azureAppConfiguration": AzureAppConfigurationOptions;
|
||||
"azure-cosmos": AzureCosmosOptions;
|
||||
"azureCosmos": AzureCosmosOptions;
|
||||
"azure-key-vault": AzureKeyVaultOptions;
|
||||
"azureKeyVault": AzureKeyVaultOptions;
|
||||
"azure-storage-blob": AzureStorageBlobOptions;
|
||||
"azureStorageBlob": AzureStorageBlobOptions;
|
||||
"azure-storage-table": AzureStorageTableOptions;
|
||||
"azureStorageTable": AzureStorageTableOptions;
|
||||
"capacitor-preferences": CapacitorPreferencesOptions;
|
||||
"capacitorPreferences": CapacitorPreferencesOptions;
|
||||
"cloudflare-kv-binding": KVOptions;
|
||||
"cloudflareKVBinding": KVOptions;
|
||||
"cloudflare-kv-http": KVHTTPOptions;
|
||||
"cloudflareKVHttp": KVHTTPOptions;
|
||||
"cloudflare-r2-binding": CloudflareR2Options;
|
||||
"cloudflareR2Binding": CloudflareR2Options;
|
||||
"db0": DB0DriverOptions;
|
||||
"deno-kv-node": DenoKvNodeOptions;
|
||||
"denoKVNode": DenoKvNodeOptions;
|
||||
"deno-kv": DenoKvOptions;
|
||||
"denoKV": DenoKvOptions;
|
||||
"fs-lite": FSStorageOptions;
|
||||
"fsLite": FSStorageOptions;
|
||||
"fs": FSStorageOptions$1;
|
||||
"github": GithubOptions;
|
||||
"http": HTTPOptions;
|
||||
"indexedb": IDBKeyvalOptions;
|
||||
"localstorage": LocalStorageOptions;
|
||||
"lru-cache": LRUDriverOptions;
|
||||
"lruCache": LRUDriverOptions;
|
||||
"mongodb": MongoDbOptions;
|
||||
"netlify-blobs": NetlifyStoreOptions;
|
||||
"netlifyBlobs": NetlifyStoreOptions;
|
||||
"overlay": OverlayStorageOptions;
|
||||
"planetscale": PlanetscaleDriverOptions;
|
||||
"redis": RedisOptions;
|
||||
"s3": S3DriverOptions;
|
||||
"session-storage": SessionStorageOptions;
|
||||
"sessionStorage": SessionStorageOptions;
|
||||
"uploadthing": UploadThingOptions;
|
||||
"upstash": UpstashOptions;
|
||||
"vercel-blob": VercelBlobOptions;
|
||||
"vercelBlob": VercelBlobOptions;
|
||||
"vercel-kv": VercelKVOptions;
|
||||
"vercelKV": VercelKVOptions;
|
||||
"vercel-runtime-cache": VercelCacheOptions;
|
||||
"vercelRuntimeCache": VercelCacheOptions;
|
||||
};
|
||||
declare const builtinDrivers: {
|
||||
readonly "azure-app-configuration": "unstorage/drivers/azure-app-configuration";
|
||||
readonly azureAppConfiguration: "unstorage/drivers/azure-app-configuration";
|
||||
readonly "azure-cosmos": "unstorage/drivers/azure-cosmos";
|
||||
readonly azureCosmos: "unstorage/drivers/azure-cosmos";
|
||||
readonly "azure-key-vault": "unstorage/drivers/azure-key-vault";
|
||||
readonly azureKeyVault: "unstorage/drivers/azure-key-vault";
|
||||
readonly "azure-storage-blob": "unstorage/drivers/azure-storage-blob";
|
||||
readonly azureStorageBlob: "unstorage/drivers/azure-storage-blob";
|
||||
readonly "azure-storage-table": "unstorage/drivers/azure-storage-table";
|
||||
readonly azureStorageTable: "unstorage/drivers/azure-storage-table";
|
||||
readonly "capacitor-preferences": "unstorage/drivers/capacitor-preferences";
|
||||
readonly capacitorPreferences: "unstorage/drivers/capacitor-preferences";
|
||||
readonly "cloudflare-kv-binding": "unstorage/drivers/cloudflare-kv-binding";
|
||||
readonly cloudflareKVBinding: "unstorage/drivers/cloudflare-kv-binding";
|
||||
readonly "cloudflare-kv-http": "unstorage/drivers/cloudflare-kv-http";
|
||||
readonly cloudflareKVHttp: "unstorage/drivers/cloudflare-kv-http";
|
||||
readonly "cloudflare-r2-binding": "unstorage/drivers/cloudflare-r2-binding";
|
||||
readonly cloudflareR2Binding: "unstorage/drivers/cloudflare-r2-binding";
|
||||
readonly db0: "unstorage/drivers/db0";
|
||||
readonly "deno-kv-node": "unstorage/drivers/deno-kv-node";
|
||||
readonly denoKVNode: "unstorage/drivers/deno-kv-node";
|
||||
readonly "deno-kv": "unstorage/drivers/deno-kv";
|
||||
readonly denoKV: "unstorage/drivers/deno-kv";
|
||||
readonly "fs-lite": "unstorage/drivers/fs-lite";
|
||||
readonly fsLite: "unstorage/drivers/fs-lite";
|
||||
readonly fs: "unstorage/drivers/fs";
|
||||
readonly github: "unstorage/drivers/github";
|
||||
readonly http: "unstorage/drivers/http";
|
||||
readonly indexedb: "unstorage/drivers/indexedb";
|
||||
readonly localstorage: "unstorage/drivers/localstorage";
|
||||
readonly "lru-cache": "unstorage/drivers/lru-cache";
|
||||
readonly lruCache: "unstorage/drivers/lru-cache";
|
||||
readonly memory: "unstorage/drivers/memory";
|
||||
readonly mongodb: "unstorage/drivers/mongodb";
|
||||
readonly "netlify-blobs": "unstorage/drivers/netlify-blobs";
|
||||
readonly netlifyBlobs: "unstorage/drivers/netlify-blobs";
|
||||
readonly null: "unstorage/drivers/null";
|
||||
readonly overlay: "unstorage/drivers/overlay";
|
||||
readonly planetscale: "unstorage/drivers/planetscale";
|
||||
readonly redis: "unstorage/drivers/redis";
|
||||
readonly s3: "unstorage/drivers/s3";
|
||||
readonly "session-storage": "unstorage/drivers/session-storage";
|
||||
readonly sessionStorage: "unstorage/drivers/session-storage";
|
||||
readonly uploadthing: "unstorage/drivers/uploadthing";
|
||||
readonly upstash: "unstorage/drivers/upstash";
|
||||
readonly "vercel-blob": "unstorage/drivers/vercel-blob";
|
||||
readonly vercelBlob: "unstorage/drivers/vercel-blob";
|
||||
readonly "vercel-kv": "unstorage/drivers/vercel-kv";
|
||||
readonly vercelKV: "unstorage/drivers/vercel-kv";
|
||||
readonly "vercel-runtime-cache": "unstorage/drivers/vercel-runtime-cache";
|
||||
readonly vercelRuntimeCache: "unstorage/drivers/vercel-runtime-cache";
|
||||
};
|
||||
|
||||
export { Driver, Storage, StorageValue, builtinDrivers, createStorage, defineDriver, filterKeyByBase, filterKeyByDepth, hasDotSegment, joinKeys, normalizeBaseKey, normalizeKey, prefixStorage, restoreSnapshot, snapshot };
|
||||
export type { BuiltinDriverName, BuiltinDriverOptions, CreateStorageOptions, Snapshot };
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
import { D as Driver, S as StorageValue, a as Storage } from './shared/unstorage.DqlWKU2I.mjs';
|
||||
export { b as DriverFlags, G as GetKeysOptions, c as StorageMeta, T as TransactionOptions, U as Unwatch, W as WatchCallback, d as WatchEvent } from './shared/unstorage.DqlWKU2I.mjs';
|
||||
import { AzureAppConfigurationOptions } from 'unstorage/drivers/azure-app-configuration';
|
||||
import { AzureCosmosOptions } from 'unstorage/drivers/azure-cosmos';
|
||||
import { AzureKeyVaultOptions } from 'unstorage/drivers/azure-key-vault';
|
||||
import { AzureStorageBlobOptions } from 'unstorage/drivers/azure-storage-blob';
|
||||
import { AzureStorageTableOptions } from 'unstorage/drivers/azure-storage-table';
|
||||
import { CapacitorPreferencesOptions } from 'unstorage/drivers/capacitor-preferences';
|
||||
import { KVOptions } from 'unstorage/drivers/cloudflare-kv-binding';
|
||||
import { KVHTTPOptions } from 'unstorage/drivers/cloudflare-kv-http';
|
||||
import { CloudflareR2Options } from 'unstorage/drivers/cloudflare-r2-binding';
|
||||
import { DB0DriverOptions } from 'unstorage/drivers/db0';
|
||||
import { DenoKvNodeOptions } from 'unstorage/drivers/deno-kv-node';
|
||||
import { DenoKvOptions } from 'unstorage/drivers/deno-kv';
|
||||
import { FSStorageOptions } from 'unstorage/drivers/fs-lite';
|
||||
import { FSStorageOptions as FSStorageOptions$1 } from 'unstorage/drivers/fs';
|
||||
import { GithubOptions } from 'unstorage/drivers/github';
|
||||
import { HTTPOptions } from 'unstorage/drivers/http';
|
||||
import { IDBKeyvalOptions } from 'unstorage/drivers/indexedb';
|
||||
import { LocalStorageOptions } from 'unstorage/drivers/localstorage';
|
||||
import { LRUDriverOptions } from 'unstorage/drivers/lru-cache';
|
||||
import { MongoDbOptions } from 'unstorage/drivers/mongodb';
|
||||
import { NetlifyStoreOptions } from 'unstorage/drivers/netlify-blobs';
|
||||
import { OverlayStorageOptions } from 'unstorage/drivers/overlay';
|
||||
import { PlanetscaleDriverOptions } from 'unstorage/drivers/planetscale';
|
||||
import { RedisOptions } from 'unstorage/drivers/redis';
|
||||
import { S3DriverOptions } from 'unstorage/drivers/s3';
|
||||
import { SessionStorageOptions } from 'unstorage/drivers/session-storage';
|
||||
import { UploadThingOptions } from 'unstorage/drivers/uploadthing';
|
||||
import { UpstashOptions } from 'unstorage/drivers/upstash';
|
||||
import { VercelBlobOptions } from 'unstorage/drivers/vercel-blob';
|
||||
import { VercelKVOptions } from 'unstorage/drivers/vercel-kv';
|
||||
import { VercelCacheOptions } from 'unstorage/drivers/vercel-runtime-cache';
|
||||
|
||||
interface CreateStorageOptions {
|
||||
driver?: Driver;
|
||||
}
|
||||
declare function createStorage<T extends StorageValue>(options?: CreateStorageOptions): Storage<T>;
|
||||
type Snapshot<T = string> = Record<string, T>;
|
||||
declare function snapshot(storage: Storage, base: string): Promise<Snapshot<string>>;
|
||||
declare function restoreSnapshot(driver: Storage, snapshot: Snapshot<StorageValue>, base?: string): Promise<void>;
|
||||
|
||||
declare function prefixStorage<T extends StorageValue>(storage: Storage<T> | Storage<any>, base: string): Storage<T>;
|
||||
declare function normalizeKey(key?: string): string;
|
||||
/**
|
||||
* Check if a normalized key has `.` or `..` segments, which drivers mapping
|
||||
* keys to paths or URLs would resolve (and could escape their base with)
|
||||
*/
|
||||
declare function hasDotSegment(key: string): boolean;
|
||||
declare function joinKeys(...keys: string[]): string;
|
||||
declare function normalizeBaseKey(base?: string): string;
|
||||
declare function filterKeyByDepth(key: string, depth: number | undefined): boolean;
|
||||
declare function filterKeyByBase(key: string, base: string | undefined): boolean;
|
||||
|
||||
type DriverFactory<OptionsT, InstanceT> = (opts: OptionsT) => Driver<OptionsT, InstanceT>;
|
||||
declare function defineDriver<OptionsT = any, InstanceT = never>(factory: DriverFactory<OptionsT, InstanceT>): DriverFactory<OptionsT, InstanceT>;
|
||||
|
||||
type BuiltinDriverName = "azure-app-configuration" | "azureAppConfiguration" | "azure-cosmos" | "azureCosmos" | "azure-key-vault" | "azureKeyVault" | "azure-storage-blob" | "azureStorageBlob" | "azure-storage-table" | "azureStorageTable" | "capacitor-preferences" | "capacitorPreferences" | "cloudflare-kv-binding" | "cloudflareKVBinding" | "cloudflare-kv-http" | "cloudflareKVHttp" | "cloudflare-r2-binding" | "cloudflareR2Binding" | "db0" | "deno-kv-node" | "denoKVNode" | "deno-kv" | "denoKV" | "fs-lite" | "fsLite" | "fs" | "github" | "http" | "indexedb" | "localstorage" | "lru-cache" | "lruCache" | "memory" | "mongodb" | "netlify-blobs" | "netlifyBlobs" | "null" | "overlay" | "planetscale" | "redis" | "s3" | "session-storage" | "sessionStorage" | "uploadthing" | "upstash" | "vercel-blob" | "vercelBlob" | "vercel-kv" | "vercelKV" | "vercel-runtime-cache" | "vercelRuntimeCache";
|
||||
type BuiltinDriverOptions = {
|
||||
"azure-app-configuration": AzureAppConfigurationOptions;
|
||||
"azureAppConfiguration": AzureAppConfigurationOptions;
|
||||
"azure-cosmos": AzureCosmosOptions;
|
||||
"azureCosmos": AzureCosmosOptions;
|
||||
"azure-key-vault": AzureKeyVaultOptions;
|
||||
"azureKeyVault": AzureKeyVaultOptions;
|
||||
"azure-storage-blob": AzureStorageBlobOptions;
|
||||
"azureStorageBlob": AzureStorageBlobOptions;
|
||||
"azure-storage-table": AzureStorageTableOptions;
|
||||
"azureStorageTable": AzureStorageTableOptions;
|
||||
"capacitor-preferences": CapacitorPreferencesOptions;
|
||||
"capacitorPreferences": CapacitorPreferencesOptions;
|
||||
"cloudflare-kv-binding": KVOptions;
|
||||
"cloudflareKVBinding": KVOptions;
|
||||
"cloudflare-kv-http": KVHTTPOptions;
|
||||
"cloudflareKVHttp": KVHTTPOptions;
|
||||
"cloudflare-r2-binding": CloudflareR2Options;
|
||||
"cloudflareR2Binding": CloudflareR2Options;
|
||||
"db0": DB0DriverOptions;
|
||||
"deno-kv-node": DenoKvNodeOptions;
|
||||
"denoKVNode": DenoKvNodeOptions;
|
||||
"deno-kv": DenoKvOptions;
|
||||
"denoKV": DenoKvOptions;
|
||||
"fs-lite": FSStorageOptions;
|
||||
"fsLite": FSStorageOptions;
|
||||
"fs": FSStorageOptions$1;
|
||||
"github": GithubOptions;
|
||||
"http": HTTPOptions;
|
||||
"indexedb": IDBKeyvalOptions;
|
||||
"localstorage": LocalStorageOptions;
|
||||
"lru-cache": LRUDriverOptions;
|
||||
"lruCache": LRUDriverOptions;
|
||||
"mongodb": MongoDbOptions;
|
||||
"netlify-blobs": NetlifyStoreOptions;
|
||||
"netlifyBlobs": NetlifyStoreOptions;
|
||||
"overlay": OverlayStorageOptions;
|
||||
"planetscale": PlanetscaleDriverOptions;
|
||||
"redis": RedisOptions;
|
||||
"s3": S3DriverOptions;
|
||||
"session-storage": SessionStorageOptions;
|
||||
"sessionStorage": SessionStorageOptions;
|
||||
"uploadthing": UploadThingOptions;
|
||||
"upstash": UpstashOptions;
|
||||
"vercel-blob": VercelBlobOptions;
|
||||
"vercelBlob": VercelBlobOptions;
|
||||
"vercel-kv": VercelKVOptions;
|
||||
"vercelKV": VercelKVOptions;
|
||||
"vercel-runtime-cache": VercelCacheOptions;
|
||||
"vercelRuntimeCache": VercelCacheOptions;
|
||||
};
|
||||
declare const builtinDrivers: {
|
||||
readonly "azure-app-configuration": "unstorage/drivers/azure-app-configuration";
|
||||
readonly azureAppConfiguration: "unstorage/drivers/azure-app-configuration";
|
||||
readonly "azure-cosmos": "unstorage/drivers/azure-cosmos";
|
||||
readonly azureCosmos: "unstorage/drivers/azure-cosmos";
|
||||
readonly "azure-key-vault": "unstorage/drivers/azure-key-vault";
|
||||
readonly azureKeyVault: "unstorage/drivers/azure-key-vault";
|
||||
readonly "azure-storage-blob": "unstorage/drivers/azure-storage-blob";
|
||||
readonly azureStorageBlob: "unstorage/drivers/azure-storage-blob";
|
||||
readonly "azure-storage-table": "unstorage/drivers/azure-storage-table";
|
||||
readonly azureStorageTable: "unstorage/drivers/azure-storage-table";
|
||||
readonly "capacitor-preferences": "unstorage/drivers/capacitor-preferences";
|
||||
readonly capacitorPreferences: "unstorage/drivers/capacitor-preferences";
|
||||
readonly "cloudflare-kv-binding": "unstorage/drivers/cloudflare-kv-binding";
|
||||
readonly cloudflareKVBinding: "unstorage/drivers/cloudflare-kv-binding";
|
||||
readonly "cloudflare-kv-http": "unstorage/drivers/cloudflare-kv-http";
|
||||
readonly cloudflareKVHttp: "unstorage/drivers/cloudflare-kv-http";
|
||||
readonly "cloudflare-r2-binding": "unstorage/drivers/cloudflare-r2-binding";
|
||||
readonly cloudflareR2Binding: "unstorage/drivers/cloudflare-r2-binding";
|
||||
readonly db0: "unstorage/drivers/db0";
|
||||
readonly "deno-kv-node": "unstorage/drivers/deno-kv-node";
|
||||
readonly denoKVNode: "unstorage/drivers/deno-kv-node";
|
||||
readonly "deno-kv": "unstorage/drivers/deno-kv";
|
||||
readonly denoKV: "unstorage/drivers/deno-kv";
|
||||
readonly "fs-lite": "unstorage/drivers/fs-lite";
|
||||
readonly fsLite: "unstorage/drivers/fs-lite";
|
||||
readonly fs: "unstorage/drivers/fs";
|
||||
readonly github: "unstorage/drivers/github";
|
||||
readonly http: "unstorage/drivers/http";
|
||||
readonly indexedb: "unstorage/drivers/indexedb";
|
||||
readonly localstorage: "unstorage/drivers/localstorage";
|
||||
readonly "lru-cache": "unstorage/drivers/lru-cache";
|
||||
readonly lruCache: "unstorage/drivers/lru-cache";
|
||||
readonly memory: "unstorage/drivers/memory";
|
||||
readonly mongodb: "unstorage/drivers/mongodb";
|
||||
readonly "netlify-blobs": "unstorage/drivers/netlify-blobs";
|
||||
readonly netlifyBlobs: "unstorage/drivers/netlify-blobs";
|
||||
readonly null: "unstorage/drivers/null";
|
||||
readonly overlay: "unstorage/drivers/overlay";
|
||||
readonly planetscale: "unstorage/drivers/planetscale";
|
||||
readonly redis: "unstorage/drivers/redis";
|
||||
readonly s3: "unstorage/drivers/s3";
|
||||
readonly "session-storage": "unstorage/drivers/session-storage";
|
||||
readonly sessionStorage: "unstorage/drivers/session-storage";
|
||||
readonly uploadthing: "unstorage/drivers/uploadthing";
|
||||
readonly upstash: "unstorage/drivers/upstash";
|
||||
readonly "vercel-blob": "unstorage/drivers/vercel-blob";
|
||||
readonly vercelBlob: "unstorage/drivers/vercel-blob";
|
||||
readonly "vercel-kv": "unstorage/drivers/vercel-kv";
|
||||
readonly vercelKV: "unstorage/drivers/vercel-kv";
|
||||
readonly "vercel-runtime-cache": "unstorage/drivers/vercel-runtime-cache";
|
||||
readonly vercelRuntimeCache: "unstorage/drivers/vercel-runtime-cache";
|
||||
};
|
||||
|
||||
export { Driver, Storage, StorageValue, builtinDrivers, createStorage, defineDriver, filterKeyByBase, filterKeyByDepth, hasDotSegment, joinKeys, normalizeBaseKey, normalizeKey, prefixStorage, restoreSnapshot, snapshot };
|
||||
export type { BuiltinDriverName, BuiltinDriverOptions, CreateStorageOptions, Snapshot };
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
import { D as Driver, S as StorageValue, a as Storage } from './shared/unstorage.DqlWKU2I.js';
|
||||
export { b as DriverFlags, G as GetKeysOptions, c as StorageMeta, T as TransactionOptions, U as Unwatch, W as WatchCallback, d as WatchEvent } from './shared/unstorage.DqlWKU2I.js';
|
||||
import { AzureAppConfigurationOptions } from 'unstorage/drivers/azure-app-configuration';
|
||||
import { AzureCosmosOptions } from 'unstorage/drivers/azure-cosmos';
|
||||
import { AzureKeyVaultOptions } from 'unstorage/drivers/azure-key-vault';
|
||||
import { AzureStorageBlobOptions } from 'unstorage/drivers/azure-storage-blob';
|
||||
import { AzureStorageTableOptions } from 'unstorage/drivers/azure-storage-table';
|
||||
import { CapacitorPreferencesOptions } from 'unstorage/drivers/capacitor-preferences';
|
||||
import { KVOptions } from 'unstorage/drivers/cloudflare-kv-binding';
|
||||
import { KVHTTPOptions } from 'unstorage/drivers/cloudflare-kv-http';
|
||||
import { CloudflareR2Options } from 'unstorage/drivers/cloudflare-r2-binding';
|
||||
import { DB0DriverOptions } from 'unstorage/drivers/db0';
|
||||
import { DenoKvNodeOptions } from 'unstorage/drivers/deno-kv-node';
|
||||
import { DenoKvOptions } from 'unstorage/drivers/deno-kv';
|
||||
import { FSStorageOptions } from 'unstorage/drivers/fs-lite';
|
||||
import { FSStorageOptions as FSStorageOptions$1 } from 'unstorage/drivers/fs';
|
||||
import { GithubOptions } from 'unstorage/drivers/github';
|
||||
import { HTTPOptions } from 'unstorage/drivers/http';
|
||||
import { IDBKeyvalOptions } from 'unstorage/drivers/indexedb';
|
||||
import { LocalStorageOptions } from 'unstorage/drivers/localstorage';
|
||||
import { LRUDriverOptions } from 'unstorage/drivers/lru-cache';
|
||||
import { MongoDbOptions } from 'unstorage/drivers/mongodb';
|
||||
import { NetlifyStoreOptions } from 'unstorage/drivers/netlify-blobs';
|
||||
import { OverlayStorageOptions } from 'unstorage/drivers/overlay';
|
||||
import { PlanetscaleDriverOptions } from 'unstorage/drivers/planetscale';
|
||||
import { RedisOptions } from 'unstorage/drivers/redis';
|
||||
import { S3DriverOptions } from 'unstorage/drivers/s3';
|
||||
import { SessionStorageOptions } from 'unstorage/drivers/session-storage';
|
||||
import { UploadThingOptions } from 'unstorage/drivers/uploadthing';
|
||||
import { UpstashOptions } from 'unstorage/drivers/upstash';
|
||||
import { VercelBlobOptions } from 'unstorage/drivers/vercel-blob';
|
||||
import { VercelKVOptions } from 'unstorage/drivers/vercel-kv';
|
||||
import { VercelCacheOptions } from 'unstorage/drivers/vercel-runtime-cache';
|
||||
|
||||
interface CreateStorageOptions {
|
||||
driver?: Driver;
|
||||
}
|
||||
declare function createStorage<T extends StorageValue>(options?: CreateStorageOptions): Storage<T>;
|
||||
type Snapshot<T = string> = Record<string, T>;
|
||||
declare function snapshot(storage: Storage, base: string): Promise<Snapshot<string>>;
|
||||
declare function restoreSnapshot(driver: Storage, snapshot: Snapshot<StorageValue>, base?: string): Promise<void>;
|
||||
|
||||
declare function prefixStorage<T extends StorageValue>(storage: Storage<T> | Storage<any>, base: string): Storage<T>;
|
||||
declare function normalizeKey(key?: string): string;
|
||||
/**
|
||||
* Check if a normalized key has `.` or `..` segments, which drivers mapping
|
||||
* keys to paths or URLs would resolve (and could escape their base with)
|
||||
*/
|
||||
declare function hasDotSegment(key: string): boolean;
|
||||
declare function joinKeys(...keys: string[]): string;
|
||||
declare function normalizeBaseKey(base?: string): string;
|
||||
declare function filterKeyByDepth(key: string, depth: number | undefined): boolean;
|
||||
declare function filterKeyByBase(key: string, base: string | undefined): boolean;
|
||||
|
||||
type DriverFactory<OptionsT, InstanceT> = (opts: OptionsT) => Driver<OptionsT, InstanceT>;
|
||||
declare function defineDriver<OptionsT = any, InstanceT = never>(factory: DriverFactory<OptionsT, InstanceT>): DriverFactory<OptionsT, InstanceT>;
|
||||
|
||||
type BuiltinDriverName = "azure-app-configuration" | "azureAppConfiguration" | "azure-cosmos" | "azureCosmos" | "azure-key-vault" | "azureKeyVault" | "azure-storage-blob" | "azureStorageBlob" | "azure-storage-table" | "azureStorageTable" | "capacitor-preferences" | "capacitorPreferences" | "cloudflare-kv-binding" | "cloudflareKVBinding" | "cloudflare-kv-http" | "cloudflareKVHttp" | "cloudflare-r2-binding" | "cloudflareR2Binding" | "db0" | "deno-kv-node" | "denoKVNode" | "deno-kv" | "denoKV" | "fs-lite" | "fsLite" | "fs" | "github" | "http" | "indexedb" | "localstorage" | "lru-cache" | "lruCache" | "memory" | "mongodb" | "netlify-blobs" | "netlifyBlobs" | "null" | "overlay" | "planetscale" | "redis" | "s3" | "session-storage" | "sessionStorage" | "uploadthing" | "upstash" | "vercel-blob" | "vercelBlob" | "vercel-kv" | "vercelKV" | "vercel-runtime-cache" | "vercelRuntimeCache";
|
||||
type BuiltinDriverOptions = {
|
||||
"azure-app-configuration": AzureAppConfigurationOptions;
|
||||
"azureAppConfiguration": AzureAppConfigurationOptions;
|
||||
"azure-cosmos": AzureCosmosOptions;
|
||||
"azureCosmos": AzureCosmosOptions;
|
||||
"azure-key-vault": AzureKeyVaultOptions;
|
||||
"azureKeyVault": AzureKeyVaultOptions;
|
||||
"azure-storage-blob": AzureStorageBlobOptions;
|
||||
"azureStorageBlob": AzureStorageBlobOptions;
|
||||
"azure-storage-table": AzureStorageTableOptions;
|
||||
"azureStorageTable": AzureStorageTableOptions;
|
||||
"capacitor-preferences": CapacitorPreferencesOptions;
|
||||
"capacitorPreferences": CapacitorPreferencesOptions;
|
||||
"cloudflare-kv-binding": KVOptions;
|
||||
"cloudflareKVBinding": KVOptions;
|
||||
"cloudflare-kv-http": KVHTTPOptions;
|
||||
"cloudflareKVHttp": KVHTTPOptions;
|
||||
"cloudflare-r2-binding": CloudflareR2Options;
|
||||
"cloudflareR2Binding": CloudflareR2Options;
|
||||
"db0": DB0DriverOptions;
|
||||
"deno-kv-node": DenoKvNodeOptions;
|
||||
"denoKVNode": DenoKvNodeOptions;
|
||||
"deno-kv": DenoKvOptions;
|
||||
"denoKV": DenoKvOptions;
|
||||
"fs-lite": FSStorageOptions;
|
||||
"fsLite": FSStorageOptions;
|
||||
"fs": FSStorageOptions$1;
|
||||
"github": GithubOptions;
|
||||
"http": HTTPOptions;
|
||||
"indexedb": IDBKeyvalOptions;
|
||||
"localstorage": LocalStorageOptions;
|
||||
"lru-cache": LRUDriverOptions;
|
||||
"lruCache": LRUDriverOptions;
|
||||
"mongodb": MongoDbOptions;
|
||||
"netlify-blobs": NetlifyStoreOptions;
|
||||
"netlifyBlobs": NetlifyStoreOptions;
|
||||
"overlay": OverlayStorageOptions;
|
||||
"planetscale": PlanetscaleDriverOptions;
|
||||
"redis": RedisOptions;
|
||||
"s3": S3DriverOptions;
|
||||
"session-storage": SessionStorageOptions;
|
||||
"sessionStorage": SessionStorageOptions;
|
||||
"uploadthing": UploadThingOptions;
|
||||
"upstash": UpstashOptions;
|
||||
"vercel-blob": VercelBlobOptions;
|
||||
"vercelBlob": VercelBlobOptions;
|
||||
"vercel-kv": VercelKVOptions;
|
||||
"vercelKV": VercelKVOptions;
|
||||
"vercel-runtime-cache": VercelCacheOptions;
|
||||
"vercelRuntimeCache": VercelCacheOptions;
|
||||
};
|
||||
declare const builtinDrivers: {
|
||||
readonly "azure-app-configuration": "unstorage/drivers/azure-app-configuration";
|
||||
readonly azureAppConfiguration: "unstorage/drivers/azure-app-configuration";
|
||||
readonly "azure-cosmos": "unstorage/drivers/azure-cosmos";
|
||||
readonly azureCosmos: "unstorage/drivers/azure-cosmos";
|
||||
readonly "azure-key-vault": "unstorage/drivers/azure-key-vault";
|
||||
readonly azureKeyVault: "unstorage/drivers/azure-key-vault";
|
||||
readonly "azure-storage-blob": "unstorage/drivers/azure-storage-blob";
|
||||
readonly azureStorageBlob: "unstorage/drivers/azure-storage-blob";
|
||||
readonly "azure-storage-table": "unstorage/drivers/azure-storage-table";
|
||||
readonly azureStorageTable: "unstorage/drivers/azure-storage-table";
|
||||
readonly "capacitor-preferences": "unstorage/drivers/capacitor-preferences";
|
||||
readonly capacitorPreferences: "unstorage/drivers/capacitor-preferences";
|
||||
readonly "cloudflare-kv-binding": "unstorage/drivers/cloudflare-kv-binding";
|
||||
readonly cloudflareKVBinding: "unstorage/drivers/cloudflare-kv-binding";
|
||||
readonly "cloudflare-kv-http": "unstorage/drivers/cloudflare-kv-http";
|
||||
readonly cloudflareKVHttp: "unstorage/drivers/cloudflare-kv-http";
|
||||
readonly "cloudflare-r2-binding": "unstorage/drivers/cloudflare-r2-binding";
|
||||
readonly cloudflareR2Binding: "unstorage/drivers/cloudflare-r2-binding";
|
||||
readonly db0: "unstorage/drivers/db0";
|
||||
readonly "deno-kv-node": "unstorage/drivers/deno-kv-node";
|
||||
readonly denoKVNode: "unstorage/drivers/deno-kv-node";
|
||||
readonly "deno-kv": "unstorage/drivers/deno-kv";
|
||||
readonly denoKV: "unstorage/drivers/deno-kv";
|
||||
readonly "fs-lite": "unstorage/drivers/fs-lite";
|
||||
readonly fsLite: "unstorage/drivers/fs-lite";
|
||||
readonly fs: "unstorage/drivers/fs";
|
||||
readonly github: "unstorage/drivers/github";
|
||||
readonly http: "unstorage/drivers/http";
|
||||
readonly indexedb: "unstorage/drivers/indexedb";
|
||||
readonly localstorage: "unstorage/drivers/localstorage";
|
||||
readonly "lru-cache": "unstorage/drivers/lru-cache";
|
||||
readonly lruCache: "unstorage/drivers/lru-cache";
|
||||
readonly memory: "unstorage/drivers/memory";
|
||||
readonly mongodb: "unstorage/drivers/mongodb";
|
||||
readonly "netlify-blobs": "unstorage/drivers/netlify-blobs";
|
||||
readonly netlifyBlobs: "unstorage/drivers/netlify-blobs";
|
||||
readonly null: "unstorage/drivers/null";
|
||||
readonly overlay: "unstorage/drivers/overlay";
|
||||
readonly planetscale: "unstorage/drivers/planetscale";
|
||||
readonly redis: "unstorage/drivers/redis";
|
||||
readonly s3: "unstorage/drivers/s3";
|
||||
readonly "session-storage": "unstorage/drivers/session-storage";
|
||||
readonly sessionStorage: "unstorage/drivers/session-storage";
|
||||
readonly uploadthing: "unstorage/drivers/uploadthing";
|
||||
readonly upstash: "unstorage/drivers/upstash";
|
||||
readonly "vercel-blob": "unstorage/drivers/vercel-blob";
|
||||
readonly vercelBlob: "unstorage/drivers/vercel-blob";
|
||||
readonly "vercel-kv": "unstorage/drivers/vercel-kv";
|
||||
readonly vercelKV: "unstorage/drivers/vercel-kv";
|
||||
readonly "vercel-runtime-cache": "unstorage/drivers/vercel-runtime-cache";
|
||||
readonly vercelRuntimeCache: "unstorage/drivers/vercel-runtime-cache";
|
||||
};
|
||||
|
||||
export { Driver, Storage, StorageValue, builtinDrivers, createStorage, defineDriver, filterKeyByBase, filterKeyByDepth, hasDotSegment, joinKeys, normalizeBaseKey, normalizeKey, prefixStorage, restoreSnapshot, snapshot };
|
||||
export type { BuiltinDriverName, BuiltinDriverOptions, CreateStorageOptions, Snapshot };
|
||||
+531
@@ -0,0 +1,531 @@
|
||||
import destr from 'destr';
|
||||
import { n as normalizeBaseKey, a as normalizeKey, b as asyncCall, f as filterKeyByDepth, c as filterKeyByBase, s as serializeRaw, d as stringify, e as deserializeRaw, h as hasDotSegment, j as joinKeys } from './shared/unstorage.lWbgcyKt.mjs';
|
||||
export { p as prefixStorage } from './shared/unstorage.lWbgcyKt.mjs';
|
||||
|
||||
function defineDriver(factory) {
|
||||
return factory;
|
||||
}
|
||||
|
||||
const DRIVER_NAME = "memory";
|
||||
const memory = defineDriver(() => {
|
||||
const data = /* @__PURE__ */ new Map();
|
||||
return {
|
||||
name: DRIVER_NAME,
|
||||
getInstance: () => data,
|
||||
hasItem(key) {
|
||||
return data.has(key);
|
||||
},
|
||||
getItem(key) {
|
||||
return data.get(key) ?? null;
|
||||
},
|
||||
getItemRaw(key) {
|
||||
return data.get(key) ?? null;
|
||||
},
|
||||
setItem(key, value) {
|
||||
data.set(key, value);
|
||||
},
|
||||
setItemRaw(key, value) {
|
||||
data.set(key, value);
|
||||
},
|
||||
removeItem(key) {
|
||||
data.delete(key);
|
||||
},
|
||||
getKeys() {
|
||||
return [...data.keys()];
|
||||
},
|
||||
clear() {
|
||||
data.clear();
|
||||
},
|
||||
dispose() {
|
||||
data.clear();
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
function createStorage(options = {}) {
|
||||
const context = {
|
||||
mounts: { "": options.driver || memory() },
|
||||
mountpoints: [""],
|
||||
watching: false,
|
||||
watchListeners: [],
|
||||
unwatch: {}
|
||||
};
|
||||
const normalizeItemKey = (key) => {
|
||||
const normalizedKey = normalizeKey(key);
|
||||
if (!normalizedKey || hasDotSegment(normalizedKey)) {
|
||||
throw new Error(`[unstorage] Invalid key: ${JSON.stringify(key)}`);
|
||||
}
|
||||
return normalizedKey;
|
||||
};
|
||||
const normalizeBase = (base) => {
|
||||
const normalizedBase = normalizeBaseKey(base);
|
||||
if (hasDotSegment(normalizedBase)) {
|
||||
throw new Error(`[unstorage] Invalid base: ${JSON.stringify(base)}`);
|
||||
}
|
||||
return normalizedBase;
|
||||
};
|
||||
const getMount = (key) => {
|
||||
for (const base of context.mountpoints) {
|
||||
if (key.startsWith(base)) {
|
||||
return {
|
||||
base,
|
||||
relativeKey: key.slice(base.length),
|
||||
driver: context.mounts[base]
|
||||
};
|
||||
}
|
||||
}
|
||||
return {
|
||||
base: "",
|
||||
relativeKey: key,
|
||||
driver: context.mounts[""]
|
||||
};
|
||||
};
|
||||
const getMounts = (base, includeParent) => {
|
||||
return context.mountpoints.filter(
|
||||
(mountpoint) => mountpoint.startsWith(base) || includeParent && base.startsWith(mountpoint)
|
||||
).map((mountpoint) => ({
|
||||
relativeBase: base.length > mountpoint.length ? base.slice(mountpoint.length) : void 0,
|
||||
mountpoint,
|
||||
driver: context.mounts[mountpoint]
|
||||
}));
|
||||
};
|
||||
const onChange = (event, key) => {
|
||||
if (!context.watching) {
|
||||
return;
|
||||
}
|
||||
key = normalizeKey(key);
|
||||
for (const listener of context.watchListeners) {
|
||||
listener(event, key);
|
||||
}
|
||||
};
|
||||
const startWatch = async () => {
|
||||
if (context.watching) {
|
||||
return;
|
||||
}
|
||||
context.watching = true;
|
||||
for (const mountpoint in context.mounts) {
|
||||
context.unwatch[mountpoint] = await watch(
|
||||
context.mounts[mountpoint],
|
||||
onChange,
|
||||
mountpoint
|
||||
);
|
||||
}
|
||||
};
|
||||
const stopWatch = async () => {
|
||||
if (!context.watching) {
|
||||
return;
|
||||
}
|
||||
for (const mountpoint in context.unwatch) {
|
||||
await context.unwatch[mountpoint]();
|
||||
}
|
||||
context.unwatch = {};
|
||||
context.watching = false;
|
||||
};
|
||||
const runBatch = (items, commonOptions, cb) => {
|
||||
const batches = /* @__PURE__ */ new Map();
|
||||
const getBatch = (mount) => {
|
||||
let batch = batches.get(mount.base);
|
||||
if (!batch) {
|
||||
batch = {
|
||||
driver: mount.driver,
|
||||
base: mount.base,
|
||||
items: []
|
||||
};
|
||||
batches.set(mount.base, batch);
|
||||
}
|
||||
return batch;
|
||||
};
|
||||
for (const item of items) {
|
||||
const isStringItem = typeof item === "string";
|
||||
const key = normalizeItemKey(isStringItem ? item : item.key);
|
||||
const value = isStringItem ? void 0 : item.value;
|
||||
const options2 = isStringItem || !item.options ? commonOptions : { ...commonOptions, ...item.options };
|
||||
const mount = getMount(key);
|
||||
getBatch(mount).items.push({
|
||||
key,
|
||||
value,
|
||||
relativeKey: mount.relativeKey,
|
||||
options: options2
|
||||
});
|
||||
}
|
||||
return Promise.all([...batches.values()].map((batch) => cb(batch))).then(
|
||||
(r) => r.flat()
|
||||
);
|
||||
};
|
||||
const storage = {
|
||||
// Item
|
||||
async hasItem(key, opts = {}) {
|
||||
key = normalizeItemKey(key);
|
||||
const { relativeKey, driver } = getMount(key);
|
||||
return asyncCall(driver.hasItem, relativeKey, opts);
|
||||
},
|
||||
async getItem(key, opts = {}) {
|
||||
key = normalizeItemKey(key);
|
||||
const { relativeKey, driver } = getMount(key);
|
||||
return asyncCall(driver.getItem, relativeKey, opts).then(
|
||||
(value) => destr(value)
|
||||
);
|
||||
},
|
||||
async getItems(items, commonOptions = {}) {
|
||||
return runBatch(items, commonOptions, (batch) => {
|
||||
if (batch.driver.getItems) {
|
||||
return asyncCall(
|
||||
batch.driver.getItems,
|
||||
batch.items.map((item) => ({
|
||||
key: item.relativeKey,
|
||||
options: item.options
|
||||
})),
|
||||
commonOptions
|
||||
).then(
|
||||
(r) => r.map((item) => ({
|
||||
key: joinKeys(batch.base, item.key),
|
||||
value: destr(item.value)
|
||||
}))
|
||||
);
|
||||
}
|
||||
return Promise.all(
|
||||
batch.items.map((item) => {
|
||||
return asyncCall(
|
||||
batch.driver.getItem,
|
||||
item.relativeKey,
|
||||
item.options
|
||||
).then((value) => ({
|
||||
key: item.key,
|
||||
value: destr(value)
|
||||
}));
|
||||
})
|
||||
);
|
||||
});
|
||||
},
|
||||
async getItemRaw(key, opts = {}) {
|
||||
key = normalizeItemKey(key);
|
||||
const { relativeKey, driver } = getMount(key);
|
||||
if (driver.getItemRaw) {
|
||||
return asyncCall(driver.getItemRaw, relativeKey, opts);
|
||||
}
|
||||
return asyncCall(driver.getItem, relativeKey, opts).then(
|
||||
(value) => deserializeRaw(value)
|
||||
);
|
||||
},
|
||||
async setItem(key, value, opts = {}) {
|
||||
if (value === void 0) {
|
||||
return storage.removeItem(key);
|
||||
}
|
||||
key = normalizeItemKey(key);
|
||||
const { relativeKey, driver } = getMount(key);
|
||||
if (!driver.setItem) {
|
||||
return;
|
||||
}
|
||||
await asyncCall(driver.setItem, relativeKey, stringify(value), opts);
|
||||
if (!driver.watch) {
|
||||
onChange("update", key);
|
||||
}
|
||||
},
|
||||
async setItems(items, commonOptions) {
|
||||
await runBatch(items, commonOptions, async (batch) => {
|
||||
if (batch.driver.setItems) {
|
||||
return asyncCall(
|
||||
batch.driver.setItems,
|
||||
batch.items.map((item) => ({
|
||||
key: item.relativeKey,
|
||||
value: stringify(item.value),
|
||||
options: item.options
|
||||
})),
|
||||
commonOptions
|
||||
);
|
||||
}
|
||||
if (!batch.driver.setItem) {
|
||||
return;
|
||||
}
|
||||
await Promise.all(
|
||||
batch.items.map((item) => {
|
||||
return asyncCall(
|
||||
batch.driver.setItem,
|
||||
item.relativeKey,
|
||||
stringify(item.value),
|
||||
item.options
|
||||
);
|
||||
})
|
||||
);
|
||||
});
|
||||
},
|
||||
async setItemRaw(key, value, opts = {}) {
|
||||
if (value === void 0) {
|
||||
return storage.removeItem(key, opts);
|
||||
}
|
||||
key = normalizeItemKey(key);
|
||||
const { relativeKey, driver } = getMount(key);
|
||||
if (driver.setItemRaw) {
|
||||
await asyncCall(driver.setItemRaw, relativeKey, value, opts);
|
||||
} else if (driver.setItem) {
|
||||
await asyncCall(driver.setItem, relativeKey, serializeRaw(value), opts);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
if (!driver.watch) {
|
||||
onChange("update", key);
|
||||
}
|
||||
},
|
||||
async removeItem(key, opts = {}) {
|
||||
if (typeof opts === "boolean") {
|
||||
opts = { removeMeta: opts };
|
||||
}
|
||||
key = normalizeItemKey(key);
|
||||
const { relativeKey, driver } = getMount(key);
|
||||
if (!driver.removeItem) {
|
||||
return;
|
||||
}
|
||||
await asyncCall(driver.removeItem, relativeKey, opts);
|
||||
if (opts.removeMeta || opts.removeMata) {
|
||||
await asyncCall(driver.removeItem, relativeKey + "$", opts);
|
||||
}
|
||||
if (!driver.watch) {
|
||||
onChange("remove", key);
|
||||
}
|
||||
},
|
||||
// Meta
|
||||
async getMeta(key, opts = {}) {
|
||||
if (typeof opts === "boolean") {
|
||||
opts = { nativeOnly: opts };
|
||||
}
|
||||
key = normalizeItemKey(key);
|
||||
const { relativeKey, driver } = getMount(key);
|
||||
const meta = /* @__PURE__ */ Object.create(null);
|
||||
if (driver.getMeta) {
|
||||
Object.assign(meta, await asyncCall(driver.getMeta, relativeKey, opts));
|
||||
}
|
||||
if (!opts.nativeOnly) {
|
||||
const value = await asyncCall(
|
||||
driver.getItem,
|
||||
relativeKey + "$",
|
||||
opts
|
||||
).then((value_) => destr(value_));
|
||||
if (value && typeof value === "object") {
|
||||
if (typeof value.atime === "string") {
|
||||
value.atime = new Date(value.atime);
|
||||
}
|
||||
if (typeof value.mtime === "string") {
|
||||
value.mtime = new Date(value.mtime);
|
||||
}
|
||||
Object.assign(meta, value);
|
||||
}
|
||||
}
|
||||
return meta;
|
||||
},
|
||||
async setMeta(key, value, opts = {}) {
|
||||
return this.setItem(normalizeItemKey(key) + "$", value, opts);
|
||||
},
|
||||
async removeMeta(key, opts = {}) {
|
||||
return this.removeItem(normalizeItemKey(key) + "$", opts);
|
||||
},
|
||||
// Keys
|
||||
async getKeys(base, opts = {}) {
|
||||
base = normalizeBase(base);
|
||||
const mounts = getMounts(base, true);
|
||||
let maskedMounts = [];
|
||||
const allKeys = [];
|
||||
let allMountsSupportMaxDepth = true;
|
||||
for (const mount of mounts) {
|
||||
if (!mount.driver.flags?.maxDepth) {
|
||||
allMountsSupportMaxDepth = false;
|
||||
}
|
||||
const rawKeys = await asyncCall(
|
||||
mount.driver.getKeys,
|
||||
mount.relativeBase,
|
||||
opts
|
||||
);
|
||||
for (const key of rawKeys) {
|
||||
const fullKey = mount.mountpoint + normalizeKey(key);
|
||||
if (!maskedMounts.some((p) => fullKey.startsWith(p))) {
|
||||
allKeys.push(fullKey);
|
||||
}
|
||||
}
|
||||
maskedMounts = [
|
||||
mount.mountpoint,
|
||||
...maskedMounts.filter((p) => !p.startsWith(mount.mountpoint))
|
||||
];
|
||||
}
|
||||
const shouldFilterByDepth = opts.maxDepth !== void 0 && !allMountsSupportMaxDepth;
|
||||
return allKeys.filter(
|
||||
(key) => (!shouldFilterByDepth || filterKeyByDepth(key, opts.maxDepth)) && filterKeyByBase(key, base)
|
||||
);
|
||||
},
|
||||
// Utils
|
||||
async clear(base, opts = {}) {
|
||||
base = normalizeBase(base);
|
||||
await Promise.all(
|
||||
getMounts(base, false).map(async (m) => {
|
||||
if (m.driver.clear) {
|
||||
return asyncCall(m.driver.clear, m.relativeBase, opts);
|
||||
}
|
||||
if (m.driver.removeItem) {
|
||||
const keys = await m.driver.getKeys(m.relativeBase || "", opts);
|
||||
return Promise.all(
|
||||
keys.map((key) => m.driver.removeItem(key, opts))
|
||||
);
|
||||
}
|
||||
})
|
||||
);
|
||||
},
|
||||
async dispose() {
|
||||
await Promise.all(
|
||||
Object.values(context.mounts).map((driver) => dispose(driver))
|
||||
);
|
||||
},
|
||||
async watch(callback) {
|
||||
await startWatch();
|
||||
context.watchListeners.push(callback);
|
||||
return async () => {
|
||||
context.watchListeners = context.watchListeners.filter(
|
||||
(listener) => listener !== callback
|
||||
);
|
||||
if (context.watchListeners.length === 0) {
|
||||
await stopWatch();
|
||||
}
|
||||
};
|
||||
},
|
||||
async unwatch() {
|
||||
context.watchListeners = [];
|
||||
await stopWatch();
|
||||
},
|
||||
// Mount
|
||||
mount(base, driver) {
|
||||
base = normalizeBase(base);
|
||||
if (base && context.mounts[base]) {
|
||||
throw new Error(`already mounted at ${base}`);
|
||||
}
|
||||
if (base) {
|
||||
context.mountpoints.push(base);
|
||||
context.mountpoints.sort((a, b) => b.length - a.length);
|
||||
}
|
||||
context.mounts[base] = driver;
|
||||
if (context.watching) {
|
||||
Promise.resolve(watch(driver, onChange, base)).then((unwatcher) => {
|
||||
context.unwatch[base] = unwatcher;
|
||||
}).catch(console.error);
|
||||
}
|
||||
return storage;
|
||||
},
|
||||
async unmount(base, _dispose = true) {
|
||||
base = normalizeBaseKey(base);
|
||||
if (!base || !context.mounts[base]) {
|
||||
return;
|
||||
}
|
||||
if (context.watching && base in context.unwatch) {
|
||||
context.unwatch[base]?.();
|
||||
delete context.unwatch[base];
|
||||
}
|
||||
if (_dispose) {
|
||||
await dispose(context.mounts[base]);
|
||||
}
|
||||
context.mountpoints = context.mountpoints.filter((key) => key !== base);
|
||||
delete context.mounts[base];
|
||||
},
|
||||
getMount(key = "") {
|
||||
key = normalizeKey(key) + ":";
|
||||
const m = getMount(key);
|
||||
return {
|
||||
driver: m.driver,
|
||||
base: m.base
|
||||
};
|
||||
},
|
||||
getMounts(base = "", opts = {}) {
|
||||
base = normalizeKey(base);
|
||||
const mounts = getMounts(base, opts.parents);
|
||||
return mounts.map((m) => ({
|
||||
driver: m.driver,
|
||||
base: m.mountpoint
|
||||
}));
|
||||
},
|
||||
// Aliases
|
||||
keys: (base, opts = {}) => storage.getKeys(base, opts),
|
||||
get: (key, opts = {}) => storage.getItem(key, opts),
|
||||
set: (key, value, opts = {}) => storage.setItem(key, value, opts),
|
||||
has: (key, opts = {}) => storage.hasItem(key, opts),
|
||||
del: (key, opts = {}) => storage.removeItem(key, opts),
|
||||
remove: (key, opts = {}) => storage.removeItem(key, opts)
|
||||
};
|
||||
return storage;
|
||||
}
|
||||
async function snapshot(storage, base) {
|
||||
base = normalizeBaseKey(base);
|
||||
const keys = await storage.getKeys(base);
|
||||
const snapshot2 = {};
|
||||
await Promise.all(
|
||||
keys.map(async (key) => {
|
||||
snapshot2[key.slice(base.length)] = await storage.getItem(key);
|
||||
})
|
||||
);
|
||||
return snapshot2;
|
||||
}
|
||||
async function restoreSnapshot(driver, snapshot2, base = "") {
|
||||
base = normalizeBaseKey(base);
|
||||
await Promise.all(
|
||||
Object.entries(snapshot2).map((e) => driver.setItem(base + e[0], e[1]))
|
||||
);
|
||||
}
|
||||
function watch(driver, onChange, base) {
|
||||
return driver.watch ? driver.watch((event, key) => onChange(event, base + key)) : () => {
|
||||
};
|
||||
}
|
||||
async function dispose(driver) {
|
||||
if (typeof driver.dispose === "function") {
|
||||
await asyncCall(driver.dispose);
|
||||
}
|
||||
}
|
||||
|
||||
const builtinDrivers = {
|
||||
"azure-app-configuration": "unstorage/drivers/azure-app-configuration",
|
||||
"azureAppConfiguration": "unstorage/drivers/azure-app-configuration",
|
||||
"azure-cosmos": "unstorage/drivers/azure-cosmos",
|
||||
"azureCosmos": "unstorage/drivers/azure-cosmos",
|
||||
"azure-key-vault": "unstorage/drivers/azure-key-vault",
|
||||
"azureKeyVault": "unstorage/drivers/azure-key-vault",
|
||||
"azure-storage-blob": "unstorage/drivers/azure-storage-blob",
|
||||
"azureStorageBlob": "unstorage/drivers/azure-storage-blob",
|
||||
"azure-storage-table": "unstorage/drivers/azure-storage-table",
|
||||
"azureStorageTable": "unstorage/drivers/azure-storage-table",
|
||||
"capacitor-preferences": "unstorage/drivers/capacitor-preferences",
|
||||
"capacitorPreferences": "unstorage/drivers/capacitor-preferences",
|
||||
"cloudflare-kv-binding": "unstorage/drivers/cloudflare-kv-binding",
|
||||
"cloudflareKVBinding": "unstorage/drivers/cloudflare-kv-binding",
|
||||
"cloudflare-kv-http": "unstorage/drivers/cloudflare-kv-http",
|
||||
"cloudflareKVHttp": "unstorage/drivers/cloudflare-kv-http",
|
||||
"cloudflare-r2-binding": "unstorage/drivers/cloudflare-r2-binding",
|
||||
"cloudflareR2Binding": "unstorage/drivers/cloudflare-r2-binding",
|
||||
"db0": "unstorage/drivers/db0",
|
||||
"deno-kv-node": "unstorage/drivers/deno-kv-node",
|
||||
"denoKVNode": "unstorage/drivers/deno-kv-node",
|
||||
"deno-kv": "unstorage/drivers/deno-kv",
|
||||
"denoKV": "unstorage/drivers/deno-kv",
|
||||
"fs-lite": "unstorage/drivers/fs-lite",
|
||||
"fsLite": "unstorage/drivers/fs-lite",
|
||||
"fs": "unstorage/drivers/fs",
|
||||
"github": "unstorage/drivers/github",
|
||||
"http": "unstorage/drivers/http",
|
||||
"indexedb": "unstorage/drivers/indexedb",
|
||||
"localstorage": "unstorage/drivers/localstorage",
|
||||
"lru-cache": "unstorage/drivers/lru-cache",
|
||||
"lruCache": "unstorage/drivers/lru-cache",
|
||||
"memory": "unstorage/drivers/memory",
|
||||
"mongodb": "unstorage/drivers/mongodb",
|
||||
"netlify-blobs": "unstorage/drivers/netlify-blobs",
|
||||
"netlifyBlobs": "unstorage/drivers/netlify-blobs",
|
||||
"null": "unstorage/drivers/null",
|
||||
"overlay": "unstorage/drivers/overlay",
|
||||
"planetscale": "unstorage/drivers/planetscale",
|
||||
"redis": "unstorage/drivers/redis",
|
||||
"s3": "unstorage/drivers/s3",
|
||||
"session-storage": "unstorage/drivers/session-storage",
|
||||
"sessionStorage": "unstorage/drivers/session-storage",
|
||||
"uploadthing": "unstorage/drivers/uploadthing",
|
||||
"upstash": "unstorage/drivers/upstash",
|
||||
"vercel-blob": "unstorage/drivers/vercel-blob",
|
||||
"vercelBlob": "unstorage/drivers/vercel-blob",
|
||||
"vercel-kv": "unstorage/drivers/vercel-kv",
|
||||
"vercelKV": "unstorage/drivers/vercel-kv",
|
||||
"vercel-runtime-cache": "unstorage/drivers/vercel-runtime-cache",
|
||||
"vercelRuntimeCache": "unstorage/drivers/vercel-runtime-cache"
|
||||
};
|
||||
|
||||
export { builtinDrivers, createStorage, defineDriver, filterKeyByBase, filterKeyByDepth, hasDotSegment, joinKeys, normalizeBaseKey, normalizeKey, restoreSnapshot, snapshot };
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
'use strict';
|
||||
|
||||
const h3 = require('h3');
|
||||
const utils = require('./shared/unstorage.D3XyewAC.cjs');
|
||||
|
||||
const MethodToTypeMap = {
|
||||
GET: "read",
|
||||
HEAD: "read",
|
||||
PUT: "write",
|
||||
DELETE: "write"
|
||||
};
|
||||
function createH3StorageHandler(storage, opts = {}) {
|
||||
return h3.eventHandler(async (event) => {
|
||||
const _path = (opts.resolvePath?.(event) ?? event.path).split("?")[0].replace(/%25/g, "%");
|
||||
const lastChar = _path[_path.length - 1];
|
||||
const isBaseKey = lastChar === ":" || lastChar === "/";
|
||||
const key = isBaseKey ? utils.normalizeBaseKey(_path) : utils.normalizeKey(_path);
|
||||
if (!(event.method in MethodToTypeMap)) {
|
||||
throw h3.createError({
|
||||
statusCode: 405,
|
||||
statusMessage: `Method Not Allowed: ${event.method}`
|
||||
});
|
||||
}
|
||||
if (!isBaseKey && !key || utils.hasDotSegment(key)) {
|
||||
throw h3.createError({
|
||||
statusCode: 400,
|
||||
statusMessage: "Invalid key"
|
||||
});
|
||||
}
|
||||
if (isBaseKey && (event.method === "HEAD" || event.method === "PUT")) {
|
||||
throw h3.createError({
|
||||
statusCode: 400,
|
||||
statusMessage: `Invalid key: ${event.method} is not allowed on a base key`
|
||||
});
|
||||
}
|
||||
try {
|
||||
await opts.authorize?.({
|
||||
type: MethodToTypeMap[event.method],
|
||||
event,
|
||||
key
|
||||
});
|
||||
} catch (error) {
|
||||
const _httpError = h3.isError(error) ? error : h3.createError({
|
||||
statusMessage: error?.message,
|
||||
statusCode: 401,
|
||||
...error
|
||||
});
|
||||
throw _httpError;
|
||||
}
|
||||
if (event.method === "GET") {
|
||||
if (isBaseKey) {
|
||||
const keys = await storage.getKeys(key);
|
||||
return keys.map((key2) => key2.replace(/:/g, "/"));
|
||||
}
|
||||
const isRaw = h3.getRequestHeader(event, "accept") === "application/octet-stream";
|
||||
const driverValue = await (isRaw ? storage.getItemRaw(key) : storage.getItem(key));
|
||||
if (driverValue === null) {
|
||||
throw h3.createError({
|
||||
statusCode: 404,
|
||||
statusMessage: "KV value not found"
|
||||
});
|
||||
}
|
||||
setMetaHeaders(event, await storage.getMeta(key));
|
||||
return isRaw ? driverValue : utils.stringify(driverValue);
|
||||
}
|
||||
if (event.method === "HEAD") {
|
||||
if (!await storage.hasItem(key)) {
|
||||
throw h3.createError({
|
||||
statusCode: 404,
|
||||
statusMessage: "KV value not found"
|
||||
});
|
||||
}
|
||||
setMetaHeaders(event, await storage.getMeta(key));
|
||||
return "";
|
||||
}
|
||||
if (event.method === "PUT") {
|
||||
const isRaw = h3.getRequestHeader(event, "content-type") === "application/octet-stream";
|
||||
const topts = {
|
||||
ttl: Number(h3.getRequestHeader(event, "x-ttl")) || void 0
|
||||
};
|
||||
if (isRaw) {
|
||||
const value = await h3.readRawBody(event, false);
|
||||
await storage.setItemRaw(key, value, topts);
|
||||
} else {
|
||||
const value = await h3.readRawBody(event, "utf8");
|
||||
if (value !== void 0) {
|
||||
await storage.setItem(key, value, topts);
|
||||
}
|
||||
}
|
||||
return "OK";
|
||||
}
|
||||
if (event.method === "DELETE") {
|
||||
await (isBaseKey ? storage.clear(key) : storage.removeItem(key));
|
||||
return "OK";
|
||||
}
|
||||
throw h3.createError({
|
||||
statusCode: 405,
|
||||
statusMessage: `Method Not Allowed: ${event.method}`
|
||||
});
|
||||
});
|
||||
}
|
||||
function setMetaHeaders(event, meta) {
|
||||
if (meta.mtime) {
|
||||
h3.setResponseHeader(
|
||||
event,
|
||||
"last-modified",
|
||||
new Date(meta.mtime).toUTCString()
|
||||
);
|
||||
}
|
||||
if (meta.ttl) {
|
||||
h3.setResponseHeader(event, "x-ttl", `${meta.ttl}`);
|
||||
h3.setResponseHeader(event, "cache-control", `max-age=${meta.ttl}`);
|
||||
}
|
||||
}
|
||||
function createStorageServer(storage, options = {}) {
|
||||
const app = h3.createApp({ debug: true });
|
||||
const handler = createH3StorageHandler(storage, options);
|
||||
app.use(handler);
|
||||
return {
|
||||
handle: h3.toNodeListener(app)
|
||||
};
|
||||
}
|
||||
|
||||
exports.createH3StorageHandler = createH3StorageHandler;
|
||||
exports.createStorageServer = createStorageServer;
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
import { RequestListener } from 'node:http';
|
||||
import { H3Event, EventHandler } from 'h3';
|
||||
import { Storage } from './index.cjs';
|
||||
|
||||
type StorageServerRequest = {
|
||||
event: H3Event;
|
||||
key: string;
|
||||
type: "read" | "write";
|
||||
};
|
||||
interface StorageServerOptions {
|
||||
authorize?: (request: StorageServerRequest) => void | Promise<void>;
|
||||
resolvePath?: (event: H3Event) => string;
|
||||
}
|
||||
/**
|
||||
* This function creates an h3-based handler for the storage server. It can then be used as event handler in h3 or Nitro
|
||||
* @param storage The storage which should be used for the storage server
|
||||
* @param opts Storage options to set the authorization check or a custom path resolver
|
||||
* @returns
|
||||
* @see createStorageServer if a node-compatible handler is needed
|
||||
*/
|
||||
declare function createH3StorageHandler(storage: Storage, opts?: StorageServerOptions): EventHandler;
|
||||
/**
|
||||
* This function creates a node-compatible handler for your custom storage server.
|
||||
*
|
||||
* The storage server will handle HEAD, GET, PUT and DELETE requests.
|
||||
* HEAD: Return if the request item exists in the storage, including a last-modified header if the storage supports it and the meta is stored
|
||||
* GET: Return the item if it exists
|
||||
* PUT: Sets the item
|
||||
* DELETE: Removes the item (or clears the whole storage if the base key was used)
|
||||
*
|
||||
* If the request sets the `Accept` header to `application/octet-stream`, the server will handle the item as raw data.
|
||||
*
|
||||
* @param storage The storage which should be used for the storage server
|
||||
* @param options Defining functions such as an authorization check and a custom path resolver
|
||||
* @returns An object containing then `handle` function for the handler
|
||||
* @see createH3StorageHandler For the bare h3 version which can be used with h3 or Nitro
|
||||
*/
|
||||
declare function createStorageServer(storage: Storage, options?: StorageServerOptions): {
|
||||
handle: RequestListener;
|
||||
};
|
||||
|
||||
export { createH3StorageHandler, createStorageServer };
|
||||
export type { StorageServerOptions, StorageServerRequest };
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
import { RequestListener } from 'node:http';
|
||||
import { H3Event, EventHandler } from 'h3';
|
||||
import { Storage } from './index.mjs';
|
||||
|
||||
type StorageServerRequest = {
|
||||
event: H3Event;
|
||||
key: string;
|
||||
type: "read" | "write";
|
||||
};
|
||||
interface StorageServerOptions {
|
||||
authorize?: (request: StorageServerRequest) => void | Promise<void>;
|
||||
resolvePath?: (event: H3Event) => string;
|
||||
}
|
||||
/**
|
||||
* This function creates an h3-based handler for the storage server. It can then be used as event handler in h3 or Nitro
|
||||
* @param storage The storage which should be used for the storage server
|
||||
* @param opts Storage options to set the authorization check or a custom path resolver
|
||||
* @returns
|
||||
* @see createStorageServer if a node-compatible handler is needed
|
||||
*/
|
||||
declare function createH3StorageHandler(storage: Storage, opts?: StorageServerOptions): EventHandler;
|
||||
/**
|
||||
* This function creates a node-compatible handler for your custom storage server.
|
||||
*
|
||||
* The storage server will handle HEAD, GET, PUT and DELETE requests.
|
||||
* HEAD: Return if the request item exists in the storage, including a last-modified header if the storage supports it and the meta is stored
|
||||
* GET: Return the item if it exists
|
||||
* PUT: Sets the item
|
||||
* DELETE: Removes the item (or clears the whole storage if the base key was used)
|
||||
*
|
||||
* If the request sets the `Accept` header to `application/octet-stream`, the server will handle the item as raw data.
|
||||
*
|
||||
* @param storage The storage which should be used for the storage server
|
||||
* @param options Defining functions such as an authorization check and a custom path resolver
|
||||
* @returns An object containing then `handle` function for the handler
|
||||
* @see createH3StorageHandler For the bare h3 version which can be used with h3 or Nitro
|
||||
*/
|
||||
declare function createStorageServer(storage: Storage, options?: StorageServerOptions): {
|
||||
handle: RequestListener;
|
||||
};
|
||||
|
||||
export { createH3StorageHandler, createStorageServer };
|
||||
export type { StorageServerOptions, StorageServerRequest };
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
import { RequestListener } from 'node:http';
|
||||
import { H3Event, EventHandler } from 'h3';
|
||||
import { Storage } from './index.js';
|
||||
|
||||
type StorageServerRequest = {
|
||||
event: H3Event;
|
||||
key: string;
|
||||
type: "read" | "write";
|
||||
};
|
||||
interface StorageServerOptions {
|
||||
authorize?: (request: StorageServerRequest) => void | Promise<void>;
|
||||
resolvePath?: (event: H3Event) => string;
|
||||
}
|
||||
/**
|
||||
* This function creates an h3-based handler for the storage server. It can then be used as event handler in h3 or Nitro
|
||||
* @param storage The storage which should be used for the storage server
|
||||
* @param opts Storage options to set the authorization check or a custom path resolver
|
||||
* @returns
|
||||
* @see createStorageServer if a node-compatible handler is needed
|
||||
*/
|
||||
declare function createH3StorageHandler(storage: Storage, opts?: StorageServerOptions): EventHandler;
|
||||
/**
|
||||
* This function creates a node-compatible handler for your custom storage server.
|
||||
*
|
||||
* The storage server will handle HEAD, GET, PUT and DELETE requests.
|
||||
* HEAD: Return if the request item exists in the storage, including a last-modified header if the storage supports it and the meta is stored
|
||||
* GET: Return the item if it exists
|
||||
* PUT: Sets the item
|
||||
* DELETE: Removes the item (or clears the whole storage if the base key was used)
|
||||
*
|
||||
* If the request sets the `Accept` header to `application/octet-stream`, the server will handle the item as raw data.
|
||||
*
|
||||
* @param storage The storage which should be used for the storage server
|
||||
* @param options Defining functions such as an authorization check and a custom path resolver
|
||||
* @returns An object containing then `handle` function for the handler
|
||||
* @see createH3StorageHandler For the bare h3 version which can be used with h3 or Nitro
|
||||
*/
|
||||
declare function createStorageServer(storage: Storage, options?: StorageServerOptions): {
|
||||
handle: RequestListener;
|
||||
};
|
||||
|
||||
export { createH3StorageHandler, createStorageServer };
|
||||
export type { StorageServerOptions, StorageServerRequest };
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
import { eventHandler, createError, isError, getRequestHeader, readRawBody, createApp, toNodeListener, setResponseHeader } from 'h3';
|
||||
import { n as normalizeBaseKey, a as normalizeKey, h as hasDotSegment, d as stringify } from './shared/unstorage.lWbgcyKt.mjs';
|
||||
|
||||
const MethodToTypeMap = {
|
||||
GET: "read",
|
||||
HEAD: "read",
|
||||
PUT: "write",
|
||||
DELETE: "write"
|
||||
};
|
||||
function createH3StorageHandler(storage, opts = {}) {
|
||||
return eventHandler(async (event) => {
|
||||
const _path = (opts.resolvePath?.(event) ?? event.path).split("?")[0].replace(/%25/g, "%");
|
||||
const lastChar = _path[_path.length - 1];
|
||||
const isBaseKey = lastChar === ":" || lastChar === "/";
|
||||
const key = isBaseKey ? normalizeBaseKey(_path) : normalizeKey(_path);
|
||||
if (!(event.method in MethodToTypeMap)) {
|
||||
throw createError({
|
||||
statusCode: 405,
|
||||
statusMessage: `Method Not Allowed: ${event.method}`
|
||||
});
|
||||
}
|
||||
if (!isBaseKey && !key || hasDotSegment(key)) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: "Invalid key"
|
||||
});
|
||||
}
|
||||
if (isBaseKey && (event.method === "HEAD" || event.method === "PUT")) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: `Invalid key: ${event.method} is not allowed on a base key`
|
||||
});
|
||||
}
|
||||
try {
|
||||
await opts.authorize?.({
|
||||
type: MethodToTypeMap[event.method],
|
||||
event,
|
||||
key
|
||||
});
|
||||
} catch (error) {
|
||||
const _httpError = isError(error) ? error : createError({
|
||||
statusMessage: error?.message,
|
||||
statusCode: 401,
|
||||
...error
|
||||
});
|
||||
throw _httpError;
|
||||
}
|
||||
if (event.method === "GET") {
|
||||
if (isBaseKey) {
|
||||
const keys = await storage.getKeys(key);
|
||||
return keys.map((key2) => key2.replace(/:/g, "/"));
|
||||
}
|
||||
const isRaw = getRequestHeader(event, "accept") === "application/octet-stream";
|
||||
const driverValue = await (isRaw ? storage.getItemRaw(key) : storage.getItem(key));
|
||||
if (driverValue === null) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
statusMessage: "KV value not found"
|
||||
});
|
||||
}
|
||||
setMetaHeaders(event, await storage.getMeta(key));
|
||||
return isRaw ? driverValue : stringify(driverValue);
|
||||
}
|
||||
if (event.method === "HEAD") {
|
||||
if (!await storage.hasItem(key)) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
statusMessage: "KV value not found"
|
||||
});
|
||||
}
|
||||
setMetaHeaders(event, await storage.getMeta(key));
|
||||
return "";
|
||||
}
|
||||
if (event.method === "PUT") {
|
||||
const isRaw = getRequestHeader(event, "content-type") === "application/octet-stream";
|
||||
const topts = {
|
||||
ttl: Number(getRequestHeader(event, "x-ttl")) || void 0
|
||||
};
|
||||
if (isRaw) {
|
||||
const value = await readRawBody(event, false);
|
||||
await storage.setItemRaw(key, value, topts);
|
||||
} else {
|
||||
const value = await readRawBody(event, "utf8");
|
||||
if (value !== void 0) {
|
||||
await storage.setItem(key, value, topts);
|
||||
}
|
||||
}
|
||||
return "OK";
|
||||
}
|
||||
if (event.method === "DELETE") {
|
||||
await (isBaseKey ? storage.clear(key) : storage.removeItem(key));
|
||||
return "OK";
|
||||
}
|
||||
throw createError({
|
||||
statusCode: 405,
|
||||
statusMessage: `Method Not Allowed: ${event.method}`
|
||||
});
|
||||
});
|
||||
}
|
||||
function setMetaHeaders(event, meta) {
|
||||
if (meta.mtime) {
|
||||
setResponseHeader(
|
||||
event,
|
||||
"last-modified",
|
||||
new Date(meta.mtime).toUTCString()
|
||||
);
|
||||
}
|
||||
if (meta.ttl) {
|
||||
setResponseHeader(event, "x-ttl", `${meta.ttl}`);
|
||||
setResponseHeader(event, "cache-control", `max-age=${meta.ttl}`);
|
||||
}
|
||||
}
|
||||
function createStorageServer(storage, options = {}) {
|
||||
const app = createApp({ debug: true });
|
||||
const handler = createH3StorageHandler(storage, options);
|
||||
app.use(handler);
|
||||
return {
|
||||
handle: toNodeListener(app)
|
||||
};
|
||||
}
|
||||
|
||||
export { createH3StorageHandler, createStorageServer };
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
'use strict';
|
||||
|
||||
function wrapToPromise(value) {
|
||||
if (!value || typeof value.then !== "function") {
|
||||
return Promise.resolve(value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
function asyncCall(function_, ...arguments_) {
|
||||
try {
|
||||
return wrapToPromise(function_(...arguments_));
|
||||
} catch (error) {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
}
|
||||
function isPrimitive(value) {
|
||||
const type = typeof value;
|
||||
return value === null || type !== "object" && type !== "function";
|
||||
}
|
||||
function isPureObject(value) {
|
||||
const proto = Object.getPrototypeOf(value);
|
||||
return !proto || proto.isPrototypeOf(Object);
|
||||
}
|
||||
function stringify(value) {
|
||||
if (isPrimitive(value)) {
|
||||
return String(value);
|
||||
}
|
||||
if (isPureObject(value) || Array.isArray(value)) {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
if (typeof value.toJSON === "function") {
|
||||
return stringify(value.toJSON());
|
||||
}
|
||||
throw new Error("[unstorage] Cannot stringify value!");
|
||||
}
|
||||
const BASE64_PREFIX = "base64:";
|
||||
function serializeRaw(value) {
|
||||
if (typeof value === "string") {
|
||||
return value;
|
||||
}
|
||||
return BASE64_PREFIX + base64Encode(value);
|
||||
}
|
||||
function deserializeRaw(value) {
|
||||
if (typeof value !== "string") {
|
||||
return value;
|
||||
}
|
||||
if (!value.startsWith(BASE64_PREFIX)) {
|
||||
return value;
|
||||
}
|
||||
return base64Decode(value.slice(BASE64_PREFIX.length));
|
||||
}
|
||||
function base64Decode(input) {
|
||||
if (globalThis.Buffer) {
|
||||
return Buffer.from(input, "base64");
|
||||
}
|
||||
return Uint8Array.from(
|
||||
globalThis.atob(input),
|
||||
(c) => c.codePointAt(0)
|
||||
);
|
||||
}
|
||||
function base64Encode(input) {
|
||||
if (globalThis.Buffer) {
|
||||
return Buffer.from(input).toString("base64");
|
||||
}
|
||||
return globalThis.btoa(String.fromCodePoint(...input));
|
||||
}
|
||||
|
||||
const storageKeyProperties = [
|
||||
"has",
|
||||
"hasItem",
|
||||
"get",
|
||||
"getItem",
|
||||
"getItemRaw",
|
||||
"set",
|
||||
"setItem",
|
||||
"setItemRaw",
|
||||
"del",
|
||||
"remove",
|
||||
"removeItem",
|
||||
"getMeta",
|
||||
"setMeta",
|
||||
"removeMeta",
|
||||
"getKeys",
|
||||
"clear",
|
||||
"mount",
|
||||
"unmount"
|
||||
];
|
||||
const nonItemKeyProperties = /* @__PURE__ */ new Set([
|
||||
"getKeys",
|
||||
"clear",
|
||||
"mount",
|
||||
"unmount"
|
||||
]);
|
||||
function prefixStorage(storage, base) {
|
||||
if (base?.includes("?")) {
|
||||
throw new Error(`[unstorage] Invalid base: ${JSON.stringify(base)}`);
|
||||
}
|
||||
base = normalizeBaseKey(base);
|
||||
if (!base) {
|
||||
return storage;
|
||||
}
|
||||
const itemKey = (key) => {
|
||||
if (!normalizeKey(key)) {
|
||||
throw new Error(`[unstorage] Invalid key: ${JSON.stringify(key)}`);
|
||||
}
|
||||
return base + key;
|
||||
};
|
||||
const nsStorage = { ...storage };
|
||||
for (const property of storageKeyProperties) {
|
||||
nsStorage[property] = nonItemKeyProperties.has(property) ? (key = "", ...args) => (
|
||||
// @ts-ignore
|
||||
storage[property](base + key, ...args)
|
||||
) : async (key = "", ...args) => (
|
||||
// @ts-ignore
|
||||
storage[property](itemKey(key), ...args)
|
||||
);
|
||||
}
|
||||
nsStorage.getKeys = (key = "", ...arguments_) => storage.getKeys(base + key, ...arguments_).then((keys) => keys.map((key2) => key2.slice(base.length)));
|
||||
nsStorage.keys = nsStorage.getKeys;
|
||||
nsStorage.getItems = async (items, commonOptions) => {
|
||||
const prefixedItems = items.map(
|
||||
(item) => typeof item === "string" ? itemKey(item) : { ...item, key: itemKey(item.key) }
|
||||
);
|
||||
const results = await storage.getItems(prefixedItems, commonOptions);
|
||||
return results.map((entry) => ({
|
||||
key: entry.key.slice(base.length),
|
||||
value: entry.value
|
||||
}));
|
||||
};
|
||||
nsStorage.setItems = async (items, commonOptions) => {
|
||||
const prefixedItems = items.map((item) => ({
|
||||
key: itemKey(item.key),
|
||||
value: item.value,
|
||||
options: item.options
|
||||
}));
|
||||
return storage.setItems(prefixedItems, commonOptions);
|
||||
};
|
||||
return nsStorage;
|
||||
}
|
||||
function normalizeKey(key) {
|
||||
if (!key) {
|
||||
return "";
|
||||
}
|
||||
return key.split("?")[0]?.replace(/[/\\]/g, ":").replace(/:+/g, ":").replace(/^:|:$/g, "") || "";
|
||||
}
|
||||
function hasDotSegment(key) {
|
||||
return key.split(":").some((segment) => segment === "." || segment === "..");
|
||||
}
|
||||
function joinKeys(...keys) {
|
||||
return normalizeKey(keys.join(":"));
|
||||
}
|
||||
function normalizeBaseKey(base) {
|
||||
base = normalizeKey(base);
|
||||
return base ? base + ":" : "";
|
||||
}
|
||||
function filterKeyByDepth(key, depth) {
|
||||
if (depth === void 0) {
|
||||
return true;
|
||||
}
|
||||
let substrCount = 0;
|
||||
let index = key.indexOf(":");
|
||||
while (index > -1) {
|
||||
substrCount++;
|
||||
index = key.indexOf(":", index + 1);
|
||||
}
|
||||
return substrCount <= depth;
|
||||
}
|
||||
function filterKeyByBase(key, base) {
|
||||
if (base) {
|
||||
return key.startsWith(base) && key[key.length - 1] !== "$";
|
||||
}
|
||||
return key[key.length - 1] !== "$";
|
||||
}
|
||||
|
||||
exports.asyncCall = asyncCall;
|
||||
exports.deserializeRaw = deserializeRaw;
|
||||
exports.filterKeyByBase = filterKeyByBase;
|
||||
exports.filterKeyByDepth = filterKeyByDepth;
|
||||
exports.hasDotSegment = hasDotSegment;
|
||||
exports.joinKeys = joinKeys;
|
||||
exports.normalizeBaseKey = normalizeBaseKey;
|
||||
exports.normalizeKey = normalizeKey;
|
||||
exports.prefixStorage = prefixStorage;
|
||||
exports.serializeRaw = serializeRaw;
|
||||
exports.stringify = stringify;
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
type StorageValue = null | string | number | boolean | object;
|
||||
type WatchEvent = "update" | "remove";
|
||||
type WatchCallback = (event: WatchEvent, key: string) => any;
|
||||
type MaybePromise<T> = T | Promise<T>;
|
||||
type MaybeDefined<T> = T extends any ? T : any;
|
||||
type Unwatch = () => MaybePromise<void>;
|
||||
interface StorageMeta {
|
||||
atime?: Date;
|
||||
mtime?: Date;
|
||||
ttl?: number;
|
||||
[key: string]: StorageValue | Date | undefined;
|
||||
}
|
||||
type TransactionOptions = Record<string, any>;
|
||||
type GetKeysOptions = TransactionOptions & {
|
||||
maxDepth?: number;
|
||||
};
|
||||
interface DriverFlags {
|
||||
maxDepth?: boolean;
|
||||
ttl?: boolean;
|
||||
}
|
||||
interface Driver<OptionsT = any, InstanceT = any> {
|
||||
name?: string;
|
||||
flags?: DriverFlags;
|
||||
options?: OptionsT;
|
||||
getInstance?: () => InstanceT;
|
||||
hasItem: (key: string, opts: TransactionOptions) => MaybePromise<boolean>;
|
||||
getItem: (key: string, opts?: TransactionOptions) => MaybePromise<StorageValue>;
|
||||
/** @experimental */
|
||||
getItems?: (items: {
|
||||
key: string;
|
||||
options?: TransactionOptions;
|
||||
}[], commonOptions?: TransactionOptions) => MaybePromise<{
|
||||
key: string;
|
||||
value: StorageValue;
|
||||
}[]>;
|
||||
/** @experimental */
|
||||
getItemRaw?: (key: string, opts: TransactionOptions) => MaybePromise<unknown>;
|
||||
setItem?: (key: string, value: string, opts: TransactionOptions) => MaybePromise<void>;
|
||||
/** @experimental */
|
||||
setItems?: (items: {
|
||||
key: string;
|
||||
value: string;
|
||||
options?: TransactionOptions;
|
||||
}[], commonOptions?: TransactionOptions) => MaybePromise<void>;
|
||||
/** @experimental */
|
||||
setItemRaw?: (key: string, value: any, opts: TransactionOptions) => MaybePromise<void>;
|
||||
removeItem?: (key: string, opts: TransactionOptions) => MaybePromise<void>;
|
||||
getMeta?: (key: string, opts: TransactionOptions) => MaybePromise<StorageMeta | null>;
|
||||
getKeys: (base: string, opts: GetKeysOptions) => MaybePromise<string[]>;
|
||||
clear?: (base: string, opts: TransactionOptions) => MaybePromise<void>;
|
||||
dispose?: () => MaybePromise<void>;
|
||||
watch?: (callback: WatchCallback) => MaybePromise<Unwatch>;
|
||||
}
|
||||
type StorageDefinition = {
|
||||
items: unknown;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
type StorageItemMap<T> = T extends StorageDefinition ? T["items"] : T;
|
||||
type StorageItemType<T, K> = K extends keyof StorageItemMap<T> ? StorageItemMap<T>[K] : T extends StorageDefinition ? StorageValue : T;
|
||||
interface Storage<T extends StorageValue = StorageValue> {
|
||||
hasItem<U extends Extract<T, StorageDefinition>, K extends keyof StorageItemMap<U>>(key: K, opts?: TransactionOptions): Promise<boolean>;
|
||||
hasItem(key: string, opts?: TransactionOptions): Promise<boolean>;
|
||||
getItem<U extends Extract<T, StorageDefinition>, K extends string & keyof StorageItemMap<U>>(key: K, ops?: TransactionOptions): Promise<StorageItemType<T, K> | null>;
|
||||
getItem<R = StorageItemType<T, string>>(key: string, opts?: TransactionOptions): Promise<R | null>;
|
||||
/** @experimental */
|
||||
getItems: <U extends T>(items: (string | {
|
||||
key: string;
|
||||
options?: TransactionOptions;
|
||||
})[], commonOptions?: TransactionOptions) => Promise<{
|
||||
key: string;
|
||||
value: U;
|
||||
}[]>;
|
||||
/** @experimental See https://github.com/unjs/unstorage/issues/142 */
|
||||
getItemRaw: <T = any>(key: string, opts?: TransactionOptions) => Promise<MaybeDefined<T> | null>;
|
||||
setItem<U extends Extract<T, StorageDefinition>, K extends keyof StorageItemMap<U>>(key: K, value: StorageItemType<T, K>, opts?: TransactionOptions): Promise<void>;
|
||||
setItem<U extends T>(key: string, value: U, opts?: TransactionOptions): Promise<void>;
|
||||
/** @experimental */
|
||||
setItems: <U extends T>(items: {
|
||||
key: string;
|
||||
value: U;
|
||||
options?: TransactionOptions;
|
||||
}[], commonOptions?: TransactionOptions) => Promise<void>;
|
||||
/** @experimental See https://github.com/unjs/unstorage/issues/142 */
|
||||
setItemRaw: <T = any>(key: string, value: MaybeDefined<T>, opts?: TransactionOptions) => Promise<void>;
|
||||
removeItem<U extends Extract<T, StorageDefinition>, K extends keyof StorageItemMap<U>>(key: K, opts?: (TransactionOptions & {
|
||||
removeMeta?: boolean;
|
||||
}) | boolean): Promise<void>;
|
||||
removeItem(key: string, opts?: (TransactionOptions & {
|
||||
removeMeta?: boolean;
|
||||
}) | boolean): Promise<void>;
|
||||
getMeta: (key: string, opts?: (TransactionOptions & {
|
||||
nativeOnly?: boolean;
|
||||
}) | boolean) => MaybePromise<StorageMeta>;
|
||||
setMeta: (key: string, value: StorageMeta, opts?: TransactionOptions) => Promise<void>;
|
||||
removeMeta: (key: string, opts?: TransactionOptions) => Promise<void>;
|
||||
getKeys: (base?: string, opts?: GetKeysOptions) => Promise<string[]>;
|
||||
clear: (base?: string, opts?: TransactionOptions) => Promise<void>;
|
||||
dispose: () => Promise<void>;
|
||||
watch: (callback: WatchCallback) => Promise<Unwatch>;
|
||||
unwatch: () => Promise<void>;
|
||||
mount: (base: string, driver: Driver) => Storage;
|
||||
unmount: (base: string, dispose?: boolean) => Promise<void>;
|
||||
getMount: (key?: string) => {
|
||||
base: string;
|
||||
driver: Driver;
|
||||
};
|
||||
getMounts: (base?: string, options?: {
|
||||
parents?: boolean;
|
||||
}) => {
|
||||
base: string;
|
||||
driver: Driver;
|
||||
}[];
|
||||
keys: Storage["getKeys"];
|
||||
get: Storage<T>["getItem"];
|
||||
set: Storage<T>["setItem"];
|
||||
has: Storage<T>["hasItem"];
|
||||
del: Storage<T>["removeItem"];
|
||||
remove: Storage<T>["removeItem"];
|
||||
}
|
||||
|
||||
export type { Driver as D, GetKeysOptions as G, StorageValue as S, TransactionOptions as T, Unwatch as U, WatchCallback as W, Storage as a, DriverFlags as b, StorageMeta as c, WatchEvent as d };
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
type StorageValue = null | string | number | boolean | object;
|
||||
type WatchEvent = "update" | "remove";
|
||||
type WatchCallback = (event: WatchEvent, key: string) => any;
|
||||
type MaybePromise<T> = T | Promise<T>;
|
||||
type MaybeDefined<T> = T extends any ? T : any;
|
||||
type Unwatch = () => MaybePromise<void>;
|
||||
interface StorageMeta {
|
||||
atime?: Date;
|
||||
mtime?: Date;
|
||||
ttl?: number;
|
||||
[key: string]: StorageValue | Date | undefined;
|
||||
}
|
||||
type TransactionOptions = Record<string, any>;
|
||||
type GetKeysOptions = TransactionOptions & {
|
||||
maxDepth?: number;
|
||||
};
|
||||
interface DriverFlags {
|
||||
maxDepth?: boolean;
|
||||
ttl?: boolean;
|
||||
}
|
||||
interface Driver<OptionsT = any, InstanceT = any> {
|
||||
name?: string;
|
||||
flags?: DriverFlags;
|
||||
options?: OptionsT;
|
||||
getInstance?: () => InstanceT;
|
||||
hasItem: (key: string, opts: TransactionOptions) => MaybePromise<boolean>;
|
||||
getItem: (key: string, opts?: TransactionOptions) => MaybePromise<StorageValue>;
|
||||
/** @experimental */
|
||||
getItems?: (items: {
|
||||
key: string;
|
||||
options?: TransactionOptions;
|
||||
}[], commonOptions?: TransactionOptions) => MaybePromise<{
|
||||
key: string;
|
||||
value: StorageValue;
|
||||
}[]>;
|
||||
/** @experimental */
|
||||
getItemRaw?: (key: string, opts: TransactionOptions) => MaybePromise<unknown>;
|
||||
setItem?: (key: string, value: string, opts: TransactionOptions) => MaybePromise<void>;
|
||||
/** @experimental */
|
||||
setItems?: (items: {
|
||||
key: string;
|
||||
value: string;
|
||||
options?: TransactionOptions;
|
||||
}[], commonOptions?: TransactionOptions) => MaybePromise<void>;
|
||||
/** @experimental */
|
||||
setItemRaw?: (key: string, value: any, opts: TransactionOptions) => MaybePromise<void>;
|
||||
removeItem?: (key: string, opts: TransactionOptions) => MaybePromise<void>;
|
||||
getMeta?: (key: string, opts: TransactionOptions) => MaybePromise<StorageMeta | null>;
|
||||
getKeys: (base: string, opts: GetKeysOptions) => MaybePromise<string[]>;
|
||||
clear?: (base: string, opts: TransactionOptions) => MaybePromise<void>;
|
||||
dispose?: () => MaybePromise<void>;
|
||||
watch?: (callback: WatchCallback) => MaybePromise<Unwatch>;
|
||||
}
|
||||
type StorageDefinition = {
|
||||
items: unknown;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
type StorageItemMap<T> = T extends StorageDefinition ? T["items"] : T;
|
||||
type StorageItemType<T, K> = K extends keyof StorageItemMap<T> ? StorageItemMap<T>[K] : T extends StorageDefinition ? StorageValue : T;
|
||||
interface Storage<T extends StorageValue = StorageValue> {
|
||||
hasItem<U extends Extract<T, StorageDefinition>, K extends keyof StorageItemMap<U>>(key: K, opts?: TransactionOptions): Promise<boolean>;
|
||||
hasItem(key: string, opts?: TransactionOptions): Promise<boolean>;
|
||||
getItem<U extends Extract<T, StorageDefinition>, K extends string & keyof StorageItemMap<U>>(key: K, ops?: TransactionOptions): Promise<StorageItemType<T, K> | null>;
|
||||
getItem<R = StorageItemType<T, string>>(key: string, opts?: TransactionOptions): Promise<R | null>;
|
||||
/** @experimental */
|
||||
getItems: <U extends T>(items: (string | {
|
||||
key: string;
|
||||
options?: TransactionOptions;
|
||||
})[], commonOptions?: TransactionOptions) => Promise<{
|
||||
key: string;
|
||||
value: U;
|
||||
}[]>;
|
||||
/** @experimental See https://github.com/unjs/unstorage/issues/142 */
|
||||
getItemRaw: <T = any>(key: string, opts?: TransactionOptions) => Promise<MaybeDefined<T> | null>;
|
||||
setItem<U extends Extract<T, StorageDefinition>, K extends keyof StorageItemMap<U>>(key: K, value: StorageItemType<T, K>, opts?: TransactionOptions): Promise<void>;
|
||||
setItem<U extends T>(key: string, value: U, opts?: TransactionOptions): Promise<void>;
|
||||
/** @experimental */
|
||||
setItems: <U extends T>(items: {
|
||||
key: string;
|
||||
value: U;
|
||||
options?: TransactionOptions;
|
||||
}[], commonOptions?: TransactionOptions) => Promise<void>;
|
||||
/** @experimental See https://github.com/unjs/unstorage/issues/142 */
|
||||
setItemRaw: <T = any>(key: string, value: MaybeDefined<T>, opts?: TransactionOptions) => Promise<void>;
|
||||
removeItem<U extends Extract<T, StorageDefinition>, K extends keyof StorageItemMap<U>>(key: K, opts?: (TransactionOptions & {
|
||||
removeMeta?: boolean;
|
||||
}) | boolean): Promise<void>;
|
||||
removeItem(key: string, opts?: (TransactionOptions & {
|
||||
removeMeta?: boolean;
|
||||
}) | boolean): Promise<void>;
|
||||
getMeta: (key: string, opts?: (TransactionOptions & {
|
||||
nativeOnly?: boolean;
|
||||
}) | boolean) => MaybePromise<StorageMeta>;
|
||||
setMeta: (key: string, value: StorageMeta, opts?: TransactionOptions) => Promise<void>;
|
||||
removeMeta: (key: string, opts?: TransactionOptions) => Promise<void>;
|
||||
getKeys: (base?: string, opts?: GetKeysOptions) => Promise<string[]>;
|
||||
clear: (base?: string, opts?: TransactionOptions) => Promise<void>;
|
||||
dispose: () => Promise<void>;
|
||||
watch: (callback: WatchCallback) => Promise<Unwatch>;
|
||||
unwatch: () => Promise<void>;
|
||||
mount: (base: string, driver: Driver) => Storage;
|
||||
unmount: (base: string, dispose?: boolean) => Promise<void>;
|
||||
getMount: (key?: string) => {
|
||||
base: string;
|
||||
driver: Driver;
|
||||
};
|
||||
getMounts: (base?: string, options?: {
|
||||
parents?: boolean;
|
||||
}) => {
|
||||
base: string;
|
||||
driver: Driver;
|
||||
}[];
|
||||
keys: Storage["getKeys"];
|
||||
get: Storage<T>["getItem"];
|
||||
set: Storage<T>["setItem"];
|
||||
has: Storage<T>["hasItem"];
|
||||
del: Storage<T>["removeItem"];
|
||||
remove: Storage<T>["removeItem"];
|
||||
}
|
||||
|
||||
export type { Driver as D, GetKeysOptions as G, StorageValue as S, TransactionOptions as T, Unwatch as U, WatchCallback as W, Storage as a, DriverFlags as b, StorageMeta as c, WatchEvent as d };
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
type StorageValue = null | string | number | boolean | object;
|
||||
type WatchEvent = "update" | "remove";
|
||||
type WatchCallback = (event: WatchEvent, key: string) => any;
|
||||
type MaybePromise<T> = T | Promise<T>;
|
||||
type MaybeDefined<T> = T extends any ? T : any;
|
||||
type Unwatch = () => MaybePromise<void>;
|
||||
interface StorageMeta {
|
||||
atime?: Date;
|
||||
mtime?: Date;
|
||||
ttl?: number;
|
||||
[key: string]: StorageValue | Date | undefined;
|
||||
}
|
||||
type TransactionOptions = Record<string, any>;
|
||||
type GetKeysOptions = TransactionOptions & {
|
||||
maxDepth?: number;
|
||||
};
|
||||
interface DriverFlags {
|
||||
maxDepth?: boolean;
|
||||
ttl?: boolean;
|
||||
}
|
||||
interface Driver<OptionsT = any, InstanceT = any> {
|
||||
name?: string;
|
||||
flags?: DriverFlags;
|
||||
options?: OptionsT;
|
||||
getInstance?: () => InstanceT;
|
||||
hasItem: (key: string, opts: TransactionOptions) => MaybePromise<boolean>;
|
||||
getItem: (key: string, opts?: TransactionOptions) => MaybePromise<StorageValue>;
|
||||
/** @experimental */
|
||||
getItems?: (items: {
|
||||
key: string;
|
||||
options?: TransactionOptions;
|
||||
}[], commonOptions?: TransactionOptions) => MaybePromise<{
|
||||
key: string;
|
||||
value: StorageValue;
|
||||
}[]>;
|
||||
/** @experimental */
|
||||
getItemRaw?: (key: string, opts: TransactionOptions) => MaybePromise<unknown>;
|
||||
setItem?: (key: string, value: string, opts: TransactionOptions) => MaybePromise<void>;
|
||||
/** @experimental */
|
||||
setItems?: (items: {
|
||||
key: string;
|
||||
value: string;
|
||||
options?: TransactionOptions;
|
||||
}[], commonOptions?: TransactionOptions) => MaybePromise<void>;
|
||||
/** @experimental */
|
||||
setItemRaw?: (key: string, value: any, opts: TransactionOptions) => MaybePromise<void>;
|
||||
removeItem?: (key: string, opts: TransactionOptions) => MaybePromise<void>;
|
||||
getMeta?: (key: string, opts: TransactionOptions) => MaybePromise<StorageMeta | null>;
|
||||
getKeys: (base: string, opts: GetKeysOptions) => MaybePromise<string[]>;
|
||||
clear?: (base: string, opts: TransactionOptions) => MaybePromise<void>;
|
||||
dispose?: () => MaybePromise<void>;
|
||||
watch?: (callback: WatchCallback) => MaybePromise<Unwatch>;
|
||||
}
|
||||
type StorageDefinition = {
|
||||
items: unknown;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
type StorageItemMap<T> = T extends StorageDefinition ? T["items"] : T;
|
||||
type StorageItemType<T, K> = K extends keyof StorageItemMap<T> ? StorageItemMap<T>[K] : T extends StorageDefinition ? StorageValue : T;
|
||||
interface Storage<T extends StorageValue = StorageValue> {
|
||||
hasItem<U extends Extract<T, StorageDefinition>, K extends keyof StorageItemMap<U>>(key: K, opts?: TransactionOptions): Promise<boolean>;
|
||||
hasItem(key: string, opts?: TransactionOptions): Promise<boolean>;
|
||||
getItem<U extends Extract<T, StorageDefinition>, K extends string & keyof StorageItemMap<U>>(key: K, ops?: TransactionOptions): Promise<StorageItemType<T, K> | null>;
|
||||
getItem<R = StorageItemType<T, string>>(key: string, opts?: TransactionOptions): Promise<R | null>;
|
||||
/** @experimental */
|
||||
getItems: <U extends T>(items: (string | {
|
||||
key: string;
|
||||
options?: TransactionOptions;
|
||||
})[], commonOptions?: TransactionOptions) => Promise<{
|
||||
key: string;
|
||||
value: U;
|
||||
}[]>;
|
||||
/** @experimental See https://github.com/unjs/unstorage/issues/142 */
|
||||
getItemRaw: <T = any>(key: string, opts?: TransactionOptions) => Promise<MaybeDefined<T> | null>;
|
||||
setItem<U extends Extract<T, StorageDefinition>, K extends keyof StorageItemMap<U>>(key: K, value: StorageItemType<T, K>, opts?: TransactionOptions): Promise<void>;
|
||||
setItem<U extends T>(key: string, value: U, opts?: TransactionOptions): Promise<void>;
|
||||
/** @experimental */
|
||||
setItems: <U extends T>(items: {
|
||||
key: string;
|
||||
value: U;
|
||||
options?: TransactionOptions;
|
||||
}[], commonOptions?: TransactionOptions) => Promise<void>;
|
||||
/** @experimental See https://github.com/unjs/unstorage/issues/142 */
|
||||
setItemRaw: <T = any>(key: string, value: MaybeDefined<T>, opts?: TransactionOptions) => Promise<void>;
|
||||
removeItem<U extends Extract<T, StorageDefinition>, K extends keyof StorageItemMap<U>>(key: K, opts?: (TransactionOptions & {
|
||||
removeMeta?: boolean;
|
||||
}) | boolean): Promise<void>;
|
||||
removeItem(key: string, opts?: (TransactionOptions & {
|
||||
removeMeta?: boolean;
|
||||
}) | boolean): Promise<void>;
|
||||
getMeta: (key: string, opts?: (TransactionOptions & {
|
||||
nativeOnly?: boolean;
|
||||
}) | boolean) => MaybePromise<StorageMeta>;
|
||||
setMeta: (key: string, value: StorageMeta, opts?: TransactionOptions) => Promise<void>;
|
||||
removeMeta: (key: string, opts?: TransactionOptions) => Promise<void>;
|
||||
getKeys: (base?: string, opts?: GetKeysOptions) => Promise<string[]>;
|
||||
clear: (base?: string, opts?: TransactionOptions) => Promise<void>;
|
||||
dispose: () => Promise<void>;
|
||||
watch: (callback: WatchCallback) => Promise<Unwatch>;
|
||||
unwatch: () => Promise<void>;
|
||||
mount: (base: string, driver: Driver) => Storage;
|
||||
unmount: (base: string, dispose?: boolean) => Promise<void>;
|
||||
getMount: (key?: string) => {
|
||||
base: string;
|
||||
driver: Driver;
|
||||
};
|
||||
getMounts: (base?: string, options?: {
|
||||
parents?: boolean;
|
||||
}) => {
|
||||
base: string;
|
||||
driver: Driver;
|
||||
}[];
|
||||
keys: Storage["getKeys"];
|
||||
get: Storage<T>["getItem"];
|
||||
set: Storage<T>["setItem"];
|
||||
has: Storage<T>["hasItem"];
|
||||
del: Storage<T>["removeItem"];
|
||||
remove: Storage<T>["removeItem"];
|
||||
}
|
||||
|
||||
export type { Driver as D, GetKeysOptions as G, StorageValue as S, TransactionOptions as T, Unwatch as U, WatchCallback as W, Storage as a, DriverFlags as b, StorageMeta as c, WatchEvent as d };
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
function wrapToPromise(value) {
|
||||
if (!value || typeof value.then !== "function") {
|
||||
return Promise.resolve(value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
function asyncCall(function_, ...arguments_) {
|
||||
try {
|
||||
return wrapToPromise(function_(...arguments_));
|
||||
} catch (error) {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
}
|
||||
function isPrimitive(value) {
|
||||
const type = typeof value;
|
||||
return value === null || type !== "object" && type !== "function";
|
||||
}
|
||||
function isPureObject(value) {
|
||||
const proto = Object.getPrototypeOf(value);
|
||||
return !proto || proto.isPrototypeOf(Object);
|
||||
}
|
||||
function stringify(value) {
|
||||
if (isPrimitive(value)) {
|
||||
return String(value);
|
||||
}
|
||||
if (isPureObject(value) || Array.isArray(value)) {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
if (typeof value.toJSON === "function") {
|
||||
return stringify(value.toJSON());
|
||||
}
|
||||
throw new Error("[unstorage] Cannot stringify value!");
|
||||
}
|
||||
const BASE64_PREFIX = "base64:";
|
||||
function serializeRaw(value) {
|
||||
if (typeof value === "string") {
|
||||
return value;
|
||||
}
|
||||
return BASE64_PREFIX + base64Encode(value);
|
||||
}
|
||||
function deserializeRaw(value) {
|
||||
if (typeof value !== "string") {
|
||||
return value;
|
||||
}
|
||||
if (!value.startsWith(BASE64_PREFIX)) {
|
||||
return value;
|
||||
}
|
||||
return base64Decode(value.slice(BASE64_PREFIX.length));
|
||||
}
|
||||
function base64Decode(input) {
|
||||
if (globalThis.Buffer) {
|
||||
return Buffer.from(input, "base64");
|
||||
}
|
||||
return Uint8Array.from(
|
||||
globalThis.atob(input),
|
||||
(c) => c.codePointAt(0)
|
||||
);
|
||||
}
|
||||
function base64Encode(input) {
|
||||
if (globalThis.Buffer) {
|
||||
return Buffer.from(input).toString("base64");
|
||||
}
|
||||
return globalThis.btoa(String.fromCodePoint(...input));
|
||||
}
|
||||
|
||||
const storageKeyProperties = [
|
||||
"has",
|
||||
"hasItem",
|
||||
"get",
|
||||
"getItem",
|
||||
"getItemRaw",
|
||||
"set",
|
||||
"setItem",
|
||||
"setItemRaw",
|
||||
"del",
|
||||
"remove",
|
||||
"removeItem",
|
||||
"getMeta",
|
||||
"setMeta",
|
||||
"removeMeta",
|
||||
"getKeys",
|
||||
"clear",
|
||||
"mount",
|
||||
"unmount"
|
||||
];
|
||||
const nonItemKeyProperties = /* @__PURE__ */ new Set([
|
||||
"getKeys",
|
||||
"clear",
|
||||
"mount",
|
||||
"unmount"
|
||||
]);
|
||||
function prefixStorage(storage, base) {
|
||||
if (base?.includes("?")) {
|
||||
throw new Error(`[unstorage] Invalid base: ${JSON.stringify(base)}`);
|
||||
}
|
||||
base = normalizeBaseKey(base);
|
||||
if (!base) {
|
||||
return storage;
|
||||
}
|
||||
const itemKey = (key) => {
|
||||
if (!normalizeKey(key)) {
|
||||
throw new Error(`[unstorage] Invalid key: ${JSON.stringify(key)}`);
|
||||
}
|
||||
return base + key;
|
||||
};
|
||||
const nsStorage = { ...storage };
|
||||
for (const property of storageKeyProperties) {
|
||||
nsStorage[property] = nonItemKeyProperties.has(property) ? (key = "", ...args) => (
|
||||
// @ts-ignore
|
||||
storage[property](base + key, ...args)
|
||||
) : async (key = "", ...args) => (
|
||||
// @ts-ignore
|
||||
storage[property](itemKey(key), ...args)
|
||||
);
|
||||
}
|
||||
nsStorage.getKeys = (key = "", ...arguments_) => storage.getKeys(base + key, ...arguments_).then((keys) => keys.map((key2) => key2.slice(base.length)));
|
||||
nsStorage.keys = nsStorage.getKeys;
|
||||
nsStorage.getItems = async (items, commonOptions) => {
|
||||
const prefixedItems = items.map(
|
||||
(item) => typeof item === "string" ? itemKey(item) : { ...item, key: itemKey(item.key) }
|
||||
);
|
||||
const results = await storage.getItems(prefixedItems, commonOptions);
|
||||
return results.map((entry) => ({
|
||||
key: entry.key.slice(base.length),
|
||||
value: entry.value
|
||||
}));
|
||||
};
|
||||
nsStorage.setItems = async (items, commonOptions) => {
|
||||
const prefixedItems = items.map((item) => ({
|
||||
key: itemKey(item.key),
|
||||
value: item.value,
|
||||
options: item.options
|
||||
}));
|
||||
return storage.setItems(prefixedItems, commonOptions);
|
||||
};
|
||||
return nsStorage;
|
||||
}
|
||||
function normalizeKey(key) {
|
||||
if (!key) {
|
||||
return "";
|
||||
}
|
||||
return key.split("?")[0]?.replace(/[/\\]/g, ":").replace(/:+/g, ":").replace(/^:|:$/g, "") || "";
|
||||
}
|
||||
function hasDotSegment(key) {
|
||||
return key.split(":").some((segment) => segment === "." || segment === "..");
|
||||
}
|
||||
function joinKeys(...keys) {
|
||||
return normalizeKey(keys.join(":"));
|
||||
}
|
||||
function normalizeBaseKey(base) {
|
||||
base = normalizeKey(base);
|
||||
return base ? base + ":" : "";
|
||||
}
|
||||
function filterKeyByDepth(key, depth) {
|
||||
if (depth === void 0) {
|
||||
return true;
|
||||
}
|
||||
let substrCount = 0;
|
||||
let index = key.indexOf(":");
|
||||
while (index > -1) {
|
||||
substrCount++;
|
||||
index = key.indexOf(":", index + 1);
|
||||
}
|
||||
return substrCount <= depth;
|
||||
}
|
||||
function filterKeyByBase(key, base) {
|
||||
if (base) {
|
||||
return key.startsWith(base) && key[key.length - 1] !== "$";
|
||||
}
|
||||
return key[key.length - 1] !== "$";
|
||||
}
|
||||
|
||||
export { normalizeKey as a, asyncCall as b, filterKeyByBase as c, stringify as d, deserializeRaw as e, filterKeyByDepth as f, hasDotSegment as h, joinKeys as j, normalizeBaseKey as n, prefixStorage as p, serializeRaw as s };
|
||||
Reference in New Issue
Block a user