noxium 1.0.6 → 1.0.10

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 (45) hide show
  1. package/README.md +167 -14
  2. package/build.ts +65 -0
  3. package/dist/drivers/mongo.cjs +1080 -0
  4. package/dist/drivers/mongo.cjs.map +456 -0
  5. package/dist/drivers/mongo.d.ts +4 -0
  6. package/dist/drivers/mongo.d.ts.map +1 -0
  7. package/dist/drivers/mongo.mjs +1081 -0
  8. package/dist/drivers/mongo.mjs.map +456 -0
  9. package/dist/drivers/sqlite.cjs +18 -0
  10. package/dist/drivers/sqlite.cjs.map +11 -0
  11. package/dist/drivers/sqlite.d.ts +4 -0
  12. package/dist/drivers/sqlite.d.ts.map +1 -0
  13. package/dist/drivers/sqlite.mjs +19 -0
  14. package/dist/drivers/sqlite.mjs.map +11 -0
  15. package/dist/error.cjs +18 -0
  16. package/dist/error.cjs.map +10 -0
  17. package/dist/error.d.ts +20 -0
  18. package/dist/error.d.ts.map +1 -0
  19. package/dist/error.mjs +19 -0
  20. package/dist/error.mjs.map +10 -0
  21. package/dist/noxium.cjs +1080 -0
  22. package/dist/noxium.cjs.map +473 -0
  23. package/dist/noxium.d.ts +21 -0
  24. package/dist/noxium.d.ts.map +1 -0
  25. package/dist/noxium.mjs +1081 -0
  26. package/dist/noxium.mjs.map +473 -0
  27. package/dist/schema.cjs +4 -0
  28. package/dist/schema.cjs.map +9 -0
  29. package/dist/schema.d.ts +84 -0
  30. package/dist/schema.d.ts.map +1 -0
  31. package/dist/schema.mjs +4 -0
  32. package/dist/schema.mjs.map +9 -0
  33. package/package.json +24 -26
  34. package/dist/cjs/createClient.cjs +0 -54
  35. package/dist/cjs/drivers/mongo.cjs +0 -61
  36. package/dist/cjs/drivers/sqlite.cjs +0 -74
  37. package/dist/cjs/error.cjs +0 -46
  38. package/dist/cjs/noxium.cjs +0 -39
  39. package/dist/cjs/schema.cjs +0 -2
  40. package/dist/esm/createClient.js +0 -52
  41. package/dist/esm/drivers/mongo.js +0 -59
  42. package/dist/esm/drivers/sqlite.js +0 -72
  43. package/dist/esm/error.js +0 -41
  44. package/dist/esm/noxium.js +0 -37
  45. package/dist/esm/schema.js +0 -1
package/README.md CHANGED
@@ -1,27 +1,180 @@
1
- # Library For Noxium
1
+ # Noxium
2
+
3
+ Lightweight, type-safe mini ORM for **Bun** and **TypeScript** that unifies **SQLite (`better-sqlite3`)** and **MongoDB (`Mongoose`)** behind a single declarative schema and query API.
4
+
5
+ ## Features
6
+
7
+ - **Dual-Driver Support:** Switch seamlessly between `sqlite` (`better-sqlite3`) and `mongo` (`mongoose`) from a single configuration object.
8
+ - **Declarative Schema:** Define models, field types (`String`, `Number`, `Boolean`, `Date`, `"ref"`), `required`, `unique`, `default`, `trim`, and `lowercase` in one place.
9
+ - **Full TypeScript Type Safety:** Automatic type inference and IDE autocomplete (`Ctrl + Space`) for required fields on `insert`, unique keys on `findUnique`, and typed query results.
10
+ - **Built-in Relations (`populate`):** Unified relation loading using `.populate()` on MongoDB and automatic `LEFT JOIN` on SQLite.
11
+ - **Lifecycle Hooks & TTL:** Supports `afterFind` hooks (e.g., auto-expiring records) and automatic TTL cleanup across both drivers.
12
+ - **Consistent Error Handling:** Standardized `DuplicateError`, `ValidationError`, and `InvalidConfigError` regardless of the underlying database.
2
13
 
3
14
  ## Installation
4
15
 
