@stonyx/orm 0.2.5-alpha.0 → 0.3.1

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 (166) hide show
  1. package/README.md +482 -15
  2. package/config/environment.js +63 -6
  3. package/dist/aggregates.d.ts +21 -0
  4. package/dist/aggregates.js +93 -0
  5. package/dist/attr.d.ts +2 -0
  6. package/dist/attr.js +22 -0
  7. package/dist/belongs-to.d.ts +11 -0
  8. package/dist/belongs-to.js +59 -0
  9. package/dist/cli.d.ts +22 -0
  10. package/dist/cli.js +148 -0
  11. package/dist/commands.d.ts +7 -0
  12. package/dist/commands.js +146 -0
  13. package/dist/db.d.ts +21 -0
  14. package/dist/db.js +180 -0
  15. package/dist/exports/db.d.ts +7 -0
  16. package/{src → dist}/exports/db.js +2 -4
  17. package/dist/has-many.d.ts +11 -0
  18. package/dist/has-many.js +58 -0
  19. package/dist/hooks.d.ts +75 -0
  20. package/dist/hooks.js +110 -0
  21. package/dist/index.d.ts +14 -0
  22. package/dist/index.js +34 -0
  23. package/dist/main.d.ts +46 -0
  24. package/dist/main.js +181 -0
  25. package/dist/manage-record.d.ts +13 -0
  26. package/dist/manage-record.js +123 -0
  27. package/dist/meta-request.d.ts +6 -0
  28. package/dist/meta-request.js +52 -0
  29. package/dist/migrate.d.ts +2 -0
  30. package/dist/migrate.js +57 -0
  31. package/dist/model-property.d.ts +9 -0
  32. package/dist/model-property.js +29 -0
  33. package/dist/model.d.ts +15 -0
  34. package/dist/model.js +18 -0
  35. package/dist/mysql/connection.d.ts +14 -0
  36. package/dist/mysql/connection.js +24 -0
  37. package/dist/mysql/migration-generator.d.ts +45 -0
  38. package/dist/mysql/migration-generator.js +254 -0
  39. package/dist/mysql/migration-runner.d.ts +12 -0
  40. package/dist/mysql/migration-runner.js +88 -0
  41. package/dist/mysql/mysql-db.d.ts +100 -0
  42. package/dist/mysql/mysql-db.js +425 -0
  43. package/dist/mysql/query-builder.d.ts +10 -0
  44. package/dist/mysql/query-builder.js +44 -0
  45. package/dist/mysql/schema-introspector.d.ts +19 -0
  46. package/dist/mysql/schema-introspector.js +257 -0
  47. package/dist/mysql/type-map.d.ts +21 -0
  48. package/dist/mysql/type-map.js +36 -0
  49. package/dist/orm-request.d.ts +38 -0
  50. package/dist/orm-request.js +475 -0
  51. package/dist/plural-registry.d.ts +4 -0
  52. package/dist/plural-registry.js +9 -0
  53. package/dist/postgres/connection.d.ts +15 -0
  54. package/dist/postgres/connection.js +32 -0
  55. package/dist/postgres/migration-generator.d.ts +45 -0
  56. package/dist/postgres/migration-generator.js +280 -0
  57. package/dist/postgres/migration-runner.d.ts +10 -0
  58. package/dist/postgres/migration-runner.js +87 -0
  59. package/dist/postgres/postgres-db.d.ts +119 -0
  60. package/dist/postgres/postgres-db.js +477 -0
  61. package/dist/postgres/query-builder.d.ts +27 -0
  62. package/dist/postgres/query-builder.js +98 -0
  63. package/dist/postgres/schema-introspector.d.ts +29 -0
  64. package/dist/postgres/schema-introspector.js +296 -0
  65. package/dist/postgres/type-map.d.ts +23 -0
  66. package/dist/postgres/type-map.js +56 -0
  67. package/dist/record.d.ts +75 -0
  68. package/dist/record.js +129 -0
  69. package/dist/relationships.d.ts +10 -0
  70. package/dist/relationships.js +41 -0
  71. package/dist/schema-helpers.d.ts +20 -0
  72. package/dist/schema-helpers.js +48 -0
  73. package/dist/serializer.d.ts +17 -0
  74. package/dist/serializer.js +136 -0
  75. package/dist/setup-rest-server.d.ts +1 -0
  76. package/dist/setup-rest-server.js +52 -0
  77. package/dist/standalone-db.d.ts +58 -0
  78. package/dist/standalone-db.js +142 -0
  79. package/dist/store.d.ts +62 -0
  80. package/dist/store.js +286 -0
  81. package/dist/timescale/query-builder.d.ts +43 -0
  82. package/dist/timescale/query-builder.js +115 -0
  83. package/dist/timescale/timescale-db.d.ts +45 -0
  84. package/dist/timescale/timescale-db.js +84 -0
  85. package/dist/transforms.d.ts +2 -0
  86. package/dist/transforms.js +17 -0
  87. package/dist/types/orm-types.d.ts +153 -0
  88. package/dist/types/orm-types.js +1 -0
  89. package/dist/utils.d.ts +7 -0
  90. package/dist/utils.js +17 -0
  91. package/dist/view-resolver.d.ts +8 -0
  92. package/dist/view-resolver.js +171 -0
  93. package/dist/view.d.ts +11 -0
  94. package/dist/view.js +18 -0
  95. package/package.json +64 -11
  96. package/src/aggregates.ts +109 -0
  97. package/src/{attr.js → attr.ts} +2 -2
  98. package/src/belongs-to.ts +90 -0
  99. package/src/cli.ts +183 -0
  100. package/src/commands.ts +179 -0
  101. package/src/db.ts +232 -0
  102. package/src/exports/db.ts +7 -0
  103. package/src/has-many.ts +92 -0
  104. package/src/hooks.ts +151 -0
  105. package/src/{index.js → index.ts} +12 -2
  106. package/src/main.ts +229 -0
  107. package/src/manage-record.ts +161 -0
  108. package/src/{meta-request.js → meta-request.ts} +17 -14
  109. package/src/migrate.ts +72 -0
  110. package/src/model-property.ts +35 -0
  111. package/src/model.ts +21 -0
  112. package/src/mysql/connection.ts +43 -0
  113. package/src/mysql/migration-generator.ts +337 -0
  114. package/src/mysql/migration-runner.ts +121 -0
  115. package/src/mysql/mysql-db.ts +543 -0
  116. package/src/mysql/query-builder.ts +69 -0
  117. package/src/mysql/schema-introspector.ts +310 -0
  118. package/src/mysql/type-map.ts +42 -0
  119. package/src/orm-request.ts +582 -0
  120. package/src/plural-registry.ts +12 -0
  121. package/src/postgres/connection.ts +48 -0
  122. package/src/postgres/migration-generator.ts +370 -0
  123. package/src/postgres/migration-runner.ts +115 -0
  124. package/src/postgres/postgres-db.ts +616 -0
  125. package/src/postgres/query-builder.ts +148 -0
  126. package/src/postgres/schema-introspector.ts +360 -0
  127. package/src/postgres/type-map.ts +61 -0
  128. package/src/record.ts +186 -0
  129. package/src/relationships.ts +54 -0
  130. package/src/schema-helpers.ts +59 -0
  131. package/src/serializer.ts +161 -0
  132. package/src/setup-rest-server.ts +62 -0
  133. package/src/standalone-db.ts +185 -0
  134. package/src/store.ts +373 -0
  135. package/src/timescale/query-builder.ts +174 -0
  136. package/src/timescale/timescale-db.ts +119 -0
  137. package/src/transforms.ts +20 -0
  138. package/src/types/mysql2.d.ts +49 -0
  139. package/src/types/orm-types.ts +158 -0
  140. package/src/types/pg.d.ts +32 -0
  141. package/src/types/stonyx-cron.d.ts +5 -0
  142. package/src/types/stonyx-events.d.ts +4 -0
  143. package/src/types/stonyx-rest-server.d.ts +16 -0
  144. package/src/types/stonyx-utils.d.ts +33 -0
  145. package/src/types/stonyx.d.ts +21 -0
  146. package/src/utils.ts +22 -0
  147. package/src/view-resolver.ts +211 -0
  148. package/src/view.ts +22 -0
  149. package/.claude/project-structure.md +0 -578
  150. package/.github/workflows/ci.yml +0 -36
  151. package/.github/workflows/publish.yml +0 -143
  152. package/src/belongs-to.js +0 -63
  153. package/src/db.js +0 -80
  154. package/src/has-many.js +0 -61
  155. package/src/main.js +0 -119
  156. package/src/manage-record.js +0 -103
  157. package/src/model-property.js +0 -29
  158. package/src/model.js +0 -9
  159. package/src/orm-request.js +0 -249
  160. package/src/record.js +0 -100
  161. package/src/relationships.js +0 -43
  162. package/src/serializer.js +0 -138
  163. package/src/setup-rest-server.js +0 -57
  164. package/src/store.js +0 -211
  165. package/src/transforms.js +0 -20
  166. package/stonyx-bootstrap.cjs +0 -30
