@ix-xs/node-comfort 1.1.31 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +190 -0
  2. package/LICENSE +21 -0
  3. package/README.md +210 -748
  4. package/index.js +84 -13
  5. package/package.json +201 -21
  6. package/src/Arr.js +901 -0
  7. package/src/Async.js +585 -0
  8. package/src/Cache.js +329 -0
  9. package/src/Checker.js +979 -188
  10. package/src/Cli.js +1034 -0
  11. package/src/Color.js +415 -0
  12. package/src/Crypto.js +707 -0
  13. package/src/Emitter.js +289 -0
  14. package/src/Env.js +555 -0
  15. package/src/FS.js +1483 -768
  16. package/src/Func.js +692 -0
  17. package/src/Http.js +538 -0
  18. package/src/Id.js +418 -0
  19. package/src/Logger.js +739 -307
  20. package/src/Num.js +849 -0
  21. package/src/Obj.js +904 -0
  22. package/src/SQLite.js +1308 -994
  23. package/src/Schema.js +1586 -0
  24. package/src/Str.js +999 -0
  25. package/src/Sys.js +511 -0
  26. package/src/Time.js +1323 -0
  27. package/src/Utils.js +321 -325
  28. package/src/errors.js +292 -0
  29. package/types/index.d.ts +693 -120
  30. package/types/src/Arr.d.ts +562 -0
  31. package/types/src/Arr.d.ts.map +1 -0
  32. package/types/src/Async.d.ts +321 -0
  33. package/types/src/Async.d.ts.map +1 -0
  34. package/types/src/Cache.d.ts +195 -0
  35. package/types/src/Cache.d.ts.map +1 -0
  36. package/types/src/Checker.d.ts +609 -81
  37. package/types/src/Checker.d.ts.map +1 -1
  38. package/types/src/Cli.d.ts +582 -0
  39. package/types/src/Cli.d.ts.map +1 -0
  40. package/types/src/Color.d.ts +294 -0
  41. package/types/src/Color.d.ts.map +1 -0
  42. package/types/src/Crypto.d.ts +534 -0
  43. package/types/src/Crypto.d.ts.map +1 -0
  44. package/types/src/Emitter.d.ts +170 -0
  45. package/types/src/Emitter.d.ts.map +1 -0
  46. package/types/src/Env.d.ts +382 -0
  47. package/types/src/Env.d.ts.map +1 -0
  48. package/types/src/FS.d.ts +709 -201
  49. package/types/src/FS.d.ts.map +1 -1
  50. package/types/src/Func.d.ts +455 -0
  51. package/types/src/Func.d.ts.map +1 -0
  52. package/types/src/Http.d.ts +374 -0
  53. package/types/src/Http.d.ts.map +1 -0
  54. package/types/src/Id.d.ts +200 -0
  55. package/types/src/Id.d.ts.map +1 -0
  56. package/types/src/Logger.d.ts +374 -24
  57. package/types/src/Logger.d.ts.map +1 -1
  58. package/types/src/Num.d.ts +578 -0
  59. package/types/src/Num.d.ts.map +1 -0
  60. package/types/src/Obj.d.ts +475 -0
  61. package/types/src/Obj.d.ts.map +1 -0
  62. package/types/src/SQLite.d.ts +647 -305
  63. package/types/src/SQLite.d.ts.map +1 -1
  64. package/types/src/Schema.d.ts +940 -0
  65. package/types/src/Schema.d.ts.map +1 -0
  66. package/types/src/Str.d.ts +696 -0
  67. package/types/src/Str.d.ts.map +1 -0
  68. package/types/src/Sys.d.ts +269 -0
  69. package/types/src/Sys.d.ts.map +1 -0
  70. package/types/src/Time.d.ts +664 -0
  71. package/types/src/Time.d.ts.map +1 -0
  72. package/types/src/Utils.d.ts +154 -102
  73. package/types/src/Utils.d.ts.map +1 -1
  74. package/types/src/errors.d.ts +292 -0
  75. package/types/src/errors.d.ts.map +1 -0
  76. package/tsconfig.json +0 -18
  77. package/types/index.d.ts.map +0 -1