5
- This is a [Node.js](https://nodejs.org/en/) module available through the
6
- [npm registry](https://www.npmjs.com/).
16
+ Install `noxium` using **Bun** or **npm**:
17
+
18
+ ```bash
19
+ bun add noxium
20
+ # or
21
+ npm install noxium
22
+
23
+ ```
24
+
25
+ ## Quick Start
26
+
27
+ ### 1. Create Your Configuration File
28
+
29
+ You can name your configuration file anything (e.g., `noxium.config.ts` or `db.config.ts`). Use `as const satisfies SchemasMap` so TypeScript preserves literal types for `required` and `unique` fields.
30
+
31
+ ```ts
32
+ // noxium.config.ts or db.config.ts
33
+ import { type NoxiumConfig, type SchemasMap } from "noxium";
7
34
 
8
- Before installing, [download and install Node.js](https://nodejs.org/en/download/).
9
- Node.js 0.10 or higher is required.
35
+ const schemas = {
36
+ clients: {
37
+ fields: {
38
+ name: { type: String, required: true, unique: true, trim: true },
39
+ email: {
40
+ type: String,
41
+ required: true,
42
+ unique: true,
43
+ lowercase: true,
44
+ trim: true,
45
+ },
46
+ password: { type: String, required: true },
47
+ role: { type: String, default: "member" },
48
+ balance: { type: Number, default: 0 },
49
+ },
50
+ },
51
+ products: {
52
+ fields: {
53
+ owner: { type: "ref", ref: "clients", required: true },
54
+ title: { type: String, required: true, trim: true },
55
+ slug: {
56
+ type: String,
57
+ required: true,
58
+ unique: true,
59
+ lowercase: true,
60
+ trim: true,
61
+ },
62
+ price: { type: Number, required: true, default: 0 },
63
+ stock: { type: Number, default: 0 },
64
+ },
65
+ },
66
+ } as const satisfies SchemasMap;
10
67
 
11
- If this is a brand new project, make sure to create a `package.json` first with
12
- the [`npm init` command](https://docs.npmjs.com/creating-a-package-json-file).
68
+ export type AppSchemas = typeof schemas;
13
69
 
14
- Installation is done using the
15
- [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
70
+ export default function getConfig(): NoxiumConfig<AppSchemas> {
71
+ const isMongo = process.env.DB_DRIVER === "mongo";
16
72
 
17
- ```console
18
- $ npm install noxium
73
+ return {
74
+ database: isMongo
75
+ ? {
76
+ type: "mongo",
77
+ mongo: {
78
+ uri: process.env.MONGODB_URI || "mongodb://localhost:27017",
79
+ dbName: process.env.MONGODB_DB || "app",
80
+ },
81
+ }
82
+ : {
83
+ type: "sqlite",
84
+ sqlite: {
85
+ path: process.env.SQLITE_PATH || "./data.db",
86
+ },
87
+ },
88
+ schemas,
89
+ };
90
+ }
19
91
  ```
20
92
 
21
- ## Features
93
+ ### 2. Initialize & Query Data
94
+
95
+ Pass your configuration into `new Noxium<AppSchemas>(...)` and access your models via `noxium.model(...)` or directly as properties (`noxium.clients`, `noxium.shortlinks`).
96
+
97
+ ```ts
98
+ import { Noxium } from "noxium";
99
+ import { DuplicateError, ValidationError } from "noxium/error";
100
+ import getConfig, { type AppSchemas } from "./noxium.config";
101
+
102
+ const noxium = new Noxium<AppSchemas>(getConfig());
103
+ const clients = noxium.model("clients");
104
+
105
+ async function main() {
106
+ try {
107
+ // Required fields without defaults (`name`, `email`, `password`) are enforced by TypeScript
108
+ const user = await clients.insert({
109
+ name: "Ayiin",
110
+ email: "ayiin@example.com",
111
+ password: "secret",
112
+ });
113
+
114
+ // Insert related record
115
+ await noxium.products.insert({
116
+ owner: user.id,
117
+ title: "Mechanical Keyboard",
118
+ slug: "mechanical-keyboard",
119
+ price: 750000,
120
+ stock: 10,
121
+ });
122
+ } catch (error) {
123
+ if (error instanceof DuplicateError) {
124
+ console.error("Duplicate value:", error.column, error.value);
125
+ } else if (error instanceof ValidationError) {
126
+ console.error("Missing required field:", error.column);
127
+ } else {
128
+ throw error;
129
+ }
130
+ }
131
+
132
+ // Query all records
133
+ const allClients = await clients.findAll();
134
+ console.log("All clients:", allClients);
135
+
136
+ // Query by unique field (`id`, `name`, or `email`)
137
+ const client = await clients.findUnique({ email: "ayiin@example.com" });
138
+ console.log("Found client:", client);
139
+
140
+ // Query with relation populate (MongoDB `.populate()` / SQLite `LEFT JOIN`)
141
+ const product = await noxium.products.findUnique(
142
+ { slug: "mechanical-keyboard" },
143
+ { populate: { owner: ["name", "email"] } },
144
+ );
145
+ console.log("Product with owner:", product);
146
+ }
147
+
148
+ main();
149
+ ```
150
+
151
+ ## Schema Options
152
+
153
+ | Option | Type | Description |
154
+ | ----------- | --------- | ----------------------------------------------------------- | ------- | ---- | ------ | --------------------------------------------------- |
155
+ | `type` | `String | Number | Boolean | Date | "ref"` | Field data type or foreign key reference (`"ref"`). |
156
+ | `ref` | `string` | Target model/table name when `type: "ref"`. |
157
+ | `required` | `boolean` | Marks field as required on insert and `NOT NULL` in SQLite. |
158
+ | `unique` | `boolean` | Enforces uniqueness and enables lookup in `findUnique`. |
159
+ | `default` | `any` | Default value applied when omitted during `insert`. |
160
+ | `trim` | `boolean` | Automatically trims whitespace on string values. |
161
+ | `lowercase` | `boolean` | Automatically converts string values to lowercase. |
162
+
163
+ ### Model-Level Options
164
+
165
+ - **`timestamps`**: Automatically manages `createdAt` and `updatedAt` (`true` by default).
166
+ - **`ttl`**: `{ field: "createdAt", seconds: 2592000 }` — Creates a MongoDB TTL index and automatically cleans up expired rows in SQLite.
167
+ - **`hooks.afterFind`**: Runs post-query transformations or maintenance logic (set `doc.__dirty = true` in SQLite to persist updates).
168
+
169
+ ## Available Model Methods
22
170
 
23
- - This is for me to learn javascript
171
+ - `insert(data)` — Inserts a new record and returns the created document.
172
+ - `update(id, data)` — Updates a record by `id` and returns the updated document.
173
+ - `findAll(options?)` — Retrieves all records in the table/collection.
174
+ - `findUnique(where, options?)` — Finds a single record by `id` or any `unique` field.
175
+ - `findMany(where?, options?)` — Finds all records matching the filter.
176
+ - `deleteMany(where)` — Deletes matching records and returns the deleted count.
24
177
 
25
178
  ## License
26
179
 
27
- [MIT](LICENSE)
180
+ [MIT](https://www.google.com/search?q=LICENSE)
package/build.ts ADDED
@@ -0,0 +1,65 @@
1
+ import { rm } from "node:fs/promises";
2
+
3
+ // 1. Bersihkan folder dist sebelum build
4
+ await rm("./dist", { recursive: true, force: true });
5
+ console.log("🧹 Folder dist dibersihkan.");
6
+
7
+ const glob = new Bun.Glob("**/*.{ts,tsx}");
8
+ const entrypoints: string[] = [];
9
+
10
+ for (const path of glob.scanSync({
11
+ cwd: "./src",
12
+ onlyFiles: true,
13
+ })) {
14
+ entrypoints.push(`./src/${path.replaceAll("\\", "/")}`); // 👈 Path lengkap untuk dibaca oleh Bun.build
15
+ }
16
+
17
+ console.log("Entrypoints:", entrypoints);
18
+
19
+ // 2. Build untuk ESM (.mjs)
20
+ const esmResult = await Bun.build({
21
+ entrypoints,
22
+ root: "./src", // 👈 Beritahu Bun root-nya adalah src agar struktur dist tetap flat
23
+ outdir: "./dist",
24
+ target: "bun",
25
+ format: "esm",
26
+ naming: "[dir]/[name].mjs",
27
+ sourcemap: "linked",
28
+ minify: true,
29
+ });
30
+
31
+ if (!esmResult.success) {
32
+ console.error("❌ ESM Build Gagal:", esmResult.logs);
33
+ process.exit(1);
34
+ }
35
+ console.log("✅ ESM Build Selesai (.mjs)");
36
+
37
+ // 3. Build untuk CJS (.cjs)
38
+ const cjsResult = await Bun.build({
39
+ entrypoints,
40
+ root: "./src", // 👈 Terapkan juga untuk CJS
41
+ outdir: "./dist",
42
+ target: "node",
43
+ format: "cjs",
44
+ naming: "[dir]/[name].cjs",
45
+ sourcemap: "linked",
46
+ minify: true,
47
+ });
48
+
49
+ if (!cjsResult.success) {
50
+ console.error("❌ CJS Build Gagal:", cjsResult.logs);
51
+ process.exit(1);
52
+ }
53
+ console.log("✅ CJS Build CJS Selesai (.cjs)");
54
+
55
+ // 4. Generate TypeScript Declaration Files (.d.ts)
56
+ console.log("⏳ Menggenerasi berkas .d.ts...");
57
+ const proc = Bun.spawn(["bunx", "tsc", "-p", "tsconfig.build.json"]);
58
+ await proc.exited;
59
+
60
+ if (proc.exitCode !== 0) {
61
+ console.error("❌ Generasi .d.ts gagal.");
62
+ process.exit(1);
63
+ }
64
+
65
+ console.log("🎉 Build berhasil! Output tersedia di folder ./dist");