dynamo-bao 0.2.4 → 0.2.6

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.
package/bin/codegen.js CHANGED
@@ -4,6 +4,7 @@ const fs = require("fs");
4
4
  const path = require("path");
5
5
  const yaml = require("js-yaml");
6
6
  const { generateModelFiles } = require("./generators/model");
7
+ const { generateManifestFile } = require("./generators/manifest");
7
8
  const { createLogger } = require("./utils/scriptLogger");
8
9
  const FieldResolver = require("../src/fieldResolver");
9
10
  const logger = createLogger("CodeGen");
@@ -99,14 +100,13 @@ function loadModelDefinitions(definitionsPath, fieldResolver) {
99
100
  function main() {
100
101
  const args = process.argv.slice(2);
101
102
 
102
- // Set default paths, but prefer config paths if available
103
- let definitionsPath = config?.paths?.modelsDefinitionPath
104
- ? path.resolve(process.cwd(), config.paths.modelsDefinitionPath)
105
- : path.resolve(process.cwd(), "./models.yaml");
103
+ // Paths should be pre-resolved by the config loader.
104
+ let definitionsPath =
105
+ config?.paths?.modelsDefinitionPath ||
106
+ path.resolve(process.cwd(), "./models.yaml");
106
107
 
107
- let outputDir = config?.paths?.modelsDir
108
- ? path.resolve(process.cwd(), config.paths.modelsDir)
109
- : path.resolve(process.cwd(), "./models");
108
+ let outputDir =
109
+ config?.paths?.modelsDir || path.resolve(process.cwd(), "./models");
110
110
 
111
111
  // Override with command line arguments if provided
112
112
  if (args.length >= 1) {
@@ -132,6 +132,16 @@ function main() {
132
132
  outputDir,
133
133
  definitions.fieldResolver,
134
134
  );
135
+
136
+ // After generating models, generate the manifest file
137
+ const manifestPath = config?.paths?.generatedModelsManifest;
138
+ if (outputDir && manifestPath) {
139
+ generateManifestFile(outputDir, manifestPath);
140
+ } else {
141
+ logger.warn(
142
+ "outputDir or generatedModelsManifest path not configured. Skipping manifest generation.",
143
+ );
144
+ }
135
145
  } catch (error) {
136
146
  console.error("Error generating models:", error);
137
147
  console.error("Stack trace:", error.stack);
@@ -139,8 +149,12 @@ function main() {
139
149
  }
140
150
  }
141
151
 
142
- if (require.main === module) {
152
+ function run() {
143
153
  main();
144
154
  }
145
155
 
146
- module.exports = { loadModelDefinitions };
156
+ if (require.main === module) {
157
+ run();
158
+ }
159
+
160
+ module.exports = { loadModelDefinitions, run };
@@ -0,0 +1,74 @@
1
+ const fs = require("fs");
2
+ const path = require("path");
3
+ const { createLogger } = require("../utils/scriptLogger");
4
+
5
+ const logger = createLogger("ManifestGenerator");
6
+
7
+ function findModelFiles(dir) {
8
+ let results = [];
9
+ const items = fs.readdirSync(dir);
10
+
11
+ items.forEach((item) => {
12
+ const fullPath = path.join(dir, item);
13
+ const stat = fs.statSync(fullPath);
14
+
15
+ if (stat.isDirectory()) {
16
+ results = results.concat(findModelFiles(fullPath));
17
+ } else if (item.endsWith(".js")) {
18
+ results.push(fullPath);
19
+ }
20
+ });
21
+
22
+ return results;
23
+ }
24
+
25
+ function generateManifestFile(modelsDir, manifestPath) {
26
+ logger.info(`Generating model manifest for directory: ${modelsDir}`);
27
+ logger.info(`Output manifest file: ${manifestPath}`);
28
+
29
+ if (!fs.existsSync(modelsDir)) {
30
+ logger.warn(
31
+ `Models directory does not exist, skipping manifest generation: ${modelsDir}`,
32
+ );
33
+ return;
34
+ }
35
+
36
+ const modelFiles = findModelFiles(modelsDir);
37
+ const manifestDir = path.dirname(manifestPath);
38
+
39
+ if (modelFiles.length === 0) {
40
+ logger.warn("No model files found to generate a manifest.");
41
+ return;
42
+ }
43
+
44
+ const imports = modelFiles
45
+ .map((file, index) => {
46
+ const relativePath = path.relative(manifestDir, file).replace(/\\/g, "/");
47
+ return `import * as model${index} from '${relativePath}';`;
48
+ })
49
+ .join("\n");
50
+
51
+ const exports = `export default {\n${modelFiles
52
+ .map((_, index) => ` ...model${index}`)
53
+ .join(",\n")}\n};`;
54
+
55
+ const content = `// THIS FILE IS AUTO-GENERATED by dynamo-bao codegen.
56
+ // DO NOT EDIT DIRECTLY.
57
+ ${imports}
58
+
59
+ ${exports}
60
+ `;
61
+
62
+ try {
63
+ if (!fs.existsSync(manifestDir)) {
64
+ fs.mkdirSync(manifestDir, { recursive: true });
65
+ }
66
+ fs.writeFileSync(manifestPath, content, "utf8");
67
+ logger.info("Model manifest generated successfully.");
68
+ } catch (error) {
69
+ logger.error("Error writing model manifest file:", error);
70
+ process.exit(1);
71
+ }
72
+ }
73
+
74
+ module.exports = { generateManifestFile };
package/bin/watch.js CHANGED
@@ -3,77 +3,67 @@
3
3
  const fs = require("fs");
4
4
  const path = require("path");
5
5
  const chokidar = require("chokidar");
6
- const { loadModelDefinitions } = require("./codegen");
7
- const { generateModelFiles } = require("./generators/model");
8
- const FieldResolver = require("../src/fieldResolver");
6
+ const { run: runCodegen } = require("./codegen");
9
7
  const { createLogger } = require("./utils/scriptLogger");
10
8
  const config = require("../src/config");
11
9
 
12
10
  const logger = createLogger("Watch");
13
11
 
14
- function getDefinitionsPath(config) {
15
- if (config.paths.modelsDefinitionPath) {
16
- const definitionPath = path.resolve(
17
- process.cwd(),
18
- config.paths.modelsDefinitionPath,
19
- );
20
- return definitionPath;
21
- }
22
- // Fall back to models.yaml in current directory
23
- return path.resolve(process.cwd(), "./models.yaml");
24
- }
25
-
26
- function generateModels(definitionsPath) {
27
- console.log(`Generating models from: ${definitionsPath}`);
28
- console.log(`Output directory: ${config.paths.modelsDir}`);
29
- console.log(`Fields directory: ${config.paths.fieldsDir}`);
30
-
31
- try {
32
- const definitions = loadModelDefinitions(definitionsPath);
33
- const builtInFieldsPath = path.resolve(__dirname, "../src/fields");
34
- const customFieldsPath = config.paths.fieldsDir;
35
-
36
- const fieldResolver = new FieldResolver(
37
- builtInFieldsPath,
38
- fs.existsSync(customFieldsPath) ? customFieldsPath : null,
39
- );
40
-
41
- generateModelFiles(
42
- definitions.models,
43
- config.paths.modelsDir,
44
- fieldResolver,
45
- );
46
- logger.info("Models generated successfully");
47
- } catch (error) {
48
- logger.error("Error generating models:", error);
49
- }
50
- }
51
-
52
12
  function main() {
53
13
  const definitionsPath = config.paths.modelsDefinitionPath
54
14
  ? path.resolve(process.cwd(), config.paths.modelsDefinitionPath)
55
15
  : path.resolve(process.cwd(), "./models.yaml");
56
16
 
17
+ const modelsDir = config.paths.modelsDir;
18
+
57
19
  // Initial generation
58
- generateModels(definitionsPath);
20
+ logger.info("Performing initial model generation...");
21
+ runCodegen();
59
22
 
60
23
  // Set up watcher with appropriate glob pattern
61
24
  const isDirectory = fs.statSync(definitionsPath).isDirectory();
62
- const watchPattern = isDirectory
25
+ const definitionWatchPattern = isDirectory
63
26
  ? path.join(definitionsPath, "**/*.{yaml,yml}") // Watch all yaml files in directory
64
27
  : definitionsPath; // Watch single file directly
65
28
 
66
- const watcher = chokidar.watch(watchPattern, {
29
+ const watchPatterns = [definitionWatchPattern];
30
+
31
+ if (modelsDir && fs.existsSync(modelsDir)) {
32
+ const modelsWatchPattern = path.join(modelsDir, "**/*.js");
33
+ watchPatterns.push(modelsWatchPattern);
34
+ logger.info(`Also watching for manual changes in: ${modelsDir}`);
35
+ }
36
+
37
+ const watcher = chokidar.watch(watchPatterns, {
67
38
  persistent: true,
68
39
  ignoreInitial: true,
69
40
  });
70
41
 
71
- console.log(`Watching for changes in: ${watchPattern}`);
42
+ logger.info(`Watching for changes in: ${watchPatterns.join(", ")}`);
43
+
44
+ const debouncedGenerate = debounce(() => {
45
+ logger.info("Change detected, running codegen...");
46
+ runCodegen();
47
+ }, 300);
72
48
 
73
49
  watcher
74
- .on("change", (path) => generateModels(path))
75
- .on("add", (path) => generateModels(path))
76
- .on("error", (error) => console.error(`Watcher error: ${error}`));
50
+ .on("all", (event, filePath) => {
51
+ logger.info(`File ${event}: ${filePath}. Regenerating...`);
52
+ debouncedGenerate();
53
+ })
54
+ .on("error", (error) => logger.error(`Watcher error: ${error}`));
55
+ }
56
+
57
+ function debounce(func, wait) {
58
+ let timeout;
59
+ return function executedFunction(...args) {
60
+ const later = () => {
61
+ clearTimeout(timeout);
62
+ func(...args);
63
+ };
64
+ clearTimeout(timeout);
65
+ timeout = setTimeout(later, wait);
66
+ };
77
67
  }
78
68
 
79
69
  if (require.main === module) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dynamo-bao",
3
- "version": "0.2.4",
3
+ "version": "0.2.6",
4
4
  "description": "Simple powerful data modeling primitives for DynamoDB in JavaScript.",
5
5
  "main": "src/index.js",
6
6
  "scripts": {
package/src/config.js CHANGED
@@ -64,19 +64,22 @@ function normalizeConfig(rawConfig, configDir) {
64
64
  return {
65
65
  ...rawConfig,
66
66
  paths: {
67
- ...rawConfig.paths,
68
- modelsDir: rawConfig.paths.modelsDir
67
+ ...(rawConfig.paths || {}),
68
+ modelsDir: rawConfig.paths?.modelsDir
69
69
  ? path.resolve(configDir, rawConfig.paths.modelsDir)
70
70
  : null,
71
- modelsDefinitionPath: rawConfig.paths.modelsDefinitionPath
71
+ modelsDefinitionPath: rawConfig.paths?.modelsDefinitionPath
72
72
  ? path.resolve(configDir, rawConfig.paths.modelsDefinitionPath)
73
73
  : null,
74
- fieldsDir: rawConfig.paths.fieldsDir
74
+ fieldsDir: rawConfig.paths?.fieldsDir
75
75
  ? path.resolve(configDir, rawConfig.paths.fieldsDir)
76
76
  : null,
77
+ generatedModelsManifest: rawConfig.paths?.generatedModelsManifest
78
+ ? path.resolve(configDir, rawConfig.paths.generatedModelsManifest)
79
+ : path.resolve(process.cwd(), ".bao/models.js"),
77
80
  },
78
81
  logging: {
79
- ...rawConfig.logging,
82
+ ...(rawConfig.logging || {}),
80
83
  // Allow environment variable to override config file
81
84
  level: process.env.LOG_LEVEL || rawConfig.logging?.level || "ERROR",
82
85
  },
package/src/index.js CHANGED
@@ -35,25 +35,67 @@ function findModelFiles(dir) {
35
35
  return results;
36
36
  }
37
37
 
38
- function _registerModels(manager = null, modelsDir = null) {
39
- if (!modelsDir) {
40
- throw new ConfigurationError("modelsDir is required");
38
+ function _registerModelsFromManifest(manager, manifestPath) {
39
+ try {
40
+ const allModels = require(manifestPath);
41
+ for (const ModelClass of Object.values(allModels.default || {})) {
42
+ if (ModelClass.prototype instanceof BaoModel) {
43
+ manager.registerModel(ModelClass);
44
+ }
45
+ }
46
+ return allModels.default ? Object.keys(allModels.default) : [];
47
+ } catch (err) {
48
+ if (err.code === "MODULE_NOT_FOUND") {
49
+ logger.warn(
50
+ `Model manifest not found at '${manifestPath}'. Falling back to directory scan. Please run codegen.`,
51
+ );
52
+ return null;
53
+ }
54
+ throw err;
41
55
  }
56
+ }
42
57
 
58
+ function _registerModelsFromDirectory(manager, modelsDir) {
59
+ if (!modelsDir || !fs.existsSync(modelsDir)) {
60
+ throw new ConfigurationError(
61
+ `modelsDir is not defined or does not exist: ${modelsDir}`,
62
+ );
63
+ }
43
64
  const modelFiles = findModelFiles(modelsDir);
44
65
  const models = {};
45
-
46
66
  modelFiles.forEach((file) => {
47
67
  const model = require(file);
48
68
  Object.entries(model).forEach(([name, ModelClass]) => {
49
- manager.registerModel(ModelClass);
50
- models[name] = ModelClass;
69
+ if (ModelClass.prototype instanceof BaoModel) {
70
+ manager.registerModel(ModelClass);
71
+ models[name] = ModelClass;
72
+ }
51
73
  });
52
74
  });
53
-
54
75
  return models;
55
76
  }
56
77
 
78
+ function _registerModels(manager, config) {
79
+ const manifestPath = config.paths.generatedModelsManifest;
80
+
81
+ // Try loading from manifest first
82
+ if (manifestPath) {
83
+ const manifestModels = _registerModelsFromManifest(manager, manifestPath);
84
+ if (manifestModels) {
85
+ // If manifest load was successful, we can return those.
86
+ // The actual model classes are in the manager. Here we just return names.
87
+ const models = {};
88
+ manager.getModels().forEach((modelClass) => {
89
+ models[modelClass.name] = modelClass;
90
+ });
91
+ return models;
92
+ }
93
+ }
94
+
95
+ // Fallback to directory scan if manifest fails or isn't specified
96
+ return _registerModelsFromDirectory(manager, config.paths.modelsDir);
97
+ }
98
+
57
99
  function initModels(userConfig = {}) {
58
100
  // Merge user config with default config
59
101
  const finalConfig = {
@@ -84,19 +126,19 @@ function initModels(userConfig = {}) {
84
126
 
85
127
  // Validate tenant context if tenancy enabled
86
128
  if (finalConfig.tenancy?.enabled) {
87
- const { TenantContext } = require('./tenant-context');
129
+ const { TenantContext } = require("./tenant-context");
88
130
  TenantContext.validateTenantRequired(finalConfig);
89
131
  }
90
132
 
91
133
  const modelsDir = finalConfig.paths.modelsDir;
92
134
 
93
135
  // Get/create manager instance with tenantId
94
- const { TenantContext } = require('./tenant-context');
136
+ const { TenantContext } = require("./tenant-context");
95
137
  const tenantId = TenantContext.getCurrentTenant() || finalConfig.testId;
96
138
  const manager = ModelManager.getInstance(tenantId);
97
139
 
98
140
  // First pass to register models
99
- const registeredModels = _registerModels(manager, modelsDir);
141
+ const registeredModels = _registerModels(manager, finalConfig);
100
142
 
101
143
  // Initialize the manager & 2nd model registration pass
102
144
  manager.init(finalConfig);
@@ -113,7 +155,7 @@ function initModels(userConfig = {}) {
113
155
  return manager;
114
156
  }
115
157
 
116
- const { TenantContext } = require('./tenant-context');
158
+ const { TenantContext } = require("./tenant-context");
117
159
 
118
160
  const firstExport = {
119
161
  // Initialize function