@holo-js/cli 0.2.6 → 0.3.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 (52) hide show
  1. package/dist/bin/holo.mjs +409 -104
  2. package/dist/{broadcast-JBQWQZSO.mjs → broadcast-5VZM5SGQ.mjs} +13 -11
  3. package/dist/{broadcast-YGJFCEPP.mjs → broadcast-AABT52BK.mjs} +10 -8
  4. package/dist/cache-A42JSVYA.mjs +138 -0
  5. package/dist/cache-DUVBBOZU.mjs +138 -0
  6. package/dist/{cache-migrations-77TLXIVG.mjs → cache-migrations-4WKSEN2Q.mjs} +12 -10
  7. package/dist/{cache-migrations-FKAHRP24.mjs → cache-migrations-PD2T5AV4.mjs} +14 -12
  8. package/dist/chunk-3RFRE7XG.mjs +491 -0
  9. package/dist/{chunk-7B2RVYLL.mjs → chunk-6BHJLCAO.mjs} +256 -392
  10. package/dist/{chunk-KS5TWO75.mjs → chunk-EQUFFLRG.mjs} +7 -7
  11. package/dist/chunk-HX6MOYBO.mjs +2 -0
  12. package/dist/{chunk-YEFJBN56.mjs → chunk-JVLZ3SOW.mjs} +11 -8
  13. package/dist/{chunk-4K4CWMMP.mjs → chunk-KRADH7PK.mjs} +53 -49
  14. package/dist/chunk-LALDNNPH.mjs +428 -0
  15. package/dist/chunk-LHK5YUR4.mjs +156 -0
  16. package/dist/{chunk-LBJAJLKU.mjs → chunk-M3IPUCTM.mjs} +1 -1
  17. package/dist/{chunk-C624G3R2.mjs → chunk-OI54DOHK.mjs} +256 -392
  18. package/dist/{chunk-LXGQCG56.mjs → chunk-OLZEMIDQ.mjs} +1 -1
  19. package/dist/{chunk-VP2E62DF.mjs → chunk-QSVMXMTQ.mjs} +49 -349
  20. package/dist/{chunk-J76GH2DR.mjs → chunk-R4ZYMEDU.mjs} +129 -86
  21. package/dist/{chunk-AJLRAC5M.mjs → chunk-TH5YCOZB.mjs} +55 -51
  22. package/dist/chunk-TRYHX5S4.mjs +360 -0
  23. package/dist/chunk-XBOVM6LO.mjs +41 -0
  24. package/dist/{chunk-ILU426CF.mjs → chunk-YACY2572.mjs} +482 -2
  25. package/dist/{config-MD27U4FM.mjs → config-BZHQK532.mjs} +3 -3
  26. package/dist/{dev-L4Y2GU2E.mjs → dev-7KGRV56X.mjs} +10 -8
  27. package/dist/{dev-YPBQBEOE.mjs → dev-GQT37XJU.mjs} +10 -8
  28. package/dist/{discovery-GWTBF5RZ.mjs → discovery-HNH3BLDL.mjs} +8 -6
  29. package/dist/{generators-VCYISHWO.mjs → generators-3FVW4AEJ.mjs} +18 -15
  30. package/dist/{generators-H4NTV4DB.mjs → generators-JWVNGUUE.mjs} +14 -11
  31. package/dist/index.d.ts +1 -1
  32. package/dist/index.mjs +407 -102
  33. package/dist/{media-migrations-BNVAPYEM.mjs → media-migrations-EG34NYAG.mjs} +13 -11
  34. package/dist/{media-migrations-NNB3DAQR.mjs → media-migrations-LGI7R7AR.mjs} +11 -9
  35. package/dist/plugins-ZGLB6JO6.mjs +24 -0
  36. package/dist/{queue-5BXSDFCO.mjs → queue-BEZDCZCY.mjs} +54 -16
  37. package/dist/{queue-D4LSWNS2.mjs → queue-R54DUUYA.mjs} +54 -16
  38. package/dist/{queue-migrations-EF4AMMSY.mjs → queue-migrations-AM3AKT76.mjs} +16 -11
  39. package/dist/{queue-migrations-LXEWXJYT.mjs → queue-migrations-U477YSFD.mjs} +18 -13
  40. package/dist/{runtime-RPMZMTD4.mjs → runtime-4TJYZLQV.mjs} +10 -8
  41. package/dist/{runtime-UKBJQFXM.mjs → runtime-MSRQD5W5.mjs} +10 -8
  42. package/dist/{runtime-GSXF4NB3.mjs → runtime-VR5BDPYQ.mjs} +1 -1
  43. package/dist/runtime-worker.mjs +7 -1
  44. package/dist/{scaffold-NJ5VH73M.mjs → scaffold-ASEX5LEX.mjs} +8 -4
  45. package/dist/{scaffold-VV3KTYGO.mjs → scaffold-ZAD3XUSD.mjs} +8 -4
  46. package/dist/{security-K5PZS3E3.mjs → security-4QLV7QCH.mjs} +8 -6
  47. package/dist/{security-JR4P7L2C.mjs → security-KYTLP4DF.mjs} +8 -6
  48. package/package.json +35 -8
  49. package/dist/cache-HUGRWOHQ.mjs +0 -66
  50. package/dist/cache-OSJ4PD52.mjs +0 -66
  51. package/dist/chunk-D7O4SU6N.mjs +0 -2
  52. package/dist/chunk-FGQ2I2YH.mjs +0 -22
