-
Notifications
You must be signed in to change notification settings - Fork 1
/
kv.ts
194 lines (177 loc) · 4.55 KB
/
kv.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
// deno-lint-ignore-file no-explicit-any
import { JSONc, path, TOML, YAML } from "./deps.ts";
import { z } from "./z.ts";
/**
* Add a type-safe key-value store to your CLI context. This is useful for
* storing things like authentication tokens and other values that you want to
* persist between CLI invocations.
*
* @param schema - The schema for the key-value store.
* @param options - Configuration options
*/
export function kv<Schema extends z.ZodRawShape>(
/**
* The schema for the key-value store.
*/
schema: Schema,
options: KvOptions = {},
): Kv<Schema> {
const execPath = Deno.execPath();
const basename = path.basename(execPath, path.extname(execPath));
const name = basename === "deno" ? "zcli-dev" : basename;
const { path: userKvPath, format = "toml", mode = 0o600 } = options;
const defaultKvPath = path.join(
Deno.env.get("HOME")!,
`.${name}`,
`kv.${format}`,
);
const kvPath = userKvPath ?? defaultKvPath;
const kvDir = path.dirname(kvPath);
const parser = parsers[format];
let cached:
| Record<
string,
{
value: unknown;
expires: number;
}
>
| undefined;
async function write(kv: typeof cached = {}) {
try {
Deno.statSync(kvDir);
} catch (_err) {
await Deno.mkdir(kvDir, { recursive: true });
}
await Deno.writeTextFile(kvPath, parser.stringify(kv), {
mode,
});
cached = kv;
}
async function read(): Promise<Exclude<typeof cached, undefined>> {
try {
Deno.statSync(kvPath);
} catch (_err) {
return {};
}
const kv = parser.parse(await Deno.readTextFile(kvPath));
// @ts-expect-error: all good
return (cached = kv);
}
async function get(key?: any): Promise<any> {
async function _get(obj: any, key?: any) {
const cachedValue = key ? obj[key] : obj;
if (key && cachedValue && !isExpired(cachedValue as any)) {
try {
return schema[key].parseAsync(cachedValue.value);
} catch (_err) {
return undefined;
}
} else if (!key) {
return Object.fromEntries(
(
await Promise.all(
Object.entries(
cachedValue as Exclude<typeof cached, undefined>,
).filter(async ([key, val]) => {
if (isExpired(val)) {
return false;
}
const parsedValue = await schema[key].safeParseAsync(val.value);
return parsedValue.success;
}),
)
).map(([key, val]) => [key, val.value]),
);
}
}
if (cached) {
return _get(cached, key);
}
const kv = await read();
return _get(kv, key);
}
return {
async set(key, value, ttl) {
const kv = await get();
kv[key] = {
value: await schema[key].parseAsync(value),
expires: ttl !== undefined ? Date.now() + ttl * 1000 : -1,
};
await write(kv);
},
get,
async delete(key) {
const kv = await get();
delete kv[key];
await write(kv);
},
async clear() {
await write();
},
};
}
const parsers = {
jsonc: {
stringify: (value: unknown) => JSON.stringify(value, null, 2),
parse: JSONc.parse,
},
yaml: YAML,
toml: TOML,
} as const;
function isExpired({ expires }: { expires: number; value: unknown }): boolean {
return expires !== -1 && Date.now() > expires;
}
export type KvOptions = {
/**
* The path to the key-value file.
* @default "$HOME/.<name>/kv.<format>"
*/
path?: string;
/**
* @default "toml"
*/
format?: "jsonc" | "yaml" | "toml";
/**
* The write mode for the kv file.
* @default 0o600
*/
mode?: number;
};
export type Kv<
Schema extends z.ZodRawShape,
Inferred extends z.infer<z.ZodObject<Schema>> = z.infer<z.ZodObject<Schema>>,
> = {
/**
* Set a value in the key-value store.
*
* @param key The key to set.
* @param value The value to set.
* @param ttl The time to live in seconds.
*/
set<Key extends keyof Inferred>(
key: Key,
value: Inferred[Key],
ttl?: number,
): Promise<void>;
/**
* Get a value from the key-value-store.
*
* @param key The key to get.
*/
get<Key extends keyof Inferred>(key: Key): Promise<Inferred[Key]>;
/**
* Get the entire kv.
*/
get(): Promise<Inferred>;
/**
* Delete a value from the key-value store.
*
* @param key The key to delete.
*/
delete<Key extends keyof Inferred>(key: Key): Promise<void>;
/**
* Clear the entire kev-value store.
*/
clear(): Promise<void>;
};