@stonyx/orm 0.2.1-beta.83 → 0.2.1-beta.85

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 (150) hide show
  1. package/dist/aggregates.d.ts +21 -0
  2. package/dist/aggregates.js +90 -0
  3. package/dist/attr.d.ts +2 -0
  4. package/dist/attr.js +22 -0
  5. package/dist/belongs-to.d.ts +11 -0
  6. package/dist/belongs-to.js +59 -0
  7. package/dist/cli.d.ts +22 -0
  8. package/dist/cli.js +148 -0
  9. package/dist/commands.d.ts +7 -0
  10. package/dist/commands.js +146 -0
  11. package/dist/db.d.ts +21 -0
  12. package/dist/db.js +174 -0
  13. package/dist/exports/db.d.ts +7 -0
  14. package/{src → dist}/exports/db.js +2 -4
  15. package/dist/has-many.d.ts +11 -0
  16. package/dist/has-many.js +58 -0
  17. package/dist/hooks.d.ts +47 -0
  18. package/dist/hooks.js +106 -0
  19. package/dist/index.d.ts +14 -0
  20. package/dist/index.js +34 -0
  21. package/dist/main.d.ts +46 -0
  22. package/dist/main.js +179 -0
  23. package/dist/manage-record.d.ts +13 -0
  24. package/dist/manage-record.js +114 -0
  25. package/dist/meta-request.d.ts +6 -0
  26. package/dist/meta-request.js +52 -0
  27. package/dist/migrate.d.ts +2 -0
  28. package/dist/migrate.js +57 -0
  29. package/dist/model-property.d.ts +9 -0
  30. package/dist/model-property.js +29 -0
  31. package/dist/model.d.ts +15 -0
  32. package/dist/model.js +18 -0
  33. package/dist/mysql/connection.d.ts +14 -0
  34. package/dist/mysql/connection.js +24 -0
  35. package/dist/mysql/migration-generator.d.ts +45 -0
  36. package/dist/mysql/migration-generator.js +245 -0
  37. package/dist/mysql/migration-runner.d.ts +12 -0
  38. package/dist/mysql/migration-runner.js +83 -0
  39. package/dist/mysql/mysql-db.d.ts +100 -0
  40. package/dist/mysql/mysql-db.js +415 -0
  41. package/dist/mysql/query-builder.d.ts +10 -0
  42. package/dist/mysql/query-builder.js +44 -0
  43. package/dist/mysql/schema-introspector.d.ts +19 -0
  44. package/dist/mysql/schema-introspector.js +286 -0
  45. package/dist/mysql/type-map.d.ts +21 -0
  46. package/dist/mysql/type-map.js +36 -0
  47. package/dist/orm-request.d.ts +38 -0
  48. package/dist/orm-request.js +455 -0
  49. package/dist/plural-registry.d.ts +4 -0
  50. package/{src → dist}/plural-registry.js +3 -6
  51. package/dist/postgres/connection.d.ts +15 -0
  52. package/dist/postgres/connection.js +30 -0
  53. package/dist/postgres/migration-generator.d.ts +45 -0
  54. package/dist/postgres/migration-generator.js +257 -0
  55. package/dist/postgres/migration-runner.d.ts +10 -0
  56. package/dist/postgres/migration-runner.js +82 -0
  57. package/dist/postgres/postgres-db.d.ts +119 -0
  58. package/dist/postgres/postgres-db.js +476 -0
  59. package/dist/postgres/query-builder.d.ts +27 -0
  60. package/dist/postgres/query-builder.js +98 -0
  61. package/dist/postgres/schema-introspector.d.ts +29 -0
  62. package/dist/postgres/schema-introspector.js +309 -0
  63. package/dist/postgres/type-map.d.ts +23 -0
  64. package/dist/postgres/type-map.js +53 -0
  65. package/dist/record.d.ts +75 -0
  66. package/dist/record.js +115 -0
  67. package/dist/relationships.d.ts +10 -0
  68. package/dist/relationships.js +39 -0
  69. package/dist/serializer.d.ts +17 -0
  70. package/dist/serializer.js +136 -0
  71. package/dist/setup-rest-server.d.ts +1 -0
  72. package/dist/setup-rest-server.js +54 -0
  73. package/dist/standalone-db.d.ts +58 -0
  74. package/dist/standalone-db.js +142 -0
  75. package/dist/store.d.ts +62 -0
  76. package/dist/store.js +271 -0
  77. package/dist/timescale/query-builder.d.ts +41 -0
  78. package/dist/timescale/query-builder.js +87 -0
  79. package/dist/timescale/timescale-db.d.ts +45 -0
  80. package/dist/timescale/timescale-db.js +84 -0
  81. package/dist/transforms.d.ts +2 -0
  82. package/dist/transforms.js +17 -0
  83. package/dist/types/orm-types.d.ts +142 -0
  84. package/dist/types/orm-types.js +1 -0
  85. package/dist/utils.d.ts +5 -0
  86. package/dist/utils.js +13 -0
  87. package/dist/view-resolver.d.ts +8 -0
  88. package/dist/view-resolver.js +169 -0
  89. package/dist/view.d.ts +11 -0
  90. package/dist/view.js +18 -0
  91. package/package.json +34 -11
  92. package/src/{aggregates.js → aggregates.ts} +27 -13
  93. package/src/{attr.js → attr.ts} +2 -2
  94. package/src/belongs-to.ts +90 -0
  95. package/src/{cli.js → cli.ts} +17 -11
  96. package/src/{commands.js → commands.ts} +179 -170
  97. package/src/{db.js → db.ts} +35 -26
  98. package/src/exports/db.ts +7 -0
  99. package/src/has-many.ts +92 -0
  100. package/src/{hooks.js → hooks.ts} +23 -27
  101. package/src/{index.js → index.ts} +4 -4
  102. package/src/{main.js → main.ts} +60 -34
  103. package/src/{manage-record.js → manage-record.ts} +42 -22
  104. package/src/{meta-request.js → meta-request.ts} +17 -14
  105. package/src/{migrate.js → migrate.ts} +9 -9
  106. package/src/{model-property.js → model-property.ts} +12 -6
  107. package/src/{model.js → model.ts} +5 -4
  108. package/src/mysql/{connection.js → connection.ts} +43 -28
  109. package/src/mysql/{migration-generator.js → migration-generator.ts} +332 -286
  110. package/src/mysql/{migration-runner.js → migration-runner.ts} +116 -110
  111. package/src/mysql/{mysql-db.js → mysql-db.ts} +537 -473
  112. package/src/mysql/{query-builder.js → query-builder.ts} +69 -64
  113. package/src/mysql/{schema-introspector.js → schema-introspector.ts} +355 -325
  114. package/src/mysql/{type-map.js → type-map.ts} +42 -37
  115. package/src/{orm-request.js → orm-request.ts} +169 -97
  116. package/src/plural-registry.ts +12 -0
  117. package/src/postgres/{connection.js → connection.ts} +14 -5
  118. package/src/postgres/{migration-generator.js → migration-generator.ts} +82 -38
  119. package/src/postgres/{migration-runner.js → migration-runner.ts} +11 -10
  120. package/src/postgres/{postgres-db.js → postgres-db.ts} +198 -114
  121. package/src/postgres/{query-builder.js → query-builder.ts} +27 -28
  122. package/src/postgres/{schema-introspector.js → schema-introspector.ts} +87 -58
  123. package/src/postgres/{type-map.js → type-map.ts} +10 -6
  124. package/src/{record.js → record.ts} +73 -34
  125. package/src/relationships.ts +53 -0
  126. package/src/{serializer.js → serializer.ts} +52 -36
  127. package/src/{setup-rest-server.js → setup-rest-server.ts} +18 -13
  128. package/src/{standalone-db.js → standalone-db.ts} +33 -24
  129. package/src/{store.js → store.ts} +90 -68
  130. package/src/timescale/{query-builder.js → query-builder.ts} +33 -38
  131. package/src/timescale/timescale-db.ts +119 -0
  132. package/src/transforms.ts +20 -0
  133. package/src/types/mysql2.d.ts +30 -0
  134. package/src/types/orm-types.ts +146 -0
  135. package/src/types/pg.d.ts +28 -0
  136. package/src/types/stonyx-cron.d.ts +5 -0
  137. package/src/types/stonyx-events.d.ts +4 -0
  138. package/src/types/stonyx-rest-server.d.ts +11 -0
  139. package/src/types/stonyx-utils.d.ts +33 -0
  140. package/src/types/stonyx.d.ts +21 -0
  141. package/src/utils.ts +16 -0
  142. package/src/{view-resolver.js → view-resolver.ts} +51 -24
  143. package/src/view.ts +22 -0
  144. package/src/belongs-to.js +0 -70
  145. package/src/has-many.js +0 -68
  146. package/src/relationships.js +0 -43
  147. package/src/timescale/timescale-db.js +0 -111
  148. package/src/transforms.js +0 -20
  149. package/src/utils.js +0 -12
  150. package/src/view.js +0 -21