@@ -1,21 +1,21 @@
1
1
  import {
2
2
  fileExists
3
- } from "./chunk-LBJAJLKU.mjs";
4
- import {
5
- prepareProjectDiscovery
6
- } from "./chunk-VP2E62DF.mjs";
3
+ } from "./chunk-M3IPUCTM.mjs";
7
4
  import {
8
5
  loadProjectConfig,
9
6
  resolveGeneratedSchemaPath
10
- } from "./chunk-YEFJBN56.mjs";
7
+ } from "./chunk-JVLZ3SOW.mjs";
8
+ import {
9
+ prepareProjectDiscovery
10
+ } from "./chunk-QSVMXMTQ.mjs";
11
11
  import {
12
12
  loadGeneratedProjectRegistry
13
- } from "./chunk-J76GH2DR.mjs";
13
+ } from "./chunk-R4ZYMEDU.mjs";
14
14
  import {
15
15
  CLI_RUNTIME_ROOT,
16
16
  GENERATED_SCHEMA_RUNTIME_PATH,
17
17
  bundleProjectModule
18
- } from "./chunk-ILU426CF.mjs";
18
+ } from "./chunk-YACY2572.mjs";
19
19
 
20
20
  // src/runtime.ts
21
21
  import { spawn } from "child_process";
@@ -0,0 +1,2 @@
1
+ // src/project.ts
2
+ import { normalizeHoloProjectConfig } from "@holo-js/kernel";
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  loadGeneratedProjectRegistry
3
- } from "./chunk-J76GH2DR.mjs";
3
+ } from "./chunk-R4ZYMEDU.mjs";
4
4
  import {
5
5
  APP_CONFIG_FILE_NAMES,
6
6
  DATABASE_CONFIG_FILE_NAMES,
@@ -8,7 +8,7 @@ import {
8
8
  isModulePackage,
9
9
  pathExists,
10
10
  resolveFirstExistingPath
11
- } from "./chunk-ILU426CF.mjs";
11
+ } from "./chunk-YACY2572.mjs";
12
12
 
13
13
  // src/project/config.ts
14
14
  import { createHash } from "crypto";
@@ -18,14 +18,16 @@ import { pathToFileURL } from "url";
18
18
  import {
19
19
  loadConfigDirectory,
20
20
  holoAppDefaults,
21
- holoDatabaseDefaults,
22
21
  loadEnvironment,
23
- normalizeAppConfig,
24
- normalizeDatabaseConfig
22
+ normalizeAppConfig
25
23
  } from "@holo-js/config";
26
24
  import {
27
25
  DEFAULT_HOLO_PROJECT_PATHS,
28
- normalizeHoloProjectConfig,
26
+ normalizeHoloProjectConfig
27
+ } from "@holo-js/kernel";
28
+ import {
29
+ holoDatabaseDefaults,
30
+ normalizeDatabaseConfig,
29
31
  renderGeneratedSchemaPlaceholder
30
32
  } from "@holo-js/db";