package/dist/main.js ADDED
@@ -0,0 +1,181 @@
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 DB from './db.js';
17
+ import config from 'stonyx/config';
18
+ import log from 'stonyx/log';
19
+ import { forEachFileImport } from '@stonyx/utils/file';
20
+ import { kebabCaseToPascalCase, pluralize } from '@stonyx/utils/string';
21
+ import { registerPluralName } from './plural-registry.js';
22
+ import setupRestServer from './setup-rest-server.js';
23
+ import baseTransforms from './transforms.js';
24
+ import Store from './store.js';
25
+ import Serializer from './serializer.js';
26
+ import { setup } from '@stonyx/events';
27
+ const defaultOptions = {
28
+ dbType: 'json'
29
+ };
30
+ export default class Orm {
31
+ static initialized = false;
32
+ static relationships = new Map();
33
+ static store = new Store();
34
+ static instance;
35
+ static ready;
36
+ models = {};
37
+ serializers = {};
38
+ views = {};
39
+ transforms = { ...baseTransforms };
40
+ warnings = new Set();
41
+ options;
42
+ sqlDb;
43
+ db;
44
+ constructor(options = {}) {
45
+ if (Orm.instance)
46
+ return Orm.instance;
47
+ const { relationships } = Orm;
48
+ // Declare relationship maps
49
+ for (const key of ['hasMany', 'belongsTo', 'global', 'pending', 'pendingBelongsTo']) {
50
+ relationships.set(key, new Map());
51
+ }
52
+ this.options = { ...defaultOptions, ...options };
53
+ Orm.instance = this;
54
+ }
55
+ async init() {
56
+ const { paths, restServer } = config.orm;
57
+ const promises = ['Model', 'Serializer', 'Transform'].map(type => {
58
+ const lowerCaseType = type.toLowerCase();
59
+ const path = paths[lowerCaseType];
60
+ if (!path)
61
+ throw new Error(`Configuration Error: ORM path for "${type}" must be defined.`);
62
+ return forEachFileImport(path, (exported, { name }) => {
63
+ // Transforms keep their original name, everything else gets converted to PascalCase with the type suffix
64
+ const alias = type === 'Transform' ? name : `${kebabCaseToPascalCase(name)}${type}`;
65
+ if (type === 'Model') {
66
+ Orm.store.set(name, new Map());
67
+ registerPluralName(name, exported);
68
+ }
69
+ const collection = this[pluralize(lowerCaseType)];
70
+ return collection[alias] = exported;
71
+ }, { ignoreAccessFailure: true, rawName: true, recursive: true, recursiveNaming: true });
72
+ });
73
+ // Wait for imports before db & rest server setup
74
+ await Promise.all(promises);
75
+ // Discover views from paths.view (separate from model/serializer/transform)
76
+ if (paths.view) {
77
+ await forEachFileImport(paths.view, (exported, { name }) => {
78
+ const alias = `${kebabCaseToPascalCase(name)}View`;
79
+ Orm.store.set(name, new Map());
80
+ registerPluralName(name, exported);
81
+ this.views[alias] = exported;
82
+ }, { ignoreAccessFailure: true, rawName: true, recursive: true, recursiveNaming: true });
83
+ }
84
+ // Setup event names for hooks after models are loaded
85
+ const eventNames = [];
86
+ const operations = ['list', 'get', 'create', 'update', 'delete'];
87
+ const viewOperations = ['list', 'get'];
88
+ const timings = ['before', 'after'];
89
+ for (const modelName of Orm.store.data.keys()) {
90
+ const isView = this.isView(modelName);
91
+ const ops = isView ? viewOperations : operations;
92
+ for (const timing of timings) {
93
+ for (const operation of ops) {
94
+ eventNames.push(`${timing}:${operation}:${modelName}`);
95
+ }
96
+ }
97
+ }
98
+ setup(eventNames);
99
+ if (config.orm.timescale) {
100
+ const { default: TimescaleDB } = await import('./timescale/timescale-db.js');
101
+ this.sqlDb = new TimescaleDB();
102
+ this.db = this.sqlDb;
103
+ promises.push(this.sqlDb.init());
104
+ }
105
+ else if (config.orm.postgres) {
106
+ const { default: PostgresDB } = await import('./postgres/postgres-db.js');
107
+ this.sqlDb = new PostgresDB();
108
+ this.db = this.sqlDb;
109
+ promises.push(this.sqlDb.init());
110
+ }
111
+ else if (config.orm.mysql) {
112
+ const { default: MysqlDB } = await import('./mysql/mysql-db.js');
113
+ this.sqlDb = new MysqlDB();
114
+ this.db = this.sqlDb;
115
+ promises.push(this.sqlDb.init());
116
+ }
117
+ else if (this.options.dbType !== 'none') {
118
+ const db = new DB();
119
+ this.db = db;
120
+ promises.push(db.init());
121
+ }
122
+ if (restServer.enabled === 'true') {
123
+ promises.push(setupRestServer(restServer.route, paths.access, restServer.metaRoute));
124
+ }
125
+ // Wire up memory resolver so store.find() can check model memory flags
126
+ Orm.store._memoryResolver = (modelName) => {
127
+ const { modelClass } = this.getRecordClasses(modelName);
128
+ return modelClass?.memory === true;
129
+ };
130
+ // Wire up SQL adapter reference for on-demand queries from store.find()/findAll()
131
+ if (this.sqlDb) {
132
+ Orm.store._sqlDb = this.sqlDb;
133
+ }
134
+ Orm.ready = await Promise.all(promises);
135
+ Orm.initialized = true;
136
+ }
137
+ async startup() {
138
+ if (this.sqlDb)
139
+ await this.sqlDb.startup();
140
+ }
141
+ async shutdown() {
142
+ if (this.sqlDb)
143
+ await this.sqlDb.shutdown();
144
+ }
145
+ static get db() {
146
+ if (!Orm.initialized)
147
+ throw new Error('ORM has not been initialized yet');
148
+ if (!Orm.instance.db)
149
+ throw new Error('ORM database has not been initialized');
150
+ return Orm.instance.db;
151
+ }
152
+ getRecordClasses(modelName) {
153
+ const modelClassPrefix = kebabCaseToPascalCase(modelName);
154
+ // Check views first, then models
155
+ const viewClass = this.views[`${modelClassPrefix}View`];
156
+ if (viewClass) {
157
+ return {
158
+ modelClass: viewClass,
159
+ serializerClass: this.serializers[`${modelClassPrefix}Serializer`] || Serializer
160
+ };
161
+ }
162
+ return {
163
+ modelClass: this.models[`${modelClassPrefix}Model`],
164
+ serializerClass: this.serializers[`${modelClassPrefix}Serializer`] || Serializer
165
+ };
166
+ }
167
+ isView(modelName) {
168
+ const modelClassPrefix = kebabCaseToPascalCase(modelName);
169
+ return !!this.views[`${modelClassPrefix}View`];
170
+ }
171
+ // Queue warnings to avoid the same error from being logged in the same iteration
172
+ warn(message) {
173
+ this.warnings.add(message);
174
+ setTimeout(() => {
175
+ this.warnings.forEach(warning => log.warn?.(warning));
176
+ this.warnings.clear();
177
+ }, 0);
178
+ }
179
+ }
180
+ export const store = Orm.store;
181
+ export const relationships = Orm.relationships;
@@ -0,0 +1,13 @@
1
+ import OrmRecord from './record.js';
2
+ interface CreateRecordOptions {
3
+ isDbRecord?: boolean;
4
+ serialize?: boolean;
5
+ transform?: boolean;
6
+ update?: boolean;
7
+ [key: string]: unknown;
8
+ }
9
+ export declare function createRecord(modelName: string, rawData?: {
10
+ [key: string]: unknown;
11
+ }, userOptions?: CreateRecordOptions): OrmRecord;
12
+ export declare function updateRecord(record: OrmRecord, rawData: unknown, userOptions?: CreateRecordOptions): void;
13
+ export {};
@@ -0,0 +1,123 @@
1
+ import Orm, { store } from '@stonyx/orm';
2
+ import OrmRecord from './record.js';
3
+ import { getGlobalRegistry, getPendingRegistry, getPendingBelongsToRegistry, getBelongsToRegistry, getHasManyRegistry } from './relationships.js';
4
+ import { isOrmRecord } from './utils.js';
5
+ const defaultOptions = {
6
+ isDbRecord: false,
7
+ serialize: true,
8
+ transform: true
9
+ };
10
+ export function createRecord(modelName, rawData = {}, userOptions = {}) {
11
+ const orm = Orm.instance;
12
+ const { initialized } = Orm;
13
+ const options = { ...defaultOptions, ...userOptions };
14
+ if (!initialized && !options.isDbRecord)
15
+ throw new Error('ORM is not ready');
16
+ // Guard: read-only views cannot have records created directly
17
+ if (orm?.isView?.(modelName) && !options.isDbRecord) {
18
+ throw new Error(`Cannot create records for read-only view '${modelName}'`);
19
+ }
20
+ const modelStore = store.get(modelName);
21
+ const globalRelationships = getGlobalRegistry();
22
+ const pendingRelationships = getPendingRegistry();
23
+ if (!modelStore)
24
+ throw new Error(`Model store for '${modelName}' is not registered. Ensure the model is defined before creating records.`);
25
+ assignRecordId(modelName, rawData);
26
+ const existingRecord = modelStore.get(rawData.id);
27
+ if (existingRecord instanceof OrmRecord) {
28
+ // Update the existing record with new data so the last entry wins
29
+ updateRecord(existingRecord, rawData, { ...options, update: true });
30
+ return existingRecord;
31
+ }
32
+ const recordClasses = orm.getRecordClasses(modelName);
33
+ const modelClass = recordClasses.modelClass;
34
+ const serializerClass = recordClasses.serializerClass;
35
+ if (!modelClass)
36
+ throw new Error(`A model named '${modelName}' does not exist`);
37
+ const model = new modelClass(modelName);
38
+ const serializer = new serializerClass(model);
39
+ const record = new OrmRecord(model, serializer);
40
+ record.serialize(rawData, options);
41
+ modelStore.set(record.id, record);
42
+ // populate global hasMany relationships
43
+ const globalHasMany = globalRelationships.get(modelName);
44
+ if (globalHasMany)
45
+ for (const relationship of globalHasMany)
46
+ relationship.push(record);
47
+ // populate pending hasMany relationships and clear the queue
48
+ const pendingHasMany = pendingRelationships.get(modelName)?.get(record.id);
49
+ if (pendingHasMany) {
50
+ for (const relationship of pendingHasMany)
51
+ relationship.push(record);
52
+ pendingHasMany.splice(0);
53
+ }
54
+ // Fulfill pending belongsTo relationships
55
+ const pendingBelongsToQueue = getPendingBelongsToRegistry();
56
+ const pendingBelongsToRaw = pendingBelongsToQueue.get(modelName)?.get(record.id);
57
+ const pendingBelongsTo = Array.isArray(pendingBelongsToRaw) ? pendingBelongsToRaw : undefined;
58
+ if (pendingBelongsTo) {
59
+ const belongsToReg = getBelongsToRegistry();
60
+ const hasManyReg = getHasManyRegistry();
61
+ for (const { sourceRecord, sourceModelName, relationshipKey, relationshipId } of pendingBelongsTo) {
62
+ // Update the belongsTo relationship on the source record
63
+ sourceRecord.__relationships[relationshipKey] = record;
64
+ sourceRecord[relationshipKey] = record; // Also update the direct property
65
+ // Update the belongsTo relationship registry
66
+ const sourceModelReg = belongsToReg.get(sourceModelName);
67
+ if (sourceModelReg) {
68
+ const targetModelReg = sourceModelReg.get(modelName);
69
+ if (targetModelReg) {
70
+ targetModelReg.set(relationshipId, record);
71
+ }
72
+ }
73
+ // Wire inverse hasMany if it exists
74
+ const inverseHasMany = hasManyReg.get(modelName)?.get(sourceModelName)?.get(record.id);
75
+ if (inverseHasMany && !inverseHasMany.includes(sourceRecord)) {
76
+ inverseHasMany.push(sourceRecord);
77
+ }
78
+ }
79
+ // Clear the pending queue
80
+ pendingBelongsTo.length = 0;
81
+ }
82
+ return record;
83
+ }
84
+ export function updateRecord(record, rawData, userOptions = {}) {
85
+ if (!rawData)
86
+ throw new Error('rawData must be passed in to updateRecord call');
87
+ // Guard: read-only views cannot be updated
88
+ const modelName = record?.__model?.__name;
89
+ if (modelName && Orm.instance?.isView?.(modelName)) {
90
+ throw new Error(`Cannot update records for read-only view '${modelName}'`);
91
+ }
92
+ const options = { ...defaultOptions, ...userOptions, update: true };
93
+ record.serialize(rawData, options);
94
+ }
95
+ /**
96
+ * gets the next available id based on last record entry.
97
+ *
98
+ * In MySQL mode with numeric IDs, assigns a temporary pending ID.
99
+ * MySQL's AUTO_INCREMENT provides the real ID after INSERT.
100
+ */
101
+ function assignRecordId(modelName, rawData) {
102
+ if (rawData.id)
103
+ return;
104
+ // In SQL mode with numeric IDs, defer to database auto-increment
105
+ if (Orm.instance?.sqlDb && !isStringIdModel(modelName)) {
106
+ rawData.id = `__pending_${Date.now()}_${Math.random()}`;
107
+ rawData.__pendingSqlId = true;
108
+ return;
109
+ }
110
+ const storeMap = store.get(modelName);
111
+ if (!storeMap)
112
+ throw new Error(`Cannot assign record ID: model "${modelName}" not found in store`);
113
+ const modelStore = Array.from(storeMap.values()).filter(isOrmRecord);
114
+ const lastRecord = modelStore.at(-1);
115
+ rawData.id = lastRecord ? lastRecord.id + 1 : 1;
116
+ }
117
+ function isStringIdModel(modelName) {
118
+ const modelClass = Orm.instance.getRecordClasses(modelName).modelClass;
119
+ if (!modelClass)
120
+ return false;
121
+ const model = new modelClass(modelName);
122
+ return model.id?.type === 'string';
123
+ }
@@ -0,0 +1,6 @@
1
+ import { Request } from '@stonyx/rest-server';
2
+ export default class MetaRequest extends Request {
3
+ handlers: Record<string, unknown>;
4
+ constructor(...args: unknown[]);
5
+ auth(): number | undefined;
6
+ }
@@ -0,0 +1,52 @@
1
+ import { Request } from '@stonyx/rest-server';
2
+ import ModelProperty from './model-property.js';
3
+ import Orm from '@stonyx/orm';
4
+ import config from 'stonyx/config';
5
+ import { dbKey } from './db.js';
6
+ export default class MetaRequest extends Request {
7
+ handlers;
8
+ constructor(...args) {
9
+ super(...args);
10
+ this.handlers = {
11
+ get: {
12
+ '/meta': () => {
13
+ try {
14
+ const { models } = Orm.instance;
15
+ const metadata = {};
16
+ for (const [modelName, modelClass] of Object.entries(models)) {
17
+ const name = modelName.slice(0, -5).toLowerCase();
18
+ if (name === dbKey)
19
+ continue;
20
+ const model = new modelClass(modelName);
21
+ const properties = {};
22
+ // Get regular properties and relationships
23
+ for (const [key, property] of Object.entries(model)) {
24
+ // Skip internal properties
25
+ if (key.startsWith('__'))
26
+ continue;
27
+ if (property instanceof ModelProperty) {
28
+ properties[key] = { type: property.type };
29
+ }
30
+ else if (typeof property === 'function') {
31
+ const isBelongsTo = property.__relationshipType === 'belongsTo';
32
+ const isHasMany = property.__relationshipType === 'hasMany';
33
+ if (isBelongsTo || isHasMany)
34
+ properties[key] = { [isBelongsTo ? 'belongsTo' : 'hasMany']: name };
35
+ }
36
+ }
37
+ metadata[name] = properties;
38
+ }
39
+ return metadata;
40
+ }
41
+ catch (error) {
42
+ return { error: error instanceof Error ? error.message : String(error) };
43
+ }
44
+ },
45
+ },
46
+ };
47
+ }
48
+ auth() {
49
+ if (!config.orm.restServer.metaRoute)
50
+ return 403;
51
+ }
52
+ }
@@ -0,0 +1,2 @@
1
+ export declare function fileToDirectory(): Promise<void>;
2
+ export declare function directoryToFile(): Promise<void>;
@@ -0,0 +1,57 @@
1
+ import config from 'stonyx/config';
2
+ import Orm from '@stonyx/orm';
3
+ import { createFile, createDirectory, readFile, updateFile, deleteDirectory } from '@stonyx/utils/file';
4
+ import { dbKey } from './db.js';
5
+ import path from 'path';
6
+ function getCollectionKeys() {
7
+ const SchemaClass = Orm.instance.models[`${dbKey}Model`];
8
+ const instance = new SchemaClass();
9
+ const keys = [];
10
+ for (const key of Object.keys(instance)) {
11
+ if (key === '__name' || key === 'id')
12
+ continue;
13
+ if (typeof instance[key] === 'function')
14
+ keys.push(key);
15
+ }
16
+ return keys;
17
+ }
18
+ function getDirPath() {
19
+ const { rootPath } = config;
20
+ const { file, directory } = config.orm.db;
21
+ const dbDir = path.dirname(path.resolve(`${rootPath}/${file}`));
22
+ return path.join(dbDir, directory);
23
+ }
24
+ export async function fileToDirectory() {
25
+ const { rootPath } = config;
26
+ const { file } = config.orm.db;
27
+ const dbFilePath = path.resolve(`${rootPath}/${file}`);
28
+ const collectionKeys = getCollectionKeys();
29
+ const dirPath = getDirPath();
30
+ // Read full data from db.json
31
+ const data = await readFile(dbFilePath, { json: true });
32
+ // Create directory and write each collection
33
+ await createDirectory(dirPath);
34
+ await Promise.all(collectionKeys.map(key => createFile(path.join(dirPath, `${key}.json`), data[key] || [], { json: true })));
35
+ // Overwrite db.json with empty-array skeleton
36
+ const skeleton = {};
37
+ for (const key of collectionKeys)
38
+ skeleton[key] = [];
39
+ await updateFile(dbFilePath, skeleton, { json: true });
40
+ }
41
+ export async function directoryToFile() {
42
+ const { rootPath } = config;
43
+ const { file } = config.orm.db;
44
+ const dbFilePath = path.resolve(`${rootPath}/${file}`);
45
+ const collectionKeys = getCollectionKeys();
46
+ const dirPath = getDirPath();
47
+ // Read each collection from the directory
48
+ const assembled = {};
49
+ await Promise.all(collectionKeys.map(async (key) => {
50
+ const filePath = path.join(dirPath, `${key}.json`);
51
+ assembled[key] = await readFile(filePath, { json: true });
52
+ }));
53
+ // Overwrite db.json with full assembled data
54
+ await updateFile(dbFilePath, assembled, { json: true });
55
+ // Remove the directory
56
+ await deleteDirectory(dirPath);
57
+ }
@@ -0,0 +1,9 @@
1
+ export default class ModelProperty {
2
+ readonly __kind: "ModelProperty";
3
+ type: string;
4
+ private _value;
5
+ ignoreFirstTransform?: boolean;
6
+ constructor(type?: string, defaultValue?: unknown);
7
+ get value(): unknown;
8
+ set value(newValue: unknown);
9
+ }
@@ -0,0 +1,29 @@
1
+ import Orm from '@stonyx/orm';
2
+ function validType(type) {
3
+ return Object.keys(Orm.instance.transforms).includes(type);
4
+ }
5
+ export default class ModelProperty {
6
+ __kind = 'ModelProperty';
7
+ type;
8
+ _value;
9
+ ignoreFirstTransform;
10
+ constructor(type = 'passthrough', defaultValue) {
11
+ if (!validType(type))
12
+ throw new Error(`Invalid model property type: ${type}`);
13
+ this.type = type;
14
+ this.value = defaultValue;
15
+ }
16
+ get value() {
17
+ return this._value;
18
+ }
19
+ set value(newValue) {
20
+ if (this.ignoreFirstTransform) {
21
+ delete this.ignoreFirstTransform;
22
+ this._value = newValue;
23
+ return;
24
+ }
25
+ if (newValue === undefined)
26
+ return;
27
+ this._value = newValue === null ? null : Orm.instance.transforms[this.type](newValue);
28
+ }
29
+ }
@@ -0,0 +1,15 @@
1
+ export default class Model {
2
+ /**
3
+ * Controls whether records of this model are loaded into memory on startup.
4
+ *
5
+ * - true → loaded on boot, kept in store
6
+ * - false → never cached; find() always queries MySQL (default)
7
+ *
8
+ * Override in subclass: static memory = true;
9
+ */
10
+ static memory: boolean;
11
+ static pluralName: string | undefined;
12
+ id: import("./model-property.js").default;
13
+ __name: string;
14
+ constructor(name: string);
15
+ }
package/dist/model.js ADDED
@@ -0,0 +1,18 @@
1
+ import attr from './attr.js';
2
+ export default class Model {
3
+ /**
4
+ * Controls whether records of this model are loaded into memory on startup.
5
+ *
6
+ * - true → loaded on boot, kept in store
7
+ * - false → never cached; find() always queries MySQL (default)
8
+ *
9
+ * Override in subclass: static memory = true;
10
+ */
11
+ static memory = false;
12
+ static pluralName = undefined;
13
+ id = attr('number');
14
+ __name;
15
+ constructor(name) {
16
+ this.__name = name;
17
+ }
18
+ }
@@ -0,0 +1,14 @@
1
+ import type { Pool } from 'mysql2/promise';
2
+ interface MysqlConfig {
3
+ host: string;
4
+ port?: number;
5
+ user: string;
6
+ password: string;
7
+ database: string;
8
+ connectionLimit?: number;
9
+ migrationsTable?: string;
10
+ migrationsDir?: string;
11
+ }
12
+ export declare function getPool(mysqlConfig: MysqlConfig): Promise<Pool>;
13
+ export declare function closePool(): Promise<void>;
14
+ export type { MysqlConfig };
@@ -0,0 +1,24 @@
1
+ let pool = null;
2
+ export async function getPool(mysqlConfig) {
3
+ if (pool)
4
+ return pool;
5
+ const mysql = await import('mysql2/promise');
6
+ pool = mysql.createPool({
7
+ host: mysqlConfig.host,
8
+ port: mysqlConfig.port,
9
+ user: mysqlConfig.user,
10
+ password: mysqlConfig.password,
11
+ database: mysqlConfig.database,
12
+ connectionLimit: mysqlConfig.connectionLimit,
13
+ waitForConnections: true,
14
+ enableKeepAlive: true,
15
+ keepAliveInitialDelay: 10000,
16
+ });
17
+ return pool;
18
+ }
19
+ export async function closePool() {
20
+ if (!pool)
21
+ return;
22
+ await pool.end();
23
+ pool = null;
24
+ }
@@ -0,0 +1,45 @@
1
+ import type { ModelSchema, SnapshotEntry, ViewSnapshotEntry, ForeignKeyDef } from './schema-introspector.js';
2
+ interface ColumnChange {
3
+ model: string;
4
+ column: string;
5
+ type: string;
6
+ }
7
+ interface ColumnTypeChange {
8
+ model: string;
9
+ column: string;
10
+ from: string;
11
+ to: string;
12
+ }
13
+ interface ForeignKeyChange {
14
+ model: string;
15
+ column: string;
16
+ references: ForeignKeyDef;
17
+ }
18
+ interface SnapshotDiff {
19
+ hasChanges: boolean;
20
+ addedModels: string[];
21
+ removedModels: string[];
22
+ addedColumns: ColumnChange[];
23
+ removedColumns: ColumnChange[];
24
+ changedColumns: ColumnTypeChange[];
25
+ addedForeignKeys: ForeignKeyChange[];
26
+ removedForeignKeys: ForeignKeyChange[];
27
+ }
28
+ interface ViewDiff {
29
+ hasChanges: boolean;
30
+ addedViews: string[];
31
+ removedViews: string[];
32
+ changedViews: string[];
33
+ }
34
+ interface GeneratedMigration {
35
+ filename: string;
36
+ content: string;
37
+ snapshot: Record<string, SnapshotEntry | ViewSnapshotEntry>;
38
+ }
39
+ export declare function generateMigration(description?: string): Promise<GeneratedMigration | null>;
40
+ export declare function loadLatestSnapshot(migrationsPath: string): Promise<Record<string, unknown>>;
41
+ export declare function diffSnapshots(previous: Record<string, SnapshotEntry>, current: Record<string, SnapshotEntry>): SnapshotDiff;
42
+ export declare function detectSchemaDrift(schemas: Record<string, ModelSchema>, snapshot: Record<string, SnapshotEntry>): SnapshotDiff;
43
+ export declare function extractViewsFromSnapshot(snapshot: Record<string, unknown>): Record<string, ViewSnapshotEntry>;
44
+ export declare function diffViewSnapshots(previous: Record<string, ViewSnapshotEntry>, current: Record<string, ViewSnapshotEntry>): ViewDiff;
45
+ export {};