package/dist/db.js ADDED
@@ -0,0 +1,174 @@
1
+ /*
2
+ * Copyright 2025 Stone Costa
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import Cron from '@stonyx/cron';
17
+ import config from 'stonyx/config';
18
+ import log from 'stonyx/log';
19
+ import Orm, { store } from '@stonyx/orm';
20
+ import { createRecord } from './manage-record.js';
21
+ import { createFile, createDirectory, updateFile, readFile, fileExists } from '@stonyx/utils/file';
22
+ import path from 'path';
23
+ export const dbKey = '__db';
24
+ export default class DB {
25
+ static instance;
26
+ record;
27
+ constructor() {
28
+ if (DB.instance)
29
+ return DB.instance;
30
+ DB.instance = this;
31
+ }
32
+ async getSchema() {
33
+ const { rootPath } = config;
34
+ const { file, schema } = config.orm.db;
35
+ if (!file)
36
+ throw new Error('Configuration Error: ORM DB file path must be defined.');
37
+ return (await import(`${rootPath}/${schema}`)).default;
38
+ }
39
+ getCollectionKeys() {
40
+ const SchemaClass = Orm.instance.models[`${dbKey}Model`];
41
+ const instance = new SchemaClass();
42
+ const keys = [];
43
+ for (const key of Object.keys(instance)) {
44
+ if (key === '__name' || key === 'id')
45
+ continue;
46
+ if (typeof instance[key] === 'function')
47
+ keys.push(key);
48
+ }
49
+ return keys;
50
+ }
51
+ getDirPath() {
52
+ const { rootPath } = config;
53
+ const { file, directory } = config.orm.db;
54
+ const dbDir = path.dirname(path.resolve(`${rootPath}/${file}`));
55
+ return path.join(dbDir, directory);
56
+ }
57
+ async validateMode() {
58
+ const { rootPath } = config;
59
+ const { file, mode } = config.orm.db;
60
+ const collectionKeys = this.getCollectionKeys();
61
+ const dirPath = this.getDirPath();
62
+ if (mode === 'directory') {
63
+ const dbFilePath = path.resolve(`${rootPath}/${file}`);
64
+ const exists = await fileExists(dbFilePath);
65
+ if (exists) {
66
+ const data = await readFile(dbFilePath, { json: true });
67
+ const hasData = collectionKeys.some(key => Array.isArray(data[key]) && data[key].length > 0);
68
+ if (hasData) {
69
+ log.error(`DB mode mismatch: db.json contains data but mode is set to 'directory'. Run migration first:\n\n stonyx db:migrate-to-directory\n`);
70
+ process.exit(1);
71
+ }
72
+ }
73
+ }
74
+ else {
75
+ const dirExists = await fileExists(dirPath);
76
+ if (dirExists) {
77
+ const hasCollectionFiles = (await Promise.all(collectionKeys.map(key => fileExists(path.join(dirPath, `${key}.json`))))).some(Boolean);
78
+ if (hasCollectionFiles) {
79
+ log.error(`DB mode mismatch: directory '${config.orm.db.directory}/' contains collection files but mode is set to 'file'. Run migration first:\n\n stonyx db:migrate-to-file\n`);
80
+ process.exit(1);
81
+ }
82
+ }
83
+ }
84
+ }
85
+ async init() {
86
+ const { autosave, saveInterval } = config.orm.db;
87
+ store.set(dbKey, new Map());
88
+ Orm.instance.models[`${dbKey}Model`] = await this.getSchema();
89
+ await this.validateMode();
90
+ this.record = await this.getRecord();
91
+ if (autosave !== 'true')
92
+ return;
93
+ new Cron().register('save', this.save.bind(this), saveInterval);
94
+ }
95
+ async create() {
96
+ const { rootPath } = config;
97
+ const { file, mode } = config.orm.db;
98
+ if (mode === 'directory') {
99
+ const dirPath = this.getDirPath();
100
+ const collectionKeys = this.getCollectionKeys();
101
+ await createDirectory(dirPath);
102
+ await Promise.all(collectionKeys.map(key => createFile(path.join(dirPath, `${key}.json`), [], { json: true })));
103
+ // Write empty-array skeleton to db.json
104
+ const skeleton = {};
105
+ for (const key of collectionKeys)
106
+ skeleton[key] = [];
107
+ await createFile(`${rootPath}/${file}`, skeleton, { json: true });
108
+ return skeleton;
109
+ }
110
+ createFile(`${rootPath}/${file}`, {}, { json: true });
111
+ return {};
112
+ }
113
+ async save() {
114
+ const { file, mode } = config.orm.db;
115
+ const jsonData = this.record.format();
116
+ delete jsonData.id; // Don't save id
117
+ if (mode === 'directory') {
118
+ const dirPath = this.getDirPath();
119
+ const collectionKeys = this.getCollectionKeys();
120
+ // Write each collection to its own file in parallel
121
+ // Use createFile for new files, updateFile for existing ones
122
+ await Promise.all(collectionKeys.map(async (key) => {
123
+ const filePath = path.join(dirPath, `${key}.json`);
124
+ const exists = await fileExists(filePath);
125
+ const data = jsonData[key] || [];
126
+ if (exists)
127
+ await updateFile(filePath, data, { json: true });
128
+ else
129
+ await createFile(filePath, data, { json: true });
130
+ }));
131
+ // Write empty-array skeleton to db.json
132
+ const skeleton = {};
133
+ for (const key of collectionKeys)
134
+ skeleton[key] = [];
135
+ const dbFilePath = `${config.rootPath}/${file}`;
136
+ const dbFileExists = await fileExists(dbFilePath);
137
+ if (dbFileExists)
138
+ await updateFile(dbFilePath, skeleton, { json: true });
139
+ else
140
+ await createFile(dbFilePath, skeleton, { json: true });
141
+ log.db(`DB has been successfully saved to ${config.orm.db.directory}/ directory`);
142
+ return;
143
+ }
144
+ await updateFile(`${config.rootPath}/${file}`, jsonData, { json: true });
145
+ log.db(`DB has been successfully saved to ${file}`);
146
+ }
147
+ async getRecord() {
148
+ const { mode } = config.orm.db;
149
+ if (mode === 'directory')
150
+ return this.getRecordFromDirectory();
151
+ return this.getRecordFromFile();
152
+ }
153
+ async getRecordFromFile() {
154
+ const { file } = config.orm.db;
155
+ const data = await readFile(file, { json: true, missingFileCallback: this.create.bind(this) });
156
+ return createRecord(dbKey, data, { isDbRecord: true, serialize: false, transform: false });
157
+ }
158
+ async getRecordFromDirectory() {
159
+ const dirPath = this.getDirPath();
160
+ const collectionKeys = this.getCollectionKeys();
161
+ const dirExists = await fileExists(dirPath);
162
+ if (!dirExists) {
163
+ const data = await this.create();
164
+ return createRecord(dbKey, data, { isDbRecord: true, serialize: false, transform: false });
165
+ }
166
+ const assembled = {};
167
+ await Promise.all(collectionKeys.map(async (key) => {
168
+ const filePath = path.join(dirPath, `${key}.json`);
169
+ const exists = await fileExists(filePath);
170
+ assembled[key] = exists ? await readFile(filePath, { json: true }) : [];
171
+ }));
172
+ return createRecord(dbKey, assembled, { isDbRecord: true, serialize: false, transform: false });
173
+ }
174
+ }
@@ -0,0 +1,7 @@
1
+ declare const db: {
2
+ record: unknown;
3
+ save(): Promise<void>;
4
+ };
5
+ export default db;
6
+ export declare const data: unknown;
7
+ export declare const saveDB: () => Promise<void>;
@@ -1,7 +1,5 @@
1
1
  import Orm from '@stonyx/orm';
2
-
3
- const { db } = Orm;
4
-
2
+ const db = Orm.db;
5
3
  export default db;
6
4
  export const data = db.record;
7
- export const saveDB = db.save.bind(db);
5
+ export const saveDB = db.save.bind(db);
@@ -0,0 +1,11 @@
1
+ import type { SourceRecord } from './types/orm-types.js';
2
+ interface HasManyOptions {
3
+ global?: boolean;
4
+ [key: string]: unknown;
5
+ }
6
+ type RelationshipHandler = ((sourceRecord: SourceRecord, rawData: unknown, options: HasManyOptions) => unknown[]) & {
7
+ __relatedModelName: string;
8
+ __relationshipType: 'hasMany';
9
+ };
10
+ export default function hasMany(modelName: string): RelationshipHandler;
11
+ export {};
@@ -0,0 +1,58 @@
1
+ import { createRecord, store } from '@stonyx/orm';
2
+ import { getRelationships, getGlobalRegistry, getPendingRegistry, getBelongsToRegistry } from './relationships.js';
3
+ import { getOrSet, makeArray } from '@stonyx/utils/object';
4
+ import { dbKey } from './db.js';
5
+ function queuePendingRelationship(pendingRelationshipQueue, pendingRelationships, modelName, id) {
6
+ pendingRelationshipQueue.push({
7
+ pendingRelationship: getOrSet(pendingRelationships, modelName, new Map()),
8
+ id
9
+ });
10
+ return null;
11
+ }
12
+ export default function hasMany(modelName) {
13
+ const globalRelationships = getGlobalRegistry();
14
+ const pendingRelationships = getPendingRegistry();
15
+ const fn = (sourceRecord, rawData, options) => {
16
+ const { __name: sourceModelName } = sourceRecord.__model;
17
+ const relationshipId = sourceRecord.id;
18
+ const relationship = getRelationships('hasMany', sourceModelName, modelName, relationshipId);
19
+ const modelStore = store.get(modelName);
20
+ const pendingRelationshipQueue = [];
21
+ const output = !rawData ? [] : makeArray(rawData).map((elementData) => {
22
+ let record;
23
+ if (typeof elementData !== 'object') {
24
+ if (!modelStore) {
25
+ return queuePendingRelationship(pendingRelationshipQueue, pendingRelationships, modelName, elementData);
26
+ }
27
+ record = modelStore.get(elementData);
28
+ if (!record) {
29
+ return queuePendingRelationship(pendingRelationshipQueue, pendingRelationships, modelName, elementData);
30
+ }
31
+ }
32
+ else {
33
+ if (elementData !== Object(elementData)) {
34
+ return queuePendingRelationship(pendingRelationshipQueue, pendingRelationships, modelName, elementData);
35
+ }
36
+ record = createRecord(modelName, elementData, options);
37
+ }
38
+ // Populate belongTo side if the relationship is defined
39
+ const recordWithId = typeof record === 'object' && record !== null && 'id' in record ? record : undefined;
40
+ const otherSide = recordWithId ? getBelongsToRegistry()
41
+ .get(modelName)?.get(sourceModelName)?.get(recordWithId.id) : undefined;
42
+ if (otherSide)
43
+ Object.assign(otherSide, sourceRecord);
44
+ return record;
45
+ }).filter((value) => value);
46
+ relationship.set(relationshipId, output);
47
+ // Assign global relationship
48
+ if (options.global || sourceModelName === dbKey)
49
+ getOrSet(globalRelationships, modelName, []).push(output);
50
+ // Assign pending relationships
51
+ for (const { pendingRelationship, id } of pendingRelationshipQueue)
52
+ getOrSet(pendingRelationship, id, []).push(output);
53
+ return output;
54
+ };
55
+ Object.defineProperty(fn, '__relatedModelName', { value: modelName });
56
+ Object.defineProperty(fn, '__relationshipType', { value: 'hasMany' });
57
+ return fn;
58
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Middleware-based hooks registry for ORM operations.
3
+ * Unlike event-based hooks, middleware hooks run sequentially and can halt operations.
4
+ */
5
+ type HookHandler = (context: Record<string, unknown>) => unknown | Promise<unknown>;
6
+ /**
7
+ * Register a before hook middleware that runs before the operation executes.
8
+ *
9
+ * @param operation - Operation name: 'create', 'update', 'delete', 'get', or 'list'
10
+ * @param model - Model name (e.g., 'user', 'animal')
11
+ * @param handler - Middleware function (context) => any
12
+ * - Return undefined to continue to next hook/handler
13
+ * - Return any value to halt operation (integer = HTTP status, object = response body)
14
+ * @returns Unsubscribe function
15
+ */
16
+ export declare function beforeHook(operation: string, model: string, handler: HookHandler): () => void;
17
+ /**
18
+ * Register an after hook middleware that runs after the operation completes.
19
+ * After hooks cannot halt operations (they run after completion).
20
+ *
21
+ * @param operation - Operation name
22
+ * @param model - Model name
23
+ * @param handler - Middleware function (context) => void
24
+ * @returns Unsubscribe function
25
+ */
26
+ export declare function afterHook(operation: string, model: string, handler: HookHandler): () => void;
27
+ /**
28
+ * Get all before hooks for an operation:model combination.
29
+ */
30
+ export declare function getBeforeHooks(operation: string, model: string): HookHandler[];
31
+ /**
32
+ * Get all after hooks for an operation:model combination.
33
+ */
34
+ export declare function getAfterHooks(operation: string, model: string): HookHandler[];
35
+ /**
36
+ * Clear registered hooks for a specific operation:model.
37
+ *
38
+ * @param operation - Operation name
39
+ * @param model - Model name
40
+ * @param type - 'before' or 'after' (if omitted, clears both)
41
+ */
42
+ export declare function clearHook(operation: string, model: string, type?: 'before' | 'after'): void;
43
+ /**
44
+ * Clear all hooks (useful for testing).
45
+ */
46
+ export declare function clearAllHooks(): void;
47
+ export {};
package/dist/hooks.js ADDED
@@ -0,0 +1,106 @@
1
+ /*
2
+ * Copyright 2025 Stone Costa
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the 'License');
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ // Map of "operation:model" -> handler[]
17
+ const beforeHooks = new Map();
18
+ const afterHooks = new Map();
19
+ /**
20
+ * Register a before hook middleware that runs before the operation executes.
21
+ *
22
+ * @param operation - Operation name: 'create', 'update', 'delete', 'get', or 'list'
23
+ * @param model - Model name (e.g., 'user', 'animal')
24
+ * @param handler - Middleware function (context) => any
25
+ * - Return undefined to continue to next hook/handler
26
+ * - Return any value to halt operation (integer = HTTP status, object = response body)
27
+ * @returns Unsubscribe function
28
+ */
29
+ export function beforeHook(operation, model, handler) {
30
+ const key = `${operation}:${model}`;
31
+ if (!beforeHooks.has(key)) {
32
+ beforeHooks.set(key, []);
33
+ }
34
+ beforeHooks.get(key).push(handler);
35
+ // Return unsubscribe function
36
+ return () => {
37
+ const hooks = beforeHooks.get(key);
38
+ if (hooks) {
39
+ const index = hooks.indexOf(handler);
40
+ if (index > -1)
41
+ hooks.splice(index, 1);
42
+ }
43
+ };
44
+ }
45
+ /**
46
+ * Register an after hook middleware that runs after the operation completes.
47
+ * After hooks cannot halt operations (they run after completion).
48
+ *
49
+ * @param operation - Operation name
50
+ * @param model - Model name
51
+ * @param handler - Middleware function (context) => void
52
+ * @returns Unsubscribe function
53
+ */
54
+ export function afterHook(operation, model, handler) {
55
+ const key = `${operation}:${model}`;
56
+ if (!afterHooks.has(key)) {
57
+ afterHooks.set(key, []);
58
+ }
59
+ afterHooks.get(key).push(handler);
60
+ // Return unsubscribe function
61
+ return () => {
62
+ const hooks = afterHooks.get(key);
63
+ if (hooks) {
64
+ const index = hooks.indexOf(handler);
65
+ if (index > -1)
66
+ hooks.splice(index, 1);
67
+ }
68
+ };
69
+ }
70
+ /**
71
+ * Get all before hooks for an operation:model combination.
72
+ */
73
+ export function getBeforeHooks(operation, model) {
74
+ const key = `${operation}:${model}`;
75
+ return beforeHooks.get(key) || [];
76
+ }
77
+ /**
78
+ * Get all after hooks for an operation:model combination.
79
+ */
80
+ export function getAfterHooks(operation, model) {
81
+ const key = `${operation}:${model}`;
82
+ return afterHooks.get(key) || [];
83
+ }
84
+ /**
85
+ * Clear registered hooks for a specific operation:model.
86
+ *
87
+ * @param operation - Operation name
88
+ * @param model - Model name
89
+ * @param type - 'before' or 'after' (if omitted, clears both)
90
+ */
91
+ export function clearHook(operation, model, type) {
92
+ const key = `${operation}:${model}`;
93
+ if (!type || type === 'before') {
94
+ beforeHooks.set(key, []);
95
+ }
96
+ if (!type || type === 'after') {
97
+ afterHooks.set(key, []);
98
+ }
99
+ }
100
+ /**
101
+ * Clear all hooks (useful for testing).
102
+ */
103
+ export function clearAllHooks() {
104
+ beforeHooks.clear();
105
+ afterHooks.clear();
106
+ }
@@ -0,0 +1,14 @@
1
+ import Model from './model.js';
2
+ import View from './view.js';
3
+ import Serializer from './serializer.js';
4
+ import attr from './attr.js';
5
+ import belongsTo from './belongs-to.js';
6
+ import hasMany from './has-many.js';
7
+ import { createRecord, updateRecord } from './manage-record.js';
8
+ import { count, avg, sum, min, max } from './aggregates.js';
9
+ export { default } from './main.js';
10
+ export { store, relationships } from './main.js';
11
+ export { Model, View, Serializer };
12
+ export { attr, belongsTo, hasMany, createRecord, updateRecord };
13
+ export { count, avg, sum, min, max };
14
+ export { beforeHook, afterHook, clearHook, clearAllHooks } from './hooks.js';
package/dist/index.js ADDED
@@ -0,0 +1,34 @@
1
+ /*
2
+ * Copyright 2025 Stone Costa
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the 'License');
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import Model from './model.js';
17
+ import View from './view.js';
18
+ import Serializer from './serializer.js';
19
+ import attr from './attr.js';
20
+ import belongsTo from './belongs-to.js';
21
+ import hasMany from './has-many.js';
22
+ import { createRecord, updateRecord } from './manage-record.js';
23
+ import { count, avg, sum, min, max } from './aggregates.js';
24
+ export { default } from './main.js';
25
+ export { store, relationships } from './main.js';
26
+ export { Model, View, Serializer }; // base classes
27
+ export { attr, belongsTo, hasMany, createRecord, updateRecord }; // helpers
28
+ export { count, avg, sum, min, max }; // aggregate helpers
29
+ export { beforeHook, afterHook, clearHook, clearAllHooks } from './hooks.js'; // middleware hooks
30
+ // Store API:
31
+ // store.get(model, id) -- sync, memory-only
32
+ // store.find(model, id) -- async, MySQL for memory:false models
33
+ // store.findAll(model) -- async, all records
34
+ // store.query(model, conditions) -- async, always hits MySQL
package/dist/main.d.ts ADDED
@@ -0,0 +1,46 @@
1
+ import Store from './store.js';
2
+ interface OrmOptions {
3
+ dbType?: string;
4
+ }
5
+ export interface SqlDb {
6
+ init(): Promise<unknown>;
7
+ startup(): Promise<void>;
8
+ shutdown(): Promise<void>;
9
+ persist(operation: string, model: string, context: unknown, response: unknown): Promise<void>;
10
+ findRecord(modelName: string, id: unknown): Promise<unknown>;
11
+ findAll(modelName: string, conditions?: Record<string, unknown>): Promise<unknown[]>;
12
+ }
13
+ export interface OrmDB {
14
+ record: unknown;
15
+ save(): Promise<void>;
16
+ init(): Promise<void>;
17
+ }
18
+ export default class Orm {
19
+ static initialized: boolean;
20
+ static relationships: Map<string, Map<string, unknown>>;
21
+ static store: Store;
22
+ static instance: Orm;
23
+ static ready: unknown[];
24
+ models: Record<string, unknown>;
25
+ serializers: Record<string, unknown>;
26
+ views: Record<string, unknown>;
27
+ transforms: Record<string, (value: unknown) => unknown>;
28
+ warnings: Set<string>;
29
+ options: OrmOptions;
30
+ sqlDb?: SqlDb;
31
+ db?: OrmDB | SqlDb;
32
+ constructor(options?: OrmOptions);
33
+ init(): Promise<void>;
34
+ startup(): Promise<void>;
35
+ shutdown(): Promise<void>;
36
+ static get db(): OrmDB | SqlDb;
37
+ getRecordClasses(modelName: string): {
38
+ modelClass: unknown;
39
+ serializerClass: unknown;
40
+ };
41
+ isView(modelName: string): boolean;
42
+ warn(message: string): void;
43
+ }
44
+ export declare const store: Store;
45
+ export declare const relationships: Map<string, Map<string, unknown>>;
46
+ export {};