31
33
  function isObject(value) {
@@ -91,7 +93,7 @@ async function importProjectConfigFile(projectRoot, filePath, environmentValues)
91
93
  const previousEnvEntries = /* @__PURE__ */ new Map();
92
94
  const importUrl = await resolveProjectConfigImportUrl(filePath, environmentValues);
93
95
  const configExtension = extname(filePath);
94
- const bundled = configExtension === ".ts" || configExtension === ".mts" ? await bundleProjectModule(projectRoot, filePath) : void 0;
96
+ const bundled = configExtension === ".ts" || configExtension === ".mts" ? await bundleProjectModule(projectRoot, filePath, { bundleDependencies: true }) : void 0;
95
97
  const resolvedImportUrl = bundled ? `${pathToFileURL(bundled.path).href}${new URL(importUrl).search}` : importUrl;
96
98
  try {
97
99
  for (const [key, value] of Object.entries(environmentValues)) {
@@ -181,6 +183,7 @@ async function serializeProjectConfig(projectRoot, config, manifestPath) {
181
183
  url: appConfig.url,
182
184
  debug: appConfig.debug,
183
185
  env: appConfig.env,
186
+ plugins: appConfig.plugins,
184
187
  paths: config.paths
185
188
  }, null, 2);
186
189
  const extension = extname(manifestPath);
@@ -214,7 +217,7 @@ async function serializeDatabaseConfig(projectRoot, _targetPath) {
214
217
  connections: databaseConfig.connections
215
218
  }, null, 2);
216
219
  return [
217
- "import { defineDatabaseConfig } from '@holo-js/config'",
220
+ "import { defineDatabaseConfig } from '@holo-js/db'",
218
221
  "",
219
222
  "export default defineDatabaseConfig(",
220
223
  contents,
@@ -1,23 +1,28 @@
1
1
  import {
2
2
  hasProjectDependency
3
- } from "./chunk-FGQ2I2YH.mjs";
3
+ } from "./chunk-LHK5YUR4.mjs";
4
4
  import {
5
5
  prepareProjectDiscovery
6
- } from "./chunk-VP2E62DF.mjs";
6
+ } from "./chunk-QSVMXMTQ.mjs";
7
7
  import {
8
8
  syncManagedDriverDependencies
9
- } from "./chunk-C624G3R2.mjs";
9
+ } from "./chunk-OI54DOHK.mjs";
10
10
  import {
11
11
  ensureGeneratedSchemaPlaceholder,
12
12
  ensureProjectConfig
13
- } from "./chunk-YEFJBN56.mjs";
13
+ } from "./chunk-JVLZ3SOW.mjs";
14
14
  import {
15
- renderFrameworkRunner
16
- } from "./chunk-J76GH2DR.mjs";
15
+ renderFrameworkRunnerForDescriptor
16
+ } from "./chunk-R4ZYMEDU.mjs";
17
17
  import {
18
+ loadProjectPluginFrameworkDescriptors
19
+ } from "./chunk-3RFRE7XG.mjs";
20
+ import {
21
+ getFrameworkDescriptorByIdFrom,
22
+ getFrameworkDescriptorsWith,
18
23
  readTextFile,
19
24
  writeTextFile
20
- } from "./chunk-ILU426CF.mjs";
25
+ } from "./chunk-YACY2572.mjs";
21
26
 
22
27
  // src/dev.ts
23
28
  import { spawnSync, spawn } from "child_process";
@@ -137,37 +142,17 @@ async function runProjectDependencyInstall(io, projectRoot, spawn2 = spawnSync)
137
142
  throw new Error(result.stderr?.trim() || result.stdout?.trim() || "Project dependency installation failed.");
138
143
  }
139
144
  }