package/types/index.d.ts CHANGED
@@ -1,120 +1,693 @@
1
- declare const _exports: {
2
- SQLite: {
3
- new (path?: string): SQLite;
4
- };
5
- wait(ms: number): Promise<void>;
6
- when(predicate: boolean | Promise<boolean> | (() => boolean | Promise<boolean>), payload?: any, options?: {
7
- interval?: number | undefined;
8
- timeout?: number | null | undefined;
9
- max?: number | null | undefined;
10
- }): {
11
- start: () => any;
12
- stop: () => any;
13
- on: <E extends "error" | "trigger" | "timeout">(event: E, handler: E extends "error" ? (error: unknown) => void | Promise<void> : (payload: any) => void | Promise<void>) => any;
14
- };
15
- dontCrash(): {
16
- on: <E extends "error" | "exit" | "sig" | "beforeExit">(event: E, handler?: (E extends "error" ? (error: Error | unknown) => void | Promise<void> : E extends "exit" ? (code: number) => void | Promise<void> : E extends "sig" ? (signal: "SIGINT" | "SIGTERM" | "SIGQUIT") => void | Promise<void> : (code: number) => void | Promise<void>)) => any;
17
- };
18
- JSONString(value: any): string;
19
- JSONParse(value: string): any;
20
- isArray(value: any): boolean;
21
- isNumber(value: any): boolean;
22
- isFunction(value: any): boolean;
23
- isObject(value: any): boolean;
24
- isBoolean(value: any): boolean;
25
- isString(value: any): boolean;
26
- isUndefined(value: any): boolean;
27
- isNull(value: any): boolean;
28
- isDate(value: any): boolean;
29
- isMap(value: any): boolean;
30
- isSet(value: any): boolean;
31
- isError(value: any): boolean;
32
- getEnv(value: string, envFilePath?: string): string | undefined;
33
- createPath(path?: string): string;
34
- getFoldersIn(path?: string, recursive?: boolean): string[] | undefined;
35
- getFolder(path?: string): string | undefined;
36
- getFilesIn(path?: string, recursive?: boolean): string[] | undefined;
37
- getFile(path: string): string | undefined;
38
- createFolder(path: string, force?: boolean): boolean | undefined;
39
- createFile(path: string, force?: boolean, data?: string | object | null | undefined): boolean | undefined;
40
- deleteFoldersIn(path?: string, filter?: (folder: string) => boolean): number | undefined;
41
- deleteFolder(path: string): boolean | undefined;
42
- deleteFilesIn(path?: string, recursive?: boolean, filter?: (file: string) => boolean): number | undefined;
43
- deleteFile(path: string): boolean | undefined;
44
- copyFoldersIn(options: {
45
- dest: string;
46
- path?: string | undefined;
47
- recursive?: boolean | undefined;
48
- withFiles?: boolean | undefined;
49
- force?: boolean | undefined;
50
- filter?: ((folder: string) => boolean) | undefined;
51
- }): number | undefined;
52
- copyFolder(options: {
53
- dest: string;
54
- path?: string | undefined;
55
- recursive?: boolean | undefined;
56
- withFiles?: boolean | undefined;
57
- force?: boolean | undefined;
58
- }): boolean | undefined;
59
- copyFilesIn(options: {
60
- dest: string;
61
- path?: string | undefined;
62
- recursive?: boolean | undefined;
63
- force?: boolean | undefined;
64
- filter?: ((file: string) => boolean) | undefined;
65
- }): number | undefined;
66
- copyFile(options: {
67
- path: string;
68
- dest: string;
69
- force?: boolean | undefined;
70
- }): boolean | undefined;
71
- moveFoldersIn(options: {
72
- dest: string;
73
- path?: string | undefined;
74
- recursive?: boolean | undefined;
75
- withFiles?: boolean | undefined;
76
- force?: boolean | undefined;
77
- filter?: ((folder: string) => boolean) | undefined;
78
- }): number | undefined;
79
- moveFolder(options: {
80
- path: string;
81
- dest: string;
82
- recursive?: boolean | undefined;
83
- withFiles?: boolean | undefined;
84
- force?: boolean | undefined;
85
- }): boolean | undefined;
86
- moveFilesIn(options: {
87
- dest: string;
88
- path?: string | undefined;
89
- recursive?: boolean | undefined;
90
- force?: boolean | undefined;
91
- filter?: ((file: string) => boolean) | undefined;
92
- }): number | undefined;
93
- moveFile(options: {
94
- path: string;
95
- dest: string;
96
- force?: boolean | undefined;
97
- }): boolean | undefined;
98
- readFile(path: string): string | undefined;
99
- watch(options?: {
100
- path?: string | undefined;
101
- recursive?: boolean | undefined;
102
- filter?: ((event: "rename" | "change", file: string) => boolean) | undefined;
103
- }): {
104
- on: <E extends "change" | "rename" | "all">(event: E, callback: E extends "all" ? (event: "change" | "rename", file: string) => void | Promise<void> : (file: string) => void | Promise<void>) => any;
105
- stop: () => void;
106
- pause: () => any;
107
- resume: () => any;
108
- } | undefined;
109
- setTimestamp(value: boolean): Logger;
110
- setDelimiter(options?: {
111
- open?: string | undefined;
112
- close?: string | undefined;
113
- }): Logger;
114
- log(content: any): Logger;
115
- group(label: string): Logger;
116
- groupEnd(): Logger;
117
- };
118
- export = _exports;
119
- import SQLite = require("./src/SQLite");
120
- //# sourceMappingURL=index.d.ts.map
1
+ // Generated by scripts/build-types.js. Do not edit by hand.
2
+ // @ix-xs/node-comfort v2.0.0
3
+
4
+ import _Arr = require("./src/Arr");
5
+ import _Async = require("./src/Async");
6
+ import _Cache = require("./src/Cache");
7
+ import _Checker = require("./src/Checker");
8
+ import _Cli = require("./src/Cli");
9
+ import _Color = require("./src/Color");
10
+ import _Crypto = require("./src/Crypto");
11
+ import _Emitter = require("./src/Emitter");
12
+ import _Env = require("./src/Env");
13
+ import _errors = require("./src/errors");
14
+ import _FS = require("./src/FS");
15
+ import _Func = require("./src/Func");
16
+ import _Http = require("./src/Http");
17
+ import _Id = require("./src/Id");
18
+ import _Logger = require("./src/Logger");
19
+ import _Num = require("./src/Num");
20
+ import _Obj = require("./src/Obj");
21
+ import _Schema = require("./src/Schema");
22
+ import _SQLite = require("./src/SQLite");
23
+ import _Str = require("./src/Str");
24
+ import _Sys = require("./src/Sys");
25
+ import _Time = require("./src/Time");
26
+ import _Utils = require("./src/Utils");
27
+
28
+ /**
29
+ * **@ix-xs/node-comfort**: The zero-dependency standard library for Node.js: logger, filesystem, SQLite, schema validation, HTTP client, CLI toolkit, cache, env, async pools, colors, events, i18n dates, ids, crypto and hundreds of fully typed helpers.
30
+ *
31
+ * @example
32
+ * const nc = require("@ix-xs/node-comfort");
33
+ * nc.info("Server ready");
34
+ * nc.str.slugify("Héllo World"); // "hello-world"
35
+ *
36
+ * @example
37
+ * import { nc, slugify, isEmail } from "@ix-xs/node-comfort";
38
+ */
39
+ declare namespace nodeComfort {
40
+
41
+ // Namespaces and classes
42
+ /**
43
+ * A console logger that works with zero setup: levels, colors, a small
44
+ * markup for styling, groups, timers and tables. In production, switch to
45
+ * one JSON object per line with `LOG_FORMAT=json`, and write to rotating
46
+ * files if you need to.
47
+ *
48
+ * Markup: `<% red bold Error:%> disk is full`. Any style name works, plus
49
+ * `#ff8800`, `bg#1e1e2e`, `rgb(255, 128, 0)` and `bgRgb(...)`.
50
+ *
51
+ * Levels, from chatty to severe: `trace`, `debug`, `info`, `warn`, `error`,
52
+ * `fatal`. The default is `info`, or `debug` when `DEBUG` is set; `LOG_LEVEL`
53
+ * overrides it. Warnings and errors go to stderr.
54
+ *
55
+ * @example
56
+ * nc.info("Server listening on port 3000");
57
+ * nc.warn("Cache is almost full");
58
+ * nc.error(new Error("Payment failed", { cause: err }));
59
+ * nc.log("<% cyan bold Tip:%> press <% bgWhite black q %> to quit");
60
+ */
61
+ export import logger = _Logger;
62
+ /**
63
+ * Files and folders without try/catch: read and write text or JSON
64
+ * (atomically), copy, move, delete, list, glob, watch, hash.
65
+ *
66
+ * Paths: absolute paths are used as they are. Paths starting with `./` or
67
+ * `../` start from the file that calls the function, so a script works
68
+ * wherever it's run from. Other relative paths start from the working
69
+ * directory, like Node's `fs`.
70
+ *
71
+ * Everyday failures don't throw: you get `undefined` when something doesn't
72
+ * exist and `false` when an operation fails.
73
+ *
74
+ * @example
75
+ * nc.writeJSON("./data/settings.json", { theme: "dark" });
76
+ * const settings = nc.readJSON("./data/settings.json", {});
77
+ * const sources = nc.glob("src/**\/*.{js,ts}");
78
+ */
79
+ export import fs = _FS;
80
+ /**
81
+ * Type checks and validators. Every `isX` accepts anything and never throws,
82
+ * and most of them are type guards: inside `if (nc.isString(value))`, your
83
+ * editor knows `value` is a string, in JavaScript too.
84
+ *
85
+ * @example
86
+ * if (nc.isEmail(body.email) && nc.isPort(body.port)) connect(body);
87
+ * nc.assert(user, "User not found");
88
+ */
89
+ export import checker = _Checker;
90
+ /**
91
+ * Everyday helpers: `wait`, `when`, `dontCrash`, and JSON functions that
92
+ * don't throw. They are also available at the top level (`nc.wait()`).
93
+ *
94
+ * @example
95
+ * await nc.wait("1.5s");
96
+ * const settings = nc.JSONParse(text, {});
97
+ */
98
+ export import utils = _Utils;
99
+ /**
100
+ * String helpers: case conversion, slugs, truncation, templates, wrapping,
101
+ * fuzzy matching, plurals. Nothing is mutated, any value is accepted, and
102
+ * lengths are counted the way you see them, so 👨‍👩‍👧 is one character and
103
+ * is never cut in half.
104
+ *
105
+ * @example
106
+ * str.slugify("Héllo, Wörld!"); // "hello-world"
107
+ * str.camelCase("user_first-name"); // "userFirstName"
108
+ * str.plural(3, { one: "file", other: "files" }); // "3 files"
109
+ */
110
+ export import str = _Str;
111
+ /**
112
+ * Numbers: clamping, rounding that gets decimals right, statistics, and
113
+ * formatting for humans (sizes, money, ordinals, compact numbers) in any
114
+ * language. Formatting is English by default: change it with `setLocale()`
115
+ * or per call with `{ locale }`.
116
+ *
117
+ * @example
118
+ * num.round(1.005, 2); // 1.01
119
+ * num.formatBytes(1536); // "1.5 KB"
120
+ * num.currency(1234.5, "EUR", { locale: "fr" }); // "1 234,50 €"
121
+ * num.percentile(latencies, 95);
122
+ */
123
+ export import num = _Num;
124
+ /**
125
+ * Array helpers. None of them mutate what you pass in, and item types carry
126
+ * through (`chunk(numbers, 2)` is a `number[][]`). Many take an iteratee:
127
+ * a property name, which your editor completes, or a function.
128
+ *
129
+ * @example
130
+ * arr.chunk([1, 2, 3, 4, 5], 2); // [[1, 2], [3, 4], [5]]
131
+ * arr.groupBy(users, "role"); // { admin: [...], user: [...] }
132
+ * arr.sortBy(users, ["lastName", "age"]);
133
+ */
134
+ export import arr = _Arr;
135
+ /**
136
+ * Object helpers: deep clone, merge, equality, diff, typed dot paths,
137
+ * pick and omit. Inputs are never mutated, and `__proto__`, `constructor`
138
+ * and `prototype` keys are always ignored, so user input can't pollute
139
+ * prototypes.
140
+ *
141
+ * @example
142
+ * obj.get(config, "db.pool.max", 10); // typed, paths autocompleted
143
+ * obj.set(state, "user.profile.name", "Ada"); // returns an updated copy
144
+ * obj.merge(defaults, userConfig);
145
+ */
146
+ export import obj = _Obj;
147
+ /**
148
+ * Function helpers: debounce, throttle, memoize, retry with backoff,
149
+ * timeouts, error handling without try/catch, and typed composition.
150
+ *
151
+ * @example
152
+ * const save = func.debounce(persist, 300);
153
+ * const data = await func.retry(() => fetchJSON(url), { attempts: 5, delay: 200, backoff: 2 });
154
+ * const [error, user] = await func.to(getUser(id));
155
+ */
156
+ export import func = _Func;
157
+ /**
158
+ * Dates and durations: formatting, relative time, calendar math, time zones
159
+ * and scheduling, in any language `Intl` knows. The default language is
160
+ * English so results are the same on every machine; change it with
161
+ * `setLocale()` or per call with `{ locale }`. Time zones work the same way
162
+ * with `setTimezone()` or `{ timeZone }`.
163
+ *
164
+ * @example
165
+ * time.setLocale("fr").setTimezone("Europe/Paris");
166
+ * time.relative(Date.now() - 3600e3); // "il y a 1 heure"
167
+ * time.format(new Date(), "dddd D MMMM YYYY"); // "lundi 15 janvier 2024"
168
+ * time.cron("0 9 * * 1-5", sendReport); // weekdays at 9:00
169
+ */
170
+ export import time = _Time;
171
+ /**
172
+ * Unique ids: UUID v4 and v7, ULID, nanoid-style ids, Snowflakes, tokens
173
+ * and short codes. All of them use the secure random generator of
174
+ * `node:crypto`, with no bias.
175
+ *
176
+ * @example
177
+ * id.uuidv7(); // "0190a5c4-7c1e-7b2a-9f3e-1c2d3e4f5a6b", sorts by creation time
178
+ * id.nano(); // "V1StGXR8_Z5jdHi6B-myT"
179
+ * id.code(); // "K7QF9X"
180
+ * id.token(32); // for API keys and reset links
181
+ */
182
+ export import id = _Id;
183
+ /**
184
+ * Crypto without the footguns, built on `node:crypto`: hashes, HMAC,
185
+ * password hashing (scrypt), encryption (AES-256-GCM), JWT, two-factor
186
+ * codes (TOTP) and secure random values.
187
+ *
188
+ * @example
189
+ * const stored = await crypto.hashPassword("hunter2");
190
+ * await crypto.verifyPassword("hunter2", stored); // true
191
+ *
192
+ * const token = crypto.signJWT({ sub: user.id }, SECRET, { expiresIn: "1h" });
193
+ * const claims = crypto.verifyJWT(token, SECRET);
194
+ */
195
+ export import crypto = _Crypto;
196
+ /**
197
+ * Terminal colors you can chain, like `chalk`. Truecolor is supported and
198
+ * downgraded on older terminals. Colors switch off by themselves when the
199
+ * output isn't a terminal or `NO_COLOR` is set; `FORCE_COLOR=1|2|3` turns
200
+ * them back on.
201
+ *
202
+ * @example
203
+ * console.log(color.green.bold("✔ Done"), color.gray("in 1.2s"));
204
+ * console.log(color.bgHex("#1e1e2e").hex("#cba6f7")(" nc "));
205
+ * console.log(color.gradient("node-comfort", ["#ff5f6d", "#ffc371"]));
206
+ */
207
+ export import color = _Color;
208
+ /**
209
+ * What you need for command-line tools: typed arguments with a generated
210
+ * `--help`, prompts, arrow-key menus, spinners, progress bars, tables and
211
+ * boxes. When nobody's at the keyboard (CI, pipes), prompts read plain lines
212
+ * and animations print only their final state.
213
+ *
214
+ * @example
215
+ * const { flags } = cli.args({
216
+ * port: { type: "number", short: "p", default: 3000, description: "Port to listen on" },
217
+ * });
218
+ * const name = await cli.prompt("Project name?", { default: "my-app" });
219
+ * const spin = cli.spinner("Installing").start();
220
+ * spin.succeed("Installed");
221
+ */
222
+ export import cli = _Cli;
223
+ /**
224
+ * Processes and the system: run commands and get their output, find
225
+ * executables, shut down cleanly, open URLs, and learn about the machine.
226
+ * Behaves the same on Windows, macOS and Linux; on Windows,
227
+ * `run("npm", [...])` finds `npm.cmd` and escapes arguments safely.
228
+ *
229
+ * @example
230
+ * const { stdout } = await sys.run("git", ["rev-parse", "HEAD"]);
231
+ * sys.onShutdown(async () => {
232
+ * await server.close();
233
+ * await db.close();
234
+ * });
235
+ */
236
+ export import sys = _Sys;
237
+ /**
238
+ * Promises and concurrency: map with a limit, queues with priorities,
239
+ * mutexes, polling, and friendlier `Promise.allSettled`.
240
+ *
241
+ * @example
242
+ * const pages = await async.map(urls, (url) => fetchPage(url), { concurrency: 5 });
243
+ *
244
+ * const limit = async.limit(2);
245
+ * await Promise.all(files.map((file) => limit(() => upload(file))));
246
+ *
247
+ * await async.poll(() => isServerReady(), { interval: 250, timeout: "10s" });
248
+ */
249
+ export import async = _Async;
250
+ /**
251
+ * Validate data with schemas, in the spirit of `zod`. Describe your data
252
+ * once and get both a runtime check with clear messages and the TypeScript
253
+ * type, `Infer<typeof schema>`. Schemas never change: `.min()` or
254
+ * `.optional()` return a new one.
255
+ *
256
+ * @example
257
+ * const User = s.object({
258
+ * name: s.string().trim().min(2),
259
+ * email: s.string().email().toLowerCase(),
260
+ * age: s.number().int().min(18).optional(),
261
+ * role: s.enum(["admin", "user"]).default("user"),
262
+ * });
263
+ *
264
+ * const user = User.parse(req.body); // typed, or a ValidationError listing every issue
265
+ * const result = User.safeParse(input); // { success, data } or { success, error }
266
+ */
267
+ export import schema = _Schema;
268
+ /**
269
+ * An HTTP client on top of `fetch`: JSON by default, query objects, base
270
+ * URLs, timeouts, safe retries that respect `Retry-After`, typed errors,
271
+ * hooks, reusable clients and downloads with progress.
272
+ *
273
+ * @example
274
+ * const { data } = await http.get("https://api.github.com/repos/nodejs/node");
275
+ *
276
+ * const api = http.create({ baseURL: "https://api.example.com/v1/", auth: { bearer: process.env.TOKEN } });
277
+ * const { data: users } = await api.get("users", { query: { page: 2 } });
278
+ */
279
+ export import http = _Http;
280
+ /**
281
+ * Environment variables you can trust: `.env` loading, typed getters, and
282
+ * `validate()` to check your whole configuration at startup and report
283
+ * every problem at once.
284
+ *
285
+ * The `.env` file in the working directory is loaded when the package is
286
+ * required; variables that are already set are never overwritten. Set
287
+ * `NODE_COMFORT_DOTENV=false` to turn that off.
288
+ *
289
+ * @example
290
+ * const config = env.validate({
291
+ * PORT: { type: "port", default: 3000 },
292
+ * DATABASE_URL: { type: "url" }, // required
293
+ * CACHE_TTL: { type: "duration", default: "5m" }, // in ms
294
+ * });
295
+ * config.PORT; // a number, typed in your editor
296
+ */
297
+ export import env = _Env;
298
+ /**
299
+ * The errors node-comfort throws. They all extend `NodeComfortError` (itself
300
+ * a regular `Error`) and carry a stable `code`, so you can branch on the
301
+ * kind of failure without parsing messages.
302
+ *
303
+ * @example
304
+ * try {
305
+ * await nc.http.get("https://api.example.com/users/42");
306
+ * } catch (error) {
307
+ * if (error instanceof nc.errors.HttpError && error.status === 404) return null;
308
+ * throw error;
309
+ * }
310
+ */
311
+ export import errors = _errors;
312
+ /**
313
+ * SQLite made pleasant, on the engine built into Node.js (22.13+): CRUD with
314
+ * rich filters, JSON and boolean columns, transactions, migrations and
315
+ * backups. Methods are synchronous, like the engine, but `await` still
316
+ * works. Errors are `SQLiteError`s. Values are always bound as parameters
317
+ * and names are checked, so there's no SQL injection through them.
318
+ *
319
+ * @example
320
+ * const db = new nc.SQLite("data/app.sqlite");
321
+ * db.createTable({
322
+ * name: "users",
323
+ * columns: {
324
+ * id: { type: "INTEGER", primaryKey: true, autoincrement: true },
325
+ * email: { type: "TEXT", notNull: true, unique: true },
326
+ * settings: { type: "JSON", defaultValue: {} },
327
+ * },
328
+ * });
329
+ * db.insert("users", { email: "ada@example.com", settings: { theme: "dark" } });
330
+ * db.getAll("users", { email: { like: "%@example.com" } }, { orderBy: "email", limit: 20 });
331
+ */
332
+ export import SQLite = _SQLite;
333
+ /**
334
+ * An in-memory cache with a size limit (the least recently used entries go
335
+ * first), expiry per entry, and stats. `getOrSet()` loads a missing value
336
+ * only once, even when many callers ask for it at the same moment.
337
+ *
338
+ * @example
339
+ * const users = new nc.Cache({ max: 1000, ttl: "5m" });
340
+ * const user = await users.getOrSet(id, () => db.users.find(id));
341
+ * users.stats; // { hits: 12, misses: 3, hitRate: 0.8, ... }
342
+ */
343
+ export import Cache = _Cache;
344
+ /**
345
+ * A small typed event emitter. Declare your events once, and your editor
346
+ * checks every event name and listener argument. `on()` returns a function
347
+ * that removes the listener, and you can `await` an event or loop over
348
+ * events with `for await`.
349
+ *
350
+ * @example
351
+ * const chat = new nc.Emitter<{ message: [text: string, from: string]; close: [] }>();
352
+ * const off = chat.on("message", (text, from) => console.log(`${from}: ${text}`));
353
+ * chat.emit("message", "hello", "ada");
354
+ * off();
355
+ * const [text] = await chat.waitFor("message", { timeout: "5s" });
356
+ */
357
+ export import Emitter = _Emitter;
358
+
359
+ // Flat helpers (logger, fs, checker, utils)
360
+ export import log = _Logger.log;
361
+ export import trace = _Logger.trace;
362
+ export import debug = _Logger.debug;
363
+ export import info = _Logger.info;
364
+ export import success = _Logger.success;
365
+ export import warn = _Logger.warn;
366
+ export import error = _Logger.error;
367
+ export import fatal = _Logger.fatal;
368
+ export import group = _Logger.group;
369
+ export import groupEnd = _Logger.groupEnd;
370
+ export import timeStart = _Logger.timeStart;
371
+ export import timeEnd = _Logger.timeEnd;
372
+ export import table = _Logger.table;
373
+ export import box = _Logger.box;
374
+ export import divider = _Logger.divider;
375
+ export import setLevel = _Logger.setLevel;
376
+ export import getLevel = _Logger.getLevel;
377
+ export import isLevelEnabled = _Logger.isLevelEnabled;
378
+ export import configure = _Logger.configure;
379
+ export import setTimestamp = _Logger.setTimestamp;
380
+ export import setDelimiter = _Logger.setDelimiter;
381
+ export import createLogger = _Logger.createLogger;
382
+ export import getEnv = _FS.getEnv;
383
+ export import createPath = _FS.createPath;
384
+ export import getFolder = _FS.getFolder;
385
+ export import getFile = _FS.getFile;
386
+ export import getFoldersIn = _FS.getFoldersIn;
387
+ export import getFilesIn = _FS.getFilesIn;
388
+ export import glob = _FS.glob;
389
+ export import find = _FS.find;
390
+ export import readFile = _FS.readFile;
391
+ export import readLines = _FS.readLines;
392
+ export import readJSON = _FS.readJSON;
393
+ export import writeFile = _FS.writeFile;
394
+ export import writeJSON = _FS.writeJSON;
395
+ export import appendFile = _FS.appendFile;
396
+ export import createFile = _FS.createFile;
397
+ export import createFolder = _FS.createFolder;
398
+ export import ensureFolder = _FS.ensureFolder;
399
+ export import ensureFile = _FS.ensureFile;
400
+ export import touch = _FS.touch;
401
+ export import deleteFolder = _FS.deleteFolder;
402
+ export import deleteFile = _FS.deleteFile;
403
+ export import remove = _FS.remove;
404
+ export import deleteFoldersIn = _FS.deleteFoldersIn;
405
+ export import deleteFilesIn = _FS.deleteFilesIn;
406
+ export import emptyFolder = _FS.emptyFolder;
407
+ export import copy = _FS.copy;
408
+ export import move = _FS.move;
409
+ export import copyFoldersIn = _FS.copyFoldersIn;
410
+ export import copyFolder = _FS.copyFolder;
411
+ export import copyFilesIn = _FS.copyFilesIn;
412
+ export import copyFile = _FS.copyFile;
413
+ export import moveFoldersIn = _FS.moveFoldersIn;
414
+ export import moveFolder = _FS.moveFolder;
415
+ export import moveFilesIn = _FS.moveFilesIn;
416
+ export import moveFile = _FS.moveFile;
417
+ export import exists = _FS.exists;
418
+ export import isFile = _FS.isFile;
419
+ export import isFolder = _FS.isFolder;
420
+ export import stat = _FS.stat;
421
+ export import fileSize = _FS.fileSize;
422
+ export import folderSize = _FS.folderSize;
423
+ export import hashFile = _FS.hashFile;
424
+ export import tempFolder = _FS.tempFolder;
425
+ export import sanitizeFilename = _FS.sanitizeFilename;
426
+ export import watch = _FS.watch;
427
+ export import isArray = _Checker.isArray;
428
+ export import isNumber = _Checker.isNumber;
429
+ export import isFinite = _Checker.isFinite;
430
+ export import isInteger = _Checker.isInteger;
431
+ export import isSafeInteger = _Checker.isSafeInteger;
432
+ export import isFloat = _Checker.isFloat;
433
+ export import isPositive = _Checker.isPositive;
434
+ export import isNegative = _Checker.isNegative;
435
+ export import isBoolean = _Checker.isBoolean;
436
+ export import isString = _Checker.isString;
437
+ export import isSymbol = _Checker.isSymbol;
438
+ export import isBigInt = _Checker.isBigInt;
439
+ export import isUndefined = _Checker.isUndefined;
440
+ export import isNull = _Checker.isNull;
441
+ export import isNil = _Checker.isNil;
442
+ export import isDefined = _Checker.isDefined;
443
+ export import isPrimitive = _Checker.isPrimitive;
444
+ export import isFunction = _Checker.isFunction;
445
+ export import isAsyncFunction = _Checker.isAsyncFunction;
446
+ export import isGeneratorFunction = _Checker.isGeneratorFunction;
447
+ export import isGenerator = _Checker.isGenerator;
448
+ export import isClass = _Checker.isClass;
449
+ export import isObject = _Checker.isObject;
450
+ export import isPlainObject = _Checker.isPlainObject;
451
+ export import isPromise = _Checker.isPromise;
452
+ export import isRegExp = _Checker.isRegExp;
453
+ export import isDate = _Checker.isDate;
454
+ export import isValidDate = _Checker.isValidDate;
455
+ export import isMap = _Checker.isMap;
456
+ export import isSet = _Checker.isSet;
457
+ export import isWeakMap = _Checker.isWeakMap;
458
+ export import isWeakSet = _Checker.isWeakSet;
459
+ export import isIterable = _Checker.isIterable;
460
+ export import isAsyncIterable = _Checker.isAsyncIterable;
461
+ export import isBuffer = _Checker.isBuffer;
462
+ export import isTypedArray = _Checker.isTypedArray;
463
+ export import isError = _Checker.isError;
464
+ export import isEmpty = _Checker.isEmpty;
465
+ export import isBlank = _Checker.isBlank;
466
+ export import isArrayOf = _Checker.isArrayOf;
467
+ export import isOneOf = _Checker.isOneOf;
468
+ export import isEmail = _Checker.isEmail;
469
+ export import isURL = _Checker.isURL;
470
+ export import isUUID = _Checker.isUUID;
471
+ export import isJSON = _Checker.isJSON;
472
+ export import isNumeric = _Checker.isNumeric;
473
+ export import isIP = _Checker.isIP;
474
+ export import isIPv4 = _Checker.isIPv4;
475
+ export import isIPv6 = _Checker.isIPv6;
476
+ export import isPort = _Checker.isPort;
477
+ export import isHex = _Checker.isHex;
478
+ export import isHexColor = _Checker.isHexColor;
479
+ export import isBase64 = _Checker.isBase64;
480
+ export import isSemver = _Checker.isSemver;
481
+ export import isISODate = _Checker.isISODate;
482
+ export import isSlug = _Checker.isSlug;
483
+ export import isAlpha = _Checker.isAlpha;
484
+ export import isAlphanumeric = _Checker.isAlphanumeric;
485
+ export import isCreditCard = _Checker.isCreditCard;
486
+ export import isJWT = _Checker.isJWT;
487
+ export import assert = _Checker.assert;
488
+ export import assertType = _Checker.assertType;
489
+ export import wait = _Utils.wait;
490
+ export import when = _Utils.when;
491
+ export import dontCrash = _Utils.dontCrash;
492
+ export import JSONString = _Utils.JSONString;
493
+ export import JSONParse = _Utils.JSONParse;
494
+
495
+ // Types
496
+ export import AnyTypedArray = _Checker.AnyTypedArray;
497
+ export import ArgsOptions = _Cli.ArgsOptions;
498
+ export import BorderStyle = _Cli.BorderStyle;
499
+ export import BoxOptions = _Cli.BoxOptions;
500
+ export import CacheOptions = _Cache.CacheOptions;
501
+ export import CacheRemovalReason = _Cache.CacheRemovalReason;
502
+ export import CacheSetOptions = _Cache.CacheSetOptions;
503
+ export import CacheStats = _Cache.CacheStats;
504
+ export import CalendarOptions = _Time.CalendarOptions;
505
+ export import CalendarUnit = _Time.CalendarUnit;
506
+ export import Change = _Obj.Change;
507
+ export import ChangeResult = _SQLite.ChangeResult;
508
+ export import Choice = _Cli.Choice;
509
+ export import ClosestOptions = _Str.ClosestOptions;
510
+ export import CoerceBuilders = _Schema.CoerceBuilders;
511
+ export import ColorChain = _Color.ColorChain;
512
+ export import ColorHelpers = _Color.ColorHelpers;
513
+ export import ColorLevel = _Color.ColorLevel;
514
+ export import ColorMethods = _Color.ColorMethods;
515
+ export import ColorModule = _Color.ColorModule;
516
+ export import ColorStyleProps = _Color.ColorStyleProps;
517
+ export import ColorStyles = _Color.ColorStyles;
518
+ export import ColumnDefinition = _SQLite.ColumnDefinition;
519
+ export import ColumnInfo = _SQLite.ColumnInfo;
520
+ export import ColumnType = _SQLite.ColumnType;
521
+ export import CompactOptions = _Obj.CompactOptions;
522
+ export import CompareOptions = _Str.CompareOptions;
523
+ export import ConfirmOptions = _Cli.ConfirmOptions;
524
+ export import CopyFileOptions = _FS.CopyFileOptions;
525
+ export import CopyFilesOptions = _FS.CopyFilesOptions;
526
+ export import CopyFolderOptions = _FS.CopyFolderOptions;
527
+ export import CopyFoldersOptions = _FS.CopyFoldersOptions;
528
+ export import CopyOptions = _FS.CopyOptions;
529
+ export import CronOptions = _Time.CronOptions;
530
+ export import CronSpec = _Time.CronSpec;
531
+ export import CurrencyOptions = _Num.CurrencyOptions;
532
+ export import DateInput = _Time.DateInput;
533
+ export import DebouncedFunction = _Func.DebouncedFunction;
534
+ export import DebounceOptions = _Func.DebounceOptions;
535
+ export import DecodedJWT = _Crypto.DecodedJWT;
536
+ export import DecryptOptions = _Crypto.DecryptOptions;
537
+ export import DeepReadonly = _Obj.DeepReadonly;
538
+ export import Deferred = _Async.Deferred;
539
+ export import DigestEncoding = _Crypto.DigestEncoding;
540
+ export import DontCrashController = _Utils.DontCrashController;
541
+ export import DontCrashEvent = _Utils.DontCrashEvent;
542
+ export import DurationUnit = _Time.DurationUnit;
543
+ export import EncryptOptions = _Crypto.EncryptOptions;
544
+ export import EnvConfig = _Env.EnvConfig;
545
+ export import EnvGetterOptions = _Env.EnvGetterOptions;
546
+ export import EnvLoadOptions = _Env.EnvLoadOptions;
547
+ export import EnvParseOptions = _Env.EnvParseOptions;
548
+ export import EnvVarSpec = _Env.EnvVarSpec;
549
+ export import EnvVarValue = _Env.EnvVarValue;
550
+ export import EventMap = _Emitter.EventMap;
551
+ export import EveryOptions = _Time.EveryOptions;
552
+ export import FindOptions = _FS.FindOptions;
553
+ export import FlagSpec = _Cli.FlagSpec;
554
+ export import FlagValue = _Cli.FlagValue;
555
+ export import ForeignKeyAction = _SQLite.ForeignKeyAction;
556
+ export import FormatBytesOptions = _Num.FormatBytesOptions;
557
+ export import FormatDateOptions = _Time.FormatDateOptions;
558
+ export import FormatDurationOptions = _Time.FormatDurationOptions;
559
+ export import FormatNumberOptions = _Num.FormatNumberOptions;
560
+ export import GlobOptions = _FS.GlobOptions;
561
+ export import HashOptions = _Crypto.HashOptions;
562
+ export import HashPasswordOptions = _Crypto.HashPasswordOptions;
563
+ export import HttpBody = _Http.HttpBody;
564
+ export import HttpClient = _Http.HttpClient;
565
+ export import HttpHooks = _Http.HttpHooks;
566
+ export import HttpMethod = _Http.HttpMethod;
567
+ export import HttpOptions = _Http.HttpOptions;
568
+ export import HttpRequestConfig = _Http.HttpRequestConfig;
569
+ export import HttpResponse = _Http.HttpResponse;
570
+ export import HttpRetryOptions = _Http.HttpRetryOptions;
571
+ export import IndexDefinition = _SQLite.IndexDefinition;
572
+ export import Infer = _Schema.Infer;
573
+ export import InsertResult = _SQLite.InsertResult;
574
+ export import IsBase64Options = _Checker.IsBase64Options;
575
+ export import IsURLOptions = _Checker.IsURLOptions;
576
+ export import IsUUIDOptions = _Checker.IsUUIDOptions;
577
+ export import Iteratee = _Arr.Iteratee;
578
+ export import JWTAlgorithm = _Crypto.JWTAlgorithm;
579
+ export import JWTClaims = _Crypto.JWTClaims;
580
+ export import Limiter = _Async.Limiter;
581
+ export import LineReader = _Cli.LineReader;
582
+ export import ListOptions = _FS.ListOptions;
583
+ export import LogFileOptions = _Logger.LogFileOptions;
584
+ export import Logger = _Logger.Logger;
585
+ export import LoggerOptions = _Logger.LoggerOptions;
586
+ export import LogLevel = _Logger.LogLevel;
587
+ export import LogStream = _Logger.LogStream;
588
+ export import MapOptions = _Async.MapOptions;
589
+ export import MaskOptions = _Str.MaskOptions;
590
+ export import MemoizedFunction = _Func.MemoizedFunction;
591
+ export import MemoizeOptions = _Func.MemoizeOptions;
592
+ export import MergeOptions = _Obj.MergeOptions;
593
+ export import Message = _Schema.Message;
594
+ export import Migration = _SQLite.Migration;
595
+ export import Mutex = _Async.Mutex;
596
+ export import NodeComfortErrorOptions = _errors.NodeComfortErrorOptions;
597
+ export import NullishToUndefined = _Obj.NullishToUndefined;
598
+ export import ObjectOutput = _Schema.ObjectOutput;
599
+ export import OrdinalOptions = _Num.OrdinalOptions;
600
+ export import Page = _Arr.Page;
601
+ export import ParseBytesOptions = _Num.ParseBytesOptions;
602
+ export import ParseContext = _Schema.ParseContext;
603
+ export import ParsedArgs = _Cli.ParsedArgs;
604
+ export import ParsedFlags = _Cli.ParsedFlags;
605
+ export import ParsedSnowflake = _Id.ParsedSnowflake;
606
+ export import PathInput = _Obj.PathInput;
607
+ export import PathLeaf = _Obj.PathLeaf;
608
+ export import Paths = _Obj.Paths;
609
+ export import PathStep = _Obj.PathStep;
610
+ export import PathValue = _Obj.PathValue;
611
+ export import PluralForms = _Str.PluralForms;
612
+ export import PluralOptions = _Str.PluralOptions;
613
+ export import PollOptions = _Async.PollOptions;
614
+ export import Primitive = _Checker.Primitive;
615
+ export import ProgressBar = _Cli.ProgressBar;
616
+ export import ProgressOptions = _Cli.ProgressOptions;
617
+ export import PromptOptions = _Cli.PromptOptions;
618
+ export import QueryOptions = _SQLite.QueryOptions;
619
+ export import QueryParams = _Http.QueryParams;
620
+ export import Queue = _Async.Queue;
621
+ export import QueueAddOptions = _Async.QueueAddOptions;
622
+ export import QueueOptions = _Async.QueueOptions;
623
+ export import RandomStringOptions = _Str.RandomStringOptions;
624
+ export import ReadJSONOptions = _FS.ReadJSONOptions;
625
+ export import RefineOptions = _Schema.RefineOptions;
626
+ export import RelativeOptions = _Time.RelativeOptions;
627
+ export import RetryOptions = _Func.RetryOptions;
628
+ export import RunOptions = _Sys.RunOptions;
629
+ export import RunResult = _Sys.RunResult;
630
+ export import SafeParseResult = _Schema.SafeParseResult;
631
+ export import ScheduledTask = _Time.ScheduledTask;
632
+ export import SelectOptions = _Cli.SelectOptions;
633
+ export import Settled = _Async.Settled;
634
+ export import Shape = _Schema.Shape;
635
+ export import ShutdownOptions = _Sys.ShutdownOptions;
636
+ export import SignJWTOptions = _Crypto.SignJWTOptions;
637
+ export import Simplify = _Schema.Simplify;
638
+ export import SlugifyOptions = _Str.SlugifyOptions;
639
+ export import SnowflakeOptions = _Id.SnowflakeOptions;
640
+ export import SortByOptions = _Arr.SortByOptions;
641
+ export import SortDirection = _SQLite.SortDirection;
642
+ export import SortKey = _Arr.SortKey;
643
+ export import Spinner = _Cli.Spinner;
644
+ export import SpinnerOptions = _Cli.SpinnerOptions;
645
+ export import SQLiteOptions = _SQLite.SQLiteOptions;
646
+ export import StartOfUnit = _Time.StartOfUnit;
647
+ export import Step = _Schema.Step;
648
+ export import Stopwatch = _Time.Stopwatch;
649
+ export import StyleEntry = _Color.StyleEntry;
650
+ export import StyleName = _Color.StyleName;
651
+ export import SystemInfo = _Sys.SystemInfo;
652
+ export import TableColumn = _Cli.TableColumn;
653
+ export import TableConstraint = _SQLite.TableConstraint;
654
+ export import TableDefinition = _SQLite.TableDefinition;
655
+ export import TableHandle = _SQLite.TableHandle;
656
+ export import TableOptions = _Cli.TableOptions;
657
+ export import TemplateOptions = _Str.TemplateOptions;
658
+ export import ThrottledFunction = _Func.ThrottledFunction;
659
+ export import ThrottleOptions = _Func.ThrottleOptions;
660
+ export import TimeZoneOptions = _Time.TimeZoneOptions;
661
+ export import TokenEncoding = _Id.TokenEncoding;
662
+ export import TOTPOptions = _Crypto.TOTPOptions;
663
+ export import TOTPURIOptions = _Crypto.TOTPURIOptions;
664
+ export import TruncateOptions = _Str.TruncateOptions;
665
+ export import ValidationIssue = _errors.ValidationIssue;
666
+ export import VarianceOptions = _Num.VarianceOptions;
667
+ export import VerifyJWTOptions = _Crypto.VerifyJWTOptions;
668
+ export import VerifyTOTPOptions = _Crypto.VerifyTOTPOptions;
669
+ export import WaitForOptions = _Emitter.WaitForOptions;
670
+ export import WaitOptions = _Utils.WaitOptions;
671
+ export import Watcher = _FS.Watcher;
672
+ export import WatchOptions = _FS.WatchOptions;
673
+ export import WeekOptions = _Time.WeekOptions;
674
+ export import WhenOptions = _Utils.WhenOptions;
675
+ export import WhenTask = _Utils.WhenTask;
676
+ export import Where = _SQLite.Where;
677
+ export import WhereOperators = _SQLite.WhereOperators;
678
+ export import WhereValue = _SQLite.WhereValue;
679
+ export import WrapOptions = _Str.WrapOptions;
680
+ export import WriteFileOptions = _FS.WriteFileOptions;
681
+ export import WriteJSONOptions = _FS.WriteJSONOptions;
682
+
683
+ // Self references
684
+ /**
685
+ * The whole toolkit. Lets you write `const { nc } = require("@ix-xs/node-comfort")`
686
+ * or `import { nc } from "@ix-xs/node-comfort"`.
687
+ */
688
+ export const nc: typeof import("./index.js");
689
+ /** The whole toolkit (same object as `nc`). */
690
+ export const nodeComfort: typeof import("./index.js");
691
+ }
692
+
693
+ export = nodeComfort;