Skip to content

Commit

Permalink
chore: apply new lint rules
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed May 1, 2024
1 parent 7b8c51e commit be542fc
Show file tree
Hide file tree
Showing 34 changed files with 74 additions and 70 deletions.
2 changes: 1 addition & 1 deletion demo/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export default defineConfig({
configureServer(server) {
const storage = createStorage();
const storageServer = createStorageServer(storage);
// eslint-disable-next-line unicorn/prefer-module

storage.mount("/src", fsdriver({ base: resolve(__dirname, "..") }));
server.middlewares.use("/storage", storageServer.handle);
},
Expand Down
2 changes: 1 addition & 1 deletion src/_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export function stringify(value: any): string {
}

function checkBufferSupport() {
if (typeof Buffer === undefined) {
if (typeof Buffer === "undefined") {
throw new TypeError("[unstorage] Buffer is not supported!");
}
}
Expand Down
2 changes: 0 additions & 2 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ async function main() {
const arguments_ = mri(process.argv.splice(2));

if (arguments_.help) {
// eslint-disable-next-line no-console
console.log("Usage: npx unstorage [rootDir]");
// eslint-disable-next-line unicorn/no-process-exit
process.exit(0);
Expand All @@ -31,7 +30,6 @@ async function main() {

// eslint-disable-next-line unicorn/prefer-top-level-await
main().catch((error) => {
// eslint-disable-next-line no-console
console.error(error);
// eslint-disable-next-line unicorn/no-process-exit
process.exit(1);
Expand Down
2 changes: 1 addition & 1 deletion src/drivers/azure-key-vault.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ function encode(value: string): string {
let encoded = Buffer.from(value).toString("base64");
for (const key in base64Map) {
encoded = encoded.replace(
new RegExp(key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"),
new RegExp(key.replace(/[$()*+.?[\\\]^{|}]/g, "\\$&"), "g"),
base64Map[key]
);
}
Expand Down
2 changes: 2 additions & 0 deletions src/drivers/azure-storage-blob.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,9 @@ async function blobToString(blob: Blob) {
fileReader.onloadend = (ev) => {
resolve(ev.target?.result);
};
// eslint-disable-next-line unicorn/prefer-add-event-listener
fileReader.onerror = reject;
// eslint-disable-next-line unicorn/prefer-blob-reading-methods
fileReader.readAsText(blob);
});
}
20 changes: 10 additions & 10 deletions src/drivers/cloudflare-kv-http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,9 @@ export default defineDriver<KVHTTPOptions>((opts) => {
}

const firstPage = await kvFetch("/keys", { params });
firstPage.result.forEach(({ name }: { name: string }) => keys.push(name));
for (const item of firstPage.result as { name: string }[]) {
keys.push(item.name);
}

const cursor = firstPage.result_info.cursor;
if (cursor) {
Expand All @@ -166,25 +168,23 @@ export default defineDriver<KVHTTPOptions>((opts) => {

while (params.cursor) {
const pageResult = await kvFetch("/keys", { params });
pageResult.result.forEach(({ name }: { name: string }) =>
keys.push(name)
);
const pageCursor = pageResult.result_info.cursor;
if (pageCursor) {
params.cursor = pageCursor;
} else {
params.cursor = undefined;
for (const item of pageResult.result as { name: string }[]) {
keys.push(item.name);
}
const pageCursor = pageResult.result_info.cursor;
params.cursor = pageCursor ? pageCursor : undefined;
}
return keys;
};

const clear = async () => {
const keys: string[] = await getKeys();
// Split into chunks of 10000, as the API only allows for 10,000 keys at a time
// TODO: Avoid reduce
// eslint-disable-next-line unicorn/no-array-reduce
const chunks = keys.reduce<string[][]>(
(acc, key, i) => {
if (i % 10000 === 0) {
if (i % 10_000 === 0) {
acc.push([]);
}
acc[acc.length - 1].push(key);
Expand Down
2 changes: 1 addition & 1 deletion src/drivers/cloudflare-r2-binding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export default defineDriver((opts: CloudflareR2Options = {}) => {
const binding = getR2Binding(opts.binding);
return (await binding.head(key)) !== null;
},
async getMeta(key, topts) {
async getMeta(key) {
key = r(key);
const binding = getR2Binding(opts.binding);
const obj = await binding.head(key);
Expand Down
7 changes: 3 additions & 4 deletions src/drivers/fs-lite.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { existsSync, promises as fsp, Stats } from "fs";
import { resolve, join } from "path";
import { existsSync, promises as fsp, Stats } from "node:fs";
import { resolve, join } from "node:path";
import { createError, createRequiredError, defineDriver } from "./utils";
import {
readFile,
Expand All @@ -8,7 +8,6 @@ import {
rmRecursive,
unlink,
} from "./utils/node-fs";
import anymatch from "anymatch";

export interface FSStorageOptions {
base?: string;
Expand All @@ -17,7 +16,7 @@ export interface FSStorageOptions {
noClear?: boolean;
}

const PATH_TRAVERSE_RE = /\.\.\:|\.\.$/;
const PATH_TRAVERSE_RE = /\.\.:|\.\.$/;

const DRIVER_NAME = "fs-lite";

Expand Down
6 changes: 3 additions & 3 deletions src/drivers/fs.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { existsSync, promises as fsp, Stats } from "fs";
import { resolve, relative, join } from "path";
import { existsSync, promises as fsp, Stats } from "node:fs";
import { resolve, relative, join } from "node:path";
import { FSWatcher, WatchOptions, watch } from "chokidar";
import { createError, createRequiredError, defineDriver } from "./utils";
import {
Expand All @@ -19,7 +19,7 @@ export interface FSStorageOptions {
watchOptions?: WatchOptions;
}

const PATH_TRAVERSE_RE = /\.\.\:|\.\.$/;
const PATH_TRAVERSE_RE = /\.\.:|\.\.$/;

const DRIVER_NAME = "fs";

Expand Down
4 changes: 1 addition & 3 deletions src/drivers/github.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,9 +149,7 @@ async function fetchFiles(opts: GithubOptions) {
if (node.type !== "blob" || !node.path.startsWith(prefix)) {
continue;
}
const key: string = node.path
.substring(prefix.length)
.replace(/\//g, ":");
const key: string = node.path.slice(prefix.length).replace(/\//g, ":");
files[key] = {
meta: {
sha: node.sha,
Expand Down
2 changes: 1 addition & 1 deletion src/drivers/indexedb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export default defineDriver((opts: IDBKeyvalOptions = {}) => {
options: opts,
async hasItem(key) {
const item = await get(makeKey(key), customStore);
return typeof item === "undefined" ? false : true;
return item === undefined ? false : true;
},
async getItem(key) {
const item = await get(makeKey(key), customStore);
Expand Down
8 changes: 4 additions & 4 deletions src/drivers/localstorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const DRIVER_NAME = "localstorage";

export default defineDriver((opts: LocalStorageOptions = {}) => {
if (!opts.window) {
opts.window = typeof window !== "undefined" ? window : undefined;
opts.window = typeof window === "undefined" ? undefined : window;
}
if (!opts.localStorage) {
opts.localStorage = opts.window?.localStorage;
Expand Down Expand Up @@ -48,12 +48,12 @@ export default defineDriver((opts: LocalStorageOptions = {}) => {
return Object.keys(opts.localStorage!);
},
clear() {
if (!opts.base) {
opts.localStorage!.clear();
} else {
if (opts.base) {
for (const key of Object.keys(opts.localStorage!)) {
opts.localStorage?.removeItem(key);
}
} else {
opts.localStorage!.clear();
}
if (opts.window && _storageListener) {
opts.window.removeEventListener("storage", _storageListener);
Expand Down
12 changes: 8 additions & 4 deletions src/drivers/lru-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export default defineDriver((opts: LRUDriverOptions = {}) => {
cache.delete(key);
},
getKeys() {
return Array.from(cache.keys());
return [...cache.keys()];
},
clear() {
cache.clear();
Expand All @@ -56,15 +56,19 @@ export default defineDriver((opts: LRUDriverOptions = {}) => {
});

function byteLength(value: any) {
if (typeof Buffer !== undefined) {
if (typeof Buffer !== "undefined") {
try {
return Buffer.byteLength(value);
} catch {}
} catch {
// ignore
}
}
try {
return typeof value === "string"
? value.length
: JSON.stringify(value).length;
} catch {}
} catch {
// ignore
}
return 0;
}
2 changes: 1 addition & 1 deletion src/drivers/memory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export default defineDriver<void>(() => {
data.delete(key);
},
getKeys() {
return Array.from(data.keys());
return [...data.keys()];
},
clear() {
data.clear();
Expand Down
11 changes: 6 additions & 5 deletions src/drivers/overlay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@ export default defineDriver((options: OverlayStorageOptions) => {
async hasItem(key, opts) {
for (const layer of options.layers) {
if (await layer.hasItem(key, opts)) {
if (layer === options.layers[0]) {
if ((await options.layers[0]?.getItem(key)) === OVERLAY_REMOVED) {
return false;
}
if (
layer === options.layers[0] &&
(await options.layers[0]?.getItem(key)) === OVERLAY_REMOVED
) {
return false;
}
return true;
}
Expand Down Expand Up @@ -54,7 +55,7 @@ export default defineDriver((options: OverlayStorageOptions) => {
return keys.map((key) => normalizeKey(key));
})
);
const uniqueKeys = Array.from(new Set(allKeys.flat()));
const uniqueKeys = [...new Set(allKeys.flat())];
const existingKeys = await Promise.all(
uniqueKeys.map(async (key) => {
if ((await options.layers[0]?.getItem(key)) === OVERLAY_REMOVED) {
Expand Down
2 changes: 1 addition & 1 deletion src/drivers/planetscale.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createError, createRequiredError, defineDriver } from "./utils";
import { createRequiredError, defineDriver } from "./utils";
import type { ExecutedQuery, Connection } from "@planetscale/database";
import { connect } from "@planetscale/database";
import { fetch } from "node-fetch-native";
Expand Down
2 changes: 1 addition & 1 deletion src/drivers/redis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export default defineDriver((opts: RedisOptions = {}) => {
return value ?? null;
},
async setItem(key, value, tOptions) {
let ttl = tOptions?.ttl ?? opts.ttl;
const ttl = tOptions?.ttl ?? opts.ttl;
if (ttl) {
await getRedisClient().set(p(key), value, "EX", ttl);
} else {
Expand Down
10 changes: 5 additions & 5 deletions src/drivers/session-storage.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createError, createRequiredError, defineDriver } from "./utils";
import { createRequiredError, defineDriver } from "./utils";

export interface SessionStorageOptions {
base?: string;
Expand All @@ -10,7 +10,7 @@ const DRIVER_NAME = "session-storage";

export default defineDriver((opts: SessionStorageOptions = {}) => {
if (!opts.window) {
opts.window = typeof window !== "undefined" ? window : undefined;
opts.window = typeof window === "undefined" ? undefined : window;
}
if (!opts.sessionStorage) {
opts.sessionStorage = opts.window?.sessionStorage;
Expand Down Expand Up @@ -48,12 +48,12 @@ export default defineDriver((opts: SessionStorageOptions = {}) => {
return Object.keys(opts.sessionStorage!);
},
clear() {
if (!opts.base) {
opts.sessionStorage!.clear();
} else {
if (opts.base) {
for (const key of Object.keys(opts.sessionStorage!)) {
opts.sessionStorage?.removeItem(key);
}
} else {
opts.sessionStorage!.clear();
}
if (opts.window && _storageListener) {
opts.window.removeEventListener("storage", _storageListener);
Expand Down
5 changes: 4 additions & 1 deletion src/drivers/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@ export function normalizeKey(key: string | undefined): string {
}

export function joinKeys(...keys: string[]) {
return keys.map(normalizeKey).filter(Boolean).join(":");
return keys
.map((key) => normalizeKey(key))
.filter(Boolean)
.join(":");
}

export function createError(
Expand Down
4 changes: 2 additions & 2 deletions src/drivers/utils/node-fs.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Dirent, existsSync, promises as fsPromises } from "fs";
import { resolve, dirname } from "path";
import { Dirent, existsSync, promises as fsPromises } from "node:fs";
import { resolve, dirname } from "node:path";

function ignoreNotfound(err: any) {
return err.code === "ENOENT" || err.code === "EISDIR" ? null : err;
Expand Down
2 changes: 1 addition & 1 deletion src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export interface StorageServerOptions {

export function createH3StorageHandler(
storage: Storage,
// eslint-disable-next-line @typescript-eslint/no-unused-vars

opts: StorageServerOptions = {}
): EventHandler {
return eventHandler(async (event) => {
Expand Down
2 changes: 1 addition & 1 deletion src/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,7 @@ export function createStorage<T extends StorageValue>(
.then((unwatcher) => {
context.unwatch[base] = unwatcher;
})
.catch(console.error); // eslint-disable-line no-console
.catch(console.error);
}
return storage;
},
Expand Down
2 changes: 1 addition & 1 deletion test/drivers/azure-key-vault.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@ describe.skip(
driver: driver({ vaultName: "testunstoragevault" }),
});
},
{ timeout: 80000 }
{ timeout: 80_000 }
); // 60s as the Azure Key Vault need to delete and purge the secret before it can be created again.
4 changes: 2 additions & 2 deletions test/drivers/azure-storage-blob.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { describe, beforeAll, afterAll } from "vitest";
import driver from "../../src/drivers/azure-storage-blob";
import { testDriver } from "./utils";
import { BlobServiceClient } from "@azure/storage-blob";
import { ChildProcess, exec } from "child_process";
import { ChildProcess, exec } from "node:child_process";

describe.skip("drivers: azure-storage-blob", () => {
let azuriteProcess: ChildProcess;
Expand Down
4 changes: 2 additions & 2 deletions test/drivers/azure-storage-table.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { describe, beforeAll, afterAll } from "vitest";
import driver from "../../src/drivers/azure-storage-table";
import { testDriver } from "./utils";
import { TableClient } from "@azure/data-tables";
import { ChildProcess, exec } from "child_process";
import { ChildProcess, exec } from "node:child_process";

describe.skip("drivers: azure-storage-table", () => {
let azuriteProcess: ChildProcess;
Expand Down
2 changes: 1 addition & 1 deletion test/drivers/capacitor-preferences.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { afterEach } from "node:test";
vi.mock("@capacitor/preferences", () => {
const data = new Map<string, string>();

const keys = vi.fn(() => Promise.resolve({ keys: Array.from(data.keys()) }));
const keys = vi.fn(() => Promise.resolve({ keys: [...data.keys()] }));
const get = vi.fn(({ key }) =>
Promise.resolve({ value: data.get(key) ?? null })
);
Expand Down
2 changes: 1 addition & 1 deletion test/drivers/cloudflare-kv-binding.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const mockBinding: KVNamespace = {
describe("drivers: cloudflare-kv", () => {
testDriver({
driver: CloudflareKVBinding({ binding: mockBinding, base: "base" }),
async additionalTests(ctx) {
async additionalTests() {
test("snapshot", async () => {
expect(await snapshot(mockStorage, "")).toMatchInlineSnapshot(`
{
Expand Down
Loading

0 comments on commit be542fc

Please sign in to comment.