140
- var FRAMEWORK_SYNC_DEFINITIONS = [
141
- {
142
- framework: "nuxt",
143
- commands: {
144
- bun: ["bun", "x", "nuxt", "prepare"],
145
- npm: ["npm", "exec", "--", "nuxt", "prepare"],
146
- pnpm: ["pnpm", "exec", "nuxt", "prepare"],
147
- yarn: ["yarn", "run", "nuxt", "prepare"]
148
- },
149
- errorLabel: "nuxt prepare"
150
- },
151
- {
152
- framework: "sveltekit",
153
- commands: {
154
- bun: ["bun", "x", "svelte-kit", "sync"],
155
- npm: ["npm", "exec", "--", "svelte-kit", "sync"],
156
- pnpm: ["pnpm", "exec", "svelte-kit", "sync"],
157
- yarn: ["yarn", "run", "svelte-kit", "sync"]
158
- },
159
- errorLabel: "svelte-kit sync"
160
- }
161
- ];
162
145
  async function runProjectPrepare(projectRoot, io, options = {}) {
163
146
  const project = await ensureProjectConfig(projectRoot);
164
147
  await ensureGeneratedSchemaPlaceholder(projectRoot, project.config);
165
148
  await prepareProjectDiscovery(projectRoot, project.config);
166
149
  await refreshFrameworkRunner(projectRoot);
167
150
  const syncFramework = options.syncFramework ?? true;
151
+ const syncDefinitions = syncFramework ? await resolveProjectFrameworkSyncDefinitions(projectRoot) : [];
168
152
  if (syncFramework) {
169
- await runFrameworkSync(projectRoot, FRAMEWORK_SYNC_DEFINITIONS[0]);
170
- await runFrameworkSync(projectRoot, FRAMEWORK_SYNC_DEFINITIONS[1]);
153
+ for (const definition of syncDefinitions) {
154
+ await runFrameworkSync(projectRoot, definition);
155
+ }
171
156
  }
172
157
  const updatedDependencies = await syncManagedDriverDependencies(projectRoot);
173
158
  if (updatedDependencies && io) {
@@ -175,8 +160,9 @@ async function runProjectPrepare(projectRoot, io, options = {}) {
175
160
  await prepareProjectDiscovery(projectRoot, project.config);
176
161
  await refreshFrameworkRunner(projectRoot);
177
162
  if (syncFramework) {
178
- await runFrameworkSync(projectRoot, FRAMEWORK_SYNC_DEFINITIONS[0]);
179
- await runFrameworkSync(projectRoot, FRAMEWORK_SYNC_DEFINITIONS[1]);
163
+ for (const definition of syncDefinitions) {
164
+ await runFrameworkSync(projectRoot, definition);
165
+ }
180
166
  }
181
167
  }
182
168
  }
@@ -186,35 +172,53 @@ async function runProjectHotPrepare(projectRoot, io) {
186
172
  async function refreshFrameworkRunner(projectRoot) {
187
173
  const frameworkProjectPath = resolve(projectRoot, ".holo-js/framework/project.json");
188
174
  const frameworkRunnerPath = resolve(projectRoot, ".holo-js/framework/run.mjs");
189
- const framework = await resolveProjectFramework(projectRoot, frameworkProjectPath);
190
- if (!framework) {
175
+ const descriptor = await resolveProjectFramework(projectRoot, frameworkProjectPath);
176
+ if (!descriptor) {
191
177
  return;
192
178
  }
193
- await writeTextFile(frameworkProjectPath, `${JSON.stringify({ framework }, null, 2)}
179
+ await writeTextFile(frameworkProjectPath, `${JSON.stringify({ framework: descriptor.id }, null, 2)}
194
180
  `);
195
- await writeTextFile(frameworkRunnerPath, renderFrameworkRunner({ framework }));
181
+ await writeTextFile(frameworkRunnerPath, renderFrameworkRunnerForDescriptor(descriptor));
196
182
  }
197
183
  async function resolveProjectFramework(projectRoot, frameworkProjectPath) {
184
+ const pluginDescriptors = await loadProjectPluginFrameworkDescriptors(projectRoot);
198
185
  try {
199
186
  const content = await readFile(frameworkProjectPath, "utf8");
200
187
  const manifest = JSON.parse(content);
201
- if (manifest.framework !== "next" && manifest.framework !== "nuxt" && manifest.framework !== "sveltekit") {
202
- return;
203
- }
204
- return manifest.framework;
188
+ const descriptor = typeof manifest.framework === "string" ? getFrameworkDescriptorByIdFrom(manifest.framework, pluginDescriptors) : void 0;
189
+ return descriptor ?? resolveProjectFrameworkFromDependencies(projectRoot, pluginDescriptors);
205
190
  } catch {
191
+ return resolveProjectFrameworkFromDependencies(projectRoot, pluginDescriptors);
206
192
  }
207
- if (await hasProjectDependency(projectRoot, "next")) {
208
- return "next";
209
- }
210
- if (await hasProjectDependency(projectRoot, "nuxt")) {
211
- return "nuxt";
212
- }
213
- if (await hasProjectDependency(projectRoot, "@sveltejs/kit")) {
214
- return "sveltekit";
193
+ }
194
+ async function resolveProjectFrameworkFromDependencies(projectRoot, pluginDescriptors = []) {
195
+ for (const descriptor of getFrameworkDescriptorsWith(pluginDescriptors)) {
196
+ const matches = await Promise.all(
197
+ descriptor.detectPackages.map((packageName) => hasProjectDependency(projectRoot, packageName))
198
+ );
199
+ if (matches.some(Boolean)) {
200
+ return descriptor;
201
+ }
215
202
  }
216
203
  return void 0;
217
204
  }
205
+ async function resolveProjectFrameworkSyncDefinitions(projectRoot) {
206
+ const pluginDescriptors = await loadProjectPluginFrameworkDescriptors(projectRoot);
207
+ const seen = /* @__PURE__ */ new Set();
208
+ const definitions = [];
209
+ for (const descriptor of getFrameworkDescriptorsWith(pluginDescriptors)) {
210
+ if (!descriptor.sync || seen.has(descriptor.id)) {
211
+ continue;
212
+ }
213
+ seen.add(descriptor.id);
214
+ definitions.push({
215
+ framework: descriptor.id,
216
+ commands: descriptor.sync.commands,
217
+ errorLabel: descriptor.sync.errorLabel
218
+ });
219
+ }
220
+ return Object.freeze(definitions);
221
+ }
218
222
  async function runFrameworkSync(projectRoot, definition) {
219
223
  const frameworkProjectPath = resolve(projectRoot, ".holo-js/framework/project.json");
220
224
  try {
@@ -0,0 +1,428 @@
1
+ import {
2
+ fileExists
3
+ } from "./chunk-M3IPUCTM.mjs";
4
+ import {
5
+ prepareProjectDiscovery
6
+ } from "./chunk-QSVMXMTQ.mjs";
7
+ import {
8
+ loadProjectConfig,
9
+ resolveGeneratedSchemaPath
10
+ } from "./chunk-JVLZ3SOW.mjs";
11
+ import {
12
+ loadGeneratedProjectRegistry
13
+ } from "./chunk-R4ZYMEDU.mjs";
14
+ import {
15
+ CLI_RUNTIME_ROOT,
16
+ GENERATED_SCHEMA_RUNTIME_PATH,
17
+ bundleProjectModule
18
+ } from "./chunk-YACY2572.mjs";
19
+
20
+ // src/runtime.ts
21
+ import { spawn } from "child_process";
22
+ import { mkdir, readFile, rm, symlink, writeFile } from "fs/promises";
23
+ import { dirname, join, resolve } from "path";
24
+ import { setTimeout } from "timers/promises";
25
+ import { fileURLToPath, pathToFileURL } from "url";
26
+ import { writeConfigCache } from "@holo-js/config";
27
+ var runtimeImportMeta = import.meta;
28
+ var RUNTIME_DEPENDENCY_LOCK_RETRY_MS = 10;
29
+ function resolveConfigModuleUrl(runtimeResolve = runtimeImportMeta.resolve?.bind(runtimeImportMeta)) {
30
+ if (typeof runtimeResolve === "function") {
31
+ const resolved = runtimeResolve("@holo-js/config");
32
+ if (resolved.startsWith("file://")) {
33
+ const resolvedPath = fileURLToPath(resolved);
34
+ const normalized = resolvedPath.replace(/\\/g, "/");
35
+ if (normalized.endsWith("/src/index.ts") || normalized.endsWith("/src/index.mts") || normalized.endsWith("/src/index.js") || normalized.endsWith("/src/index.mjs")) {
36
+ return pathToFileURL(resolve(dirname(dirname(resolvedPath)), "dist/index.mjs")).href;
37
+ }
38
+ }
39
+ return resolved;
40
+ }
41
+ return pathToFileURL(resolve(dirname(fileURLToPath(import.meta.url)), "../node_modules/@holo-js/config/dist/index.mjs")).href;
42
+ }
43
+ async function initializeProjectRuntime(projectRoot, options = {}) {
44
+ const { initializeHolo } = await import("@holo-js/core");
45
+ return initializeHolo(projectRoot, options);
46
+ }
47
+ function parseBooleanEnv(value) {
48
+ if (value === "true") return true;
49
+ if (value === "false") return false;
50
+ return void 0;
51
+ }
52
+ async function cacheProjectConfig(projectRoot, cacheWriter = writeConfigCache) {
53
+ try {
54
+ return await cacheWriter(projectRoot, { processEnv: process.env });
55
+ } catch (error) {
56
+ throw new Error(error instanceof Error && error.message ? error.message : "Failed to cache config.");
57
+ }
58
+ }
59
+ function createEnvRuntimeConfig() {
60
+ return {
61
+ db: {
62
+ defaultConnection: "default",
63
+ connections: {
64
+ default: {
65
+ driver: process.env.DB_DRIVER,
66
+ url: process.env.DB_URL,
67
+ host: process.env.DB_HOST,
68
+ port: process.env.DB_PORT,
69
+ username: process.env.DB_USERNAME,
70
+ password: process.env.DB_PASSWORD,
71
+ database: process.env.DB_DATABASE,
72
+ schema: process.env.DB_SCHEMA,
73
+ ssl: parseBooleanEnv(process.env.DB_SSL),
74
+ logging: parseBooleanEnv(process.env.DB_LOGGING)
75
+ }
76
+ }
77
+ }
78
+ };
79
+ }
80
+ function normalizeRuntimeConnectionInput(connection) {
81
+ if (typeof connection === "string") {
82
+ return { url: connection };
83
+ }
84
+ return connection ? { ...connection } : {};
85
+ }
86
+ function isDefined(value) {
87
+ return value !== void 0;
88
+ }
89
+ function filterDefinedRuntimeConnectionInput(connection) {
90
+ return Object.fromEntries(
91
+ Object.entries(connection).filter(([, value]) => isDefined(value))
92
+ );
93
+ }
94
+ function mergeRuntimeDatabaseConfig(config, envRuntimeConfig) {
95
+ const envDefault = envRuntimeConfig.db.connections.default;
96
+ const hasEnvOverrides = Object.values(envDefault).some(isDefined);
97
+ if (!config) {
98
+ return envRuntimeConfig.db;
99
+ }
100
+ if (!hasEnvOverrides) {
101
+ return config;
102
+ }
103
+ const defaultConnection = config.defaultConnection ?? "default";
104
+ const connections = { ...config.connections ?? {} };
105
+ connections[defaultConnection] = {
106
+ ...normalizeRuntimeConnectionInput(connections[defaultConnection]),
107
+ ...filterDefinedRuntimeConnectionInput(envDefault)
108
+ };
109
+ return {
110
+ ...config,
111
+ defaultConnection,
112
+ connections
113
+ };
114
+ }
115
+ var RUNTIME_MIGRATION_NAME_PATTERN = /^\d{4}_\d{2}_\d{2}_\d{6}_[a-z0-9_]+$/;
116
+ function inferRuntimeMigrationName(entry) {
117
+ const fileName = entry.split("/").pop()?.replace(/\.[^.]+$/, "");
118
+ if (!fileName || !RUNTIME_MIGRATION_NAME_PATTERN.test(fileName)) {
119
+ throw new Error(`Registered migration "${entry}" must use a timestamped file name matching YYYY_MM_DD_HHMMSS_description.`);
120
+ }
121
+ return fileName;
122
+ }
123
+ function normalizeRuntimeMigration(entry, migration) {
124
+ return {
125
+ ...migration,
126
+ name: typeof migration.name === "string" ? migration.name : inferRuntimeMigrationName(entry)
127
+ };
128
+ }
129
+ function compileFreshDropIdentifierPath(quoteIdentifier, identifier) {
130
+ if (!identifier.includes(".")) {
131
+ return quoteIdentifier(identifier);
132
+ }
133
+ return identifier.split(".").map((part) => quoteIdentifier(part)).join(".");
134
+ }
135
+ async function dropAllTablesForFresh(connection, schema) {
136
+ const tables = await schema.getTables();
137
+ if (connection.getDialect().name === "postgres") {
138
+ const schemaName = connection.getSchemaName();
139
+ const quoteIdentifier = connection.getDialect().quoteIdentifier;
140
+ for (const tableName of tables) {
141
+ const qualifiedTableName = schemaName ? `${schemaName}.${tableName}` : tableName;
142
+ await connection.executeCompiled({
143
+ sql: `DROP TABLE IF EXISTS ${compileFreshDropIdentifierPath(quoteIdentifier, qualifiedTableName)} CASCADE`,
144
+ source: `schema:dropTableFresh:${qualifiedTableName}`
145
+ });
146
+ }
147
+ return;
148
+ }
149
+ await schema.withoutForeignKeyConstraints(async () => {
150
+ for (const tableName of tables) {
151
+ await schema.dropTable(tableName);
152
+ }
153
+ });
154
+ }
155
+ async function getRuntimeEnvironment(projectRoot) {
156
+ let project = await loadProjectConfig(projectRoot, { required: true });
157
+ if (!await loadGeneratedProjectRegistry(projectRoot)) {
158
+ await prepareProjectDiscovery(projectRoot, project.config);
159
+ project = await loadProjectConfig(projectRoot, { required: true });
160
+ }
161
+ const generatedSchemaPath = resolveGeneratedSchemaPath(projectRoot, project.config);
162
+ const hasGeneratedSchema = await fileExists(generatedSchemaPath);
163
+ const bundleInputs = [
164
+ ...project.config.models.map((entry) => resolve(projectRoot, entry)),
165
+ ...project.config.migrations.map((entry) => resolve(projectRoot, entry)),
166
+ ...project.config.seeders.map((entry) => resolve(projectRoot, entry)),
167
+ ...hasGeneratedSchema ? [generatedSchemaPath] : []
168
+ ];
169
+ const bundled = [];
170
+ try {
171
+ for (const entryPath of bundleInputs) {
172
+ bundled.push(await bundleProjectModule(projectRoot, entryPath, { external: ["@holo-js/db"] }));
173
+ }
174
+ } catch (error) {
175
+ await Promise.all(bundled.map((entry) => entry.cleanup()));
176
+ throw error;
177
+ }
178
+ const bundledModels = bundled.slice(0, project.config.models.length).map((entry) => entry.path);
179
+ const bundledMigrations = bundled.slice(project.config.models.length, project.config.models.length + project.config.migrations.length).map((entry) => entry.path);
180
+ const bundledSeeders = bundled.slice(project.config.models.length + project.config.migrations.length).slice(0, project.config.seeders.length).map((entry) => entry.path);
181
+ const bundledGeneratedSchema = hasGeneratedSchema ? bundled[project.config.models.length + project.config.migrations.length + project.config.seeders.length]?.path : void 0;
182
+ return {
183
+ project,
184
+ bundledModels,
185
+ bundledMigrations,
186
+ bundledSeeders,
187
+ ...bundledGeneratedSchema ? { bundledGeneratedSchema } : {},
188
+ async cleanup() {
189
+ await Promise.all(bundled.map((entry) => entry.cleanup()));
190
+ }
191
+ };
192
+ }
193
+ async function resolvePackageRootFromSpecifier(specifier) {
194
+ let current = dirname(fileURLToPath(import.meta.resolve(specifier)));
195
+ while (true) {
196
+ if (await fileExists(join(current, "package.json"))) {
197
+ return current;
198
+ }
199
+ const parent = dirname(current);
200
+ if (parent === current) {
201
+ throw new Error(`Could not resolve package root for "${specifier}".`);
202
+ }
203
+ current = parent;
204
+ }
205
+ }
206
+ function isFileExistsError(error) {
207
+ return error instanceof Error && "code" in error && error.code === "EEXIST";
208
+ }
209
+ async function withRuntimeDependencyLock(projectRoot, callback) {
210
+ const runtimeRoot = join(projectRoot, CLI_RUNTIME_ROOT);
211
+ const lockDir = join(runtimeRoot, "node_modules.lock");
212
+ await mkdir(runtimeRoot, { recursive: true });
213
+ while (true) {
214
+ try {
215
+ await mkdir(lockDir);
216
+ break;
217
+ } catch (error) {
218
+ if (!isFileExistsError(error)) {
219
+ throw error;
220
+ }
221
+ await setTimeout(RUNTIME_DEPENDENCY_LOCK_RETRY_MS);
222
+ }
223
+ }
224
+ try {
225
+ return await callback();
226
+ } finally {
227
+ await rm(lockDir, { recursive: true, force: true });
228
+ }
229
+ }
230
+ async function readRuntimeDependencyReferenceCount(refPath) {
231
+ const raw = await readFile(refPath, "utf8").catch(() => void 0);
232
+ const count = raw === void 0 ? 0 : Number.parseInt(raw, 10);
233
+ return Number.isFinite(count) && count > 0 ? count : 0;
234
+ }
235
+ async function ensureRuntimeDependencyLink(projectRoot) {
236
+ return await withRuntimeDependencyLock(projectRoot, async () => {
237
+ const runtimeRoot = join(projectRoot, CLI_RUNTIME_ROOT);
238
+ const packageRoot = await resolvePackageRootFromSpecifier("@holo-js/db");
239
+ const nodeModulesDir = join(runtimeRoot, "node_modules");
240
+ const namespaceDir = join(nodeModulesDir, "@holo-js");
241
+ const targetPath = join(namespaceDir, "db");
242
+ const refPath = join(nodeModulesDir, ".holo-js-runtime-refs");
243
+ const references = await readRuntimeDependencyReferenceCount(refPath);
244
+ await mkdir(namespaceDir, { recursive: true });
245
+ if (references === 0) {
246
+ await rm(targetPath, { recursive: true, force: true });
247
+ await symlink(packageRoot, targetPath, "junction");
248
+ }
249
+ await writeFile(refPath, String(references + 1), "utf8");
250
+ return runtimeRoot;
251
+ });
252
+ }
253
+ async function cleanupRuntimeDependencyLink(projectRoot) {
254
+ await withRuntimeDependencyLock(projectRoot, async () => {
255
+ const nodeModulesDir = join(projectRoot, CLI_RUNTIME_ROOT, "node_modules");
256
+ const refPath = join(nodeModulesDir, ".holo-js-runtime-refs");
257
+ const references = await readRuntimeDependencyReferenceCount(refPath);
258
+ const nextReferences = references - 1;
259
+ if (nextReferences <= 0) {
260
+ await rm(nodeModulesDir, { recursive: true, force: true });
261
+ return;
262
+ }
263
+ await writeFile(refPath, String(nextReferences), "utf8");
264
+ });
265
+ }
266
+ function resolveRuntimeWorkerPath() {
267
+ const runtimePath = fileURLToPath(import.meta.url);
268
+ return runtimePath.endsWith("/src/runtime.ts") ? resolve(dirname(runtimePath), "runtime-worker.ts") : resolve(dirname(runtimePath), "runtime-worker.mjs");
269
+ }
270
+ function supportsNodeTypeStripping(version = process.versions.node) {
271
+ const [major = "0", minor = "0"] = version.split(".");
272
+ const majorVersion = Number.parseInt(major, 10);
273
+ const minorVersion = Number.parseInt(minor, 10);
274
+ return majorVersion > 22 || majorVersion === 22 && minorVersion >= 6;
275
+ }
276
+ function resolveCompiledRuntimeWorkerPath(workerPath) {
277
+ return resolve(dirname(workerPath), "../dist/runtime-worker.mjs");
278
+ }
279
+ function createRuntimeInvocation(workerPath = resolveRuntimeWorkerPath()) {
280
+ if (workerPath.endsWith(".ts")) {
281
+ return {
282
+ command: "node",
283
+ args: supportsNodeTypeStripping() ? ["--experimental-strip-types", workerPath] : [resolveCompiledRuntimeWorkerPath(workerPath)]
284
+ };
285
+ }
286
+ return {
287
+ command: "node",
288
+ args: [workerPath]
289
+ };
290
+ }
291
+ function runRuntimeInvocation(command, args, options) {
292
+ return new Promise((resolveInvocation) => {
293
+ const child = spawn(command, args, {
294
+ cwd: options.cwd,
295
+ env: options.env,
296
+ stdio: ["ignore", "pipe", "pipe"]
297
+ });
298
+ let stdout = "";
299
+ let stderr = "";
300
+ let error = null;
301
+ child.stdout.setEncoding("utf8");
302
+ child.stdout.on("data", (chunk) => {
303
+ stdout += chunk;
304
+ });
305
+ child.stderr.setEncoding("utf8");
306
+ child.stderr.on("data", (chunk) => {
307
+ stderr += chunk;
308
+ });
309
+ child.on("error", (spawnError) => {
310
+ error = spawnError;
311
+ });
312
+ child.on("close", (status) => {
313
+ resolveInvocation({
314
+ status,
315
+ error,
316
+ stdout,
317
+ stderr
318
+ });
319
+ });
320
+ });
321
+ }
322
+ function getRuntimeFailureMessage(kind, result) {
323
+ const stderr = result.stderr?.trim();
324
+ if (stderr) {
325
+ return formatRuntimeFailureText(stderr);
326
+ }
327
+ const stdout = result.stdout?.trim();
328
+ if (stdout) {
329
+ return formatRuntimeFailureText(stdout);
330
+ }
331
+ const errorCode = result.error && "code" in result.error ? result.error.code : void 0;
332
+ if (typeof errorCode === "string" && errorCode.length > 0) {
333
+ return `Failed to launch runtime command "${kind}": ${errorCode}.`;
334
+ }
335
+ return `Runtime command "${kind}" failed.`;
336
+ }
337
+ function stripRuntimeErrorPrefix(line) {
338
+ return line.replace(/^(?:[A-Za-z][\w.]*Error|Error):\s+/, "");
339
+ }
340
+ function isRuntimeErrorSourceLine(line) {
341
+ return line.startsWith("throw ") || line.startsWith("at ") || line === "^" || /^\^+$/.test(line);
342
+ }
343
+ function formatRuntimeFailureText(text) {
344
+ const lines = text.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
345
+ const friendlyLine = lines.find((line) => line.includes("Unable to ") && !isRuntimeErrorSourceLine(line));
346
+ if (friendlyLine) {
347
+ return stripRuntimeErrorPrefix(friendlyLine);
348
+ }
349
+ const errorLine = lines.find((line) => /^(?:[A-Za-z][\w.]*Error|Error):\s+/.test(line));
350
+ if (errorLine) {
351
+ return stripRuntimeErrorPrefix(errorLine);
352
+ }
353
+ return lines[0] ?? text.trim();
354
+ }
355
+ async function withRuntimeEnvironment(projectRoot, kind, options, callback) {
356
+ if (kind === "seed") {
357
+ const project = await loadProjectConfig(projectRoot, { required: true });
358
+ await prepareProjectDiscovery(projectRoot, project.config);
359
+ }
360
+ const environment = await getRuntimeEnvironment(projectRoot);
361
+ let dependencyLinkEnsured = false;
362
+ try {
363
+ const envRuntimeConfig = createEnvRuntimeConfig();
364
+ const runtimeDatabaseConfig = mergeRuntimeDatabaseConfig(
365
+ environment.project.config.database,
366
+ envRuntimeConfig
367
+ );
368
+ const runtimeRoot = await ensureRuntimeDependencyLink(projectRoot);
369
+ dependencyLinkEnsured = true;
370
+ const runtimePayload = JSON.stringify({
371
+ kind,
372
+ projectRoot,
373
+ runtimeConfig: {
374
+ db: runtimeDatabaseConfig
375
+ },
376
+ models: environment.bundledModels.map((entry) => pathToFileURL(entry).href),
377
+ migrations: environment.bundledMigrations.map((entry) => pathToFileURL(entry).href),
378
+ seeders: environment.bundledSeeders.map((entry) => pathToFileURL(entry).href),
379
+ generatedSchema: environment.bundledGeneratedSchema ? pathToFileURL(environment.bundledGeneratedSchema).href : void 0,
380
+ generatedSchemaOutputPath: resolveGeneratedSchemaPath(projectRoot, environment.project.config),
381
+ generatedSchemaRuntimeOutputPath: resolve(projectRoot, GENERATED_SCHEMA_RUNTIME_PATH),
382
+ options
383
+ });
384
+ const runtime = createRuntimeInvocation();
385
+ const result = await runRuntimeInvocation(runtime.command, runtime.args, {
386
+ cwd: runtimeRoot,
387
+ env: {
388
+ ...process.env,
389
+ HOLO_RUNTIME_PAYLOAD: runtimePayload
390
+ }
391
+ });
392
+ if (result.status !== 0) {
393
+ throw new Error(getRuntimeFailureMessage(kind, result));
394
+ }
395
+ return await callback((result.stdout ?? "").trim());
396
+ } finally {
397
+ if (dependencyLinkEnsured) {
398
+ await cleanupRuntimeDependencyLink(projectRoot);
399
+ }
400
+ await environment.cleanup();
401
+ }
402
+ }
403
+
404
+ export {
405
+ resolveConfigModuleUrl,
406
+ initializeProjectRuntime,
407
+ parseBooleanEnv,
408
+ cacheProjectConfig,
409
+ createEnvRuntimeConfig,
410
+ normalizeRuntimeConnectionInput,
411
+ isDefined,
412
+ filterDefinedRuntimeConnectionInput,
413
+ mergeRuntimeDatabaseConfig,
414
+ RUNTIME_MIGRATION_NAME_PATTERN,
415
+ inferRuntimeMigrationName,
416
+ normalizeRuntimeMigration,
417
+ compileFreshDropIdentifierPath,
418
+ dropAllTablesForFresh,
419
+ getRuntimeEnvironment,
420
+ resolvePackageRootFromSpecifier,
421
+ ensureRuntimeDependencyLink,
422
+ cleanupRuntimeDependencyLink,
423
+ resolveRuntimeWorkerPath,
424
+ createRuntimeInvocation,
425
+ runRuntimeInvocation,
426
+ getRuntimeFailureMessage,
427
+ withRuntimeEnvironment
428
+ };