@qpqjs/cli 0.3.0 → 0.4.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.
- package/lib/commonjs/cli/commandMenu.js +5 -4
- package/lib/commonjs/cli/commandMenu.js.map +1 -1
- package/lib/commonjs/cli/runCli.js +15 -7
- package/lib/commonjs/cli/runCli.js.map +1 -1
- package/lib/commonjs/commands/checkCircular.js +15 -7
- package/lib/commonjs/commands/checkCircular.js.map +1 -1
- package/lib/commonjs/commands/clearResources.js +8 -14
- package/lib/commonjs/commands/clearResources.js.map +1 -1
- package/lib/commonjs/commands/go.js +3 -7
- package/lib/commonjs/commands/go.js.map +1 -1
- package/lib/commonjs/commands/goDev.js +4 -2
- package/lib/commonjs/commands/goDev.js.map +1 -1
- package/lib/commonjs/commands/goDevApi.js +23 -20
- package/lib/commonjs/commands/goDevApi.js.map +1 -1
- package/lib/commonjs/commands/goDevWeb.js +13 -8
- package/lib/commonjs/commands/goDevWeb.js.map +1 -1
- package/lib/commonjs/commands/goDocker.js +10 -13
- package/lib/commonjs/commands/goDocker.js.map +1 -1
- package/lib/commonjs/commands/hooks.js +4 -2
- package/lib/commonjs/commands/hooks.js.map +1 -1
- package/lib/commonjs/commands/migrate.js +11 -9
- package/lib/commonjs/commands/migrate.js.map +1 -1
- package/lib/commonjs/commands/prep.js +4 -2
- package/lib/commonjs/commands/prep.js.map +1 -1
- package/lib/commonjs/commands/publish.js +4 -7
- package/lib/commonjs/commands/publish.js.map +1 -1
- package/lib/commonjs/commands/scriptBuild.js +7 -5
- package/lib/commonjs/commands/scriptBuild.js.map +1 -1
- package/lib/commonjs/commands/scriptBuilderLayer.js +6 -4
- package/lib/commonjs/commands/scriptBuilderLayer.js.map +1 -1
- package/lib/commonjs/commands/scriptNew.js +7 -5
- package/lib/commonjs/commands/scriptNew.js.map +1 -1
- package/lib/commonjs/commands/setup.js +14 -22
- package/lib/commonjs/commands/setup.js.map +1 -1
- package/lib/commonjs/commands/synth.js +16 -20
- package/lib/commonjs/commands/synth.js.map +1 -1
- package/lib/commonjs/commands/teardown.js +8 -14
- package/lib/commonjs/commands/teardown.js.map +1 -1
- package/lib/commonjs/lib/CliError.d.ts +4 -0
- package/lib/commonjs/lib/CliError.js +14 -0
- package/lib/commonjs/lib/CliError.js.map +1 -0
- package/lib/commonjs/lib/circularImports.d.ts +0 -1
- package/lib/commonjs/lib/circularImports.js +5 -6
- package/lib/commonjs/lib/circularImports.js.map +1 -1
- package/lib/commonjs/lib/clearResourcesPlan.d.ts +0 -1
- package/lib/commonjs/lib/clearResourcesPlan.js +12 -13
- package/lib/commonjs/lib/clearResourcesPlan.js.map +1 -1
- package/lib/commonjs/lib/deployPrompts.d.ts +2 -1
- package/lib/commonjs/lib/deployPrompts.js +16 -16
- package/lib/commonjs/lib/deployPrompts.js.map +1 -1
- package/lib/commonjs/lib/devServerEntry.js +5 -4
- package/lib/commonjs/lib/devServerEntry.js.map +1 -1
- package/lib/commonjs/lib/devServerPorts.js +2 -4
- package/lib/commonjs/lib/devServerPorts.js.map +1 -1
- package/lib/commonjs/lib/discovery.d.ts +0 -2
- package/lib/commonjs/lib/discovery.js +11 -44
- package/lib/commonjs/lib/discovery.js.map +1 -1
- package/lib/commonjs/lib/hooks.js +5 -3
- package/lib/commonjs/lib/hooks.js.map +1 -1
- package/lib/commonjs/lib/killChildWithEscalation.js +3 -1
- package/lib/commonjs/lib/killChildWithEscalation.js.map +1 -1
- package/lib/commonjs/lib/killStaleListeners.js +24 -37
- package/lib/commonjs/lib/killStaleListeners.js.map +1 -1
- package/lib/commonjs/lib/out.d.ts +11 -0
- package/lib/commonjs/lib/out.js +30 -0
- package/lib/commonjs/lib/out.js.map +1 -0
- package/lib/commonjs/lib/prompts.d.ts +1 -0
- package/lib/commonjs/lib/prompts.js +15 -2
- package/lib/commonjs/lib/prompts.js.map +1 -1
- package/lib/commonjs/lib/qpqConfigs.js +4 -4
- package/lib/commonjs/lib/qpqConfigs.js.map +1 -1
- package/lib/commonjs/lib/requireDriverCapability.d.ts +7 -0
- package/lib/commonjs/lib/requireDriverCapability.js +17 -0
- package/lib/commonjs/lib/requireDriverCapability.js.map +1 -0
- package/lib/commonjs/lib/resolveAppSelection.d.ts +1 -0
- package/lib/commonjs/lib/resolveAppSelection.js +19 -12
- package/lib/commonjs/lib/resolveAppSelection.js.map +1 -1
- package/lib/commonjs/lib/resolveCommandContext.d.ts +12 -0
- package/lib/commonjs/lib/resolveCommandContext.js +26 -0
- package/lib/commonjs/lib/resolveCommandContext.js.map +1 -0
- package/lib/commonjs/lib/resolveDeployment.d.ts +0 -1
- package/lib/commonjs/lib/resolveDeployment.js +15 -10
- package/lib/commonjs/lib/resolveDeployment.js.map +1 -1
- package/lib/commonjs/lib/runCommand.d.ts +20 -0
- package/lib/commonjs/lib/runCommand.js +64 -34
- package/lib/commonjs/lib/runCommand.js.map +1 -1
- package/lib/commonjs/lib/runTasks.js +8 -4
- package/lib/commonjs/lib/runTasks.js.map +1 -1
- package/lib/commonjs/lib/timing.js +5 -3
- package/lib/commonjs/lib/timing.js.map +1 -1
- package/lib/commonjs/lib/typeWatcher.d.ts +2 -1
- package/lib/commonjs/lib/typeWatcher.js +6 -13
- package/lib/commonjs/lib/typeWatcher.js.map +1 -1
- package/lib/commonjs/lib/userScriptBuilderLayer.d.ts +0 -2
- package/lib/commonjs/lib/userScriptBuilderLayer.js +7 -8
- package/lib/commonjs/lib/userScriptBuilderLayer.js.map +1 -1
- package/lib/commonjs/lib/views.js +3 -2
- package/lib/commonjs/lib/views.js.map +1 -1
- package/lib/commonjs/lib/webAddressingEnv.d.ts +0 -2
- package/lib/commonjs/lib/webAddressingEnv.js +4 -4
- package/lib/commonjs/lib/webAddressingEnv.js.map +1 -1
- package/lib/commonjs/platforms/aws/awsCredentials.js +3 -1
- package/lib/commonjs/platforms/aws/awsCredentials.js.map +1 -1
- package/lib/commonjs/platforms/aws/cdkApp.js +1 -1
- package/lib/commonjs/platforms/aws/cdkApp.js.map +1 -1
- package/lib/commonjs/platforms/aws/clearResources.js +16 -26
- package/lib/commonjs/platforms/aws/clearResources.js.map +1 -1
- package/lib/commonjs/platforms/aws/getDeployEnv.d.ts +1 -0
- package/lib/commonjs/platforms/aws/getDeployEnv.js +12 -0
- package/lib/commonjs/platforms/aws/getDeployEnv.js.map +1 -0
- package/lib/commonjs/platforms/aws/go.js +17 -15
- package/lib/commonjs/platforms/aws/go.js.map +1 -1
- package/lib/commonjs/platforms/aws/goDocker.js +29 -26
- package/lib/commonjs/platforms/aws/goDocker.js.map +1 -1
- package/lib/commonjs/platforms/aws/goDockerManifest.js +6 -1
- package/lib/commonjs/platforms/aws/goDockerManifest.js.map +1 -1
- package/lib/commonjs/platforms/aws/publish.js +13 -11
- package/lib/commonjs/platforms/aws/publish.js.map +1 -1
- package/lib/commonjs/platforms/aws/remote.js +8 -7
- package/lib/commonjs/platforms/aws/remote.js.map +1 -1
- package/lib/commonjs/platforms/aws/setup/buildBucketNamesStep.js +4 -4
- package/lib/commonjs/platforms/aws/setup/buildBucketNamesStep.js.map +1 -1
- package/lib/commonjs/platforms/aws/setup/buildGithubDeployRoleStep.js +4 -3
- package/lib/commonjs/platforms/aws/setup/buildGithubDeployRoleStep.js.map +1 -1
- package/lib/commonjs/platforms/aws/stacks.d.ts +0 -1
- package/lib/commonjs/platforms/aws/stacks.js +21 -33
- package/lib/commonjs/platforms/aws/stacks.js.map +1 -1
- package/lib/commonjs/platforms/aws/teardown.js +9 -7
- package/lib/commonjs/platforms/aws/teardown.js.map +1 -1
- package/lib/commonjs/platforms/aws/viewsSync.js +23 -11
- package/lib/commonjs/platforms/aws/viewsSync.js.map +1 -1
- package/lib/commonjs/platforms/docker/go.js +20 -18
- package/lib/commonjs/platforms/docker/go.js.map +1 -1
- package/lib/commonjs/platforms/docker/index.js +5 -4
- package/lib/commonjs/platforms/docker/index.js.map +1 -1
- package/lib/commonjs/platforms/docker/parseMounts.js +3 -2
- package/lib/commonjs/platforms/docker/parseMounts.js.map +1 -1
- package/lib/commonjs/platforms/index.js +4 -2
- package/lib/commonjs/platforms/index.js.map +1 -1
- package/lib/commonjs/platforms/types.d.ts +2 -2
- package/lib/commonjs/platforms/types.js.map +1 -1
- package/lib/esm/cli/commandMenu.js +5 -4
- package/lib/esm/cli/commandMenu.js.map +1 -1
- package/lib/esm/cli/runCli.js +15 -7
- package/lib/esm/cli/runCli.js.map +1 -1
- package/lib/esm/commands/checkCircular.js +15 -7
- package/lib/esm/commands/checkCircular.js.map +1 -1
- package/lib/esm/commands/clearResources.js +8 -14
- package/lib/esm/commands/clearResources.js.map +1 -1
- package/lib/esm/commands/go.js +3 -7
- package/lib/esm/commands/go.js.map +1 -1
- package/lib/esm/commands/goDev.js +4 -2
- package/lib/esm/commands/goDev.js.map +1 -1
- package/lib/esm/commands/goDevApi.js +21 -18
- package/lib/esm/commands/goDevApi.js.map +1 -1
- package/lib/esm/commands/goDevWeb.js +12 -8
- package/lib/esm/commands/goDevWeb.js.map +1 -1
- package/lib/esm/commands/goDocker.js +10 -13
- package/lib/esm/commands/goDocker.js.map +1 -1
- package/lib/esm/commands/hooks.js +4 -2
- package/lib/esm/commands/hooks.js.map +1 -1
- package/lib/esm/commands/migrate.js +9 -7
- package/lib/esm/commands/migrate.js.map +1 -1
- package/lib/esm/commands/prep.js +4 -2
- package/lib/esm/commands/prep.js.map +1 -1
- package/lib/esm/commands/publish.js +4 -7
- package/lib/esm/commands/publish.js.map +1 -1
- package/lib/esm/commands/scriptBuild.js +7 -5
- package/lib/esm/commands/scriptBuild.js.map +1 -1
- package/lib/esm/commands/scriptBuilderLayer.js +6 -4
- package/lib/esm/commands/scriptBuilderLayer.js.map +1 -1
- package/lib/esm/commands/scriptNew.js +7 -5
- package/lib/esm/commands/scriptNew.js.map +1 -1
- package/lib/esm/commands/setup.js +14 -22
- package/lib/esm/commands/setup.js.map +1 -1
- package/lib/esm/commands/synth.js +18 -22
- package/lib/esm/commands/synth.js.map +1 -1
- package/lib/esm/commands/teardown.js +8 -14
- package/lib/esm/commands/teardown.js.map +1 -1
- package/lib/esm/lib/CliError.d.ts +4 -0
- package/lib/esm/lib/CliError.js +11 -0
- package/lib/esm/lib/CliError.js.map +1 -0
- package/lib/esm/lib/circularImports.d.ts +0 -1
- package/lib/esm/lib/circularImports.js +4 -4
- package/lib/esm/lib/circularImports.js.map +1 -1
- package/lib/esm/lib/clearResourcesPlan.d.ts +0 -1
- package/lib/esm/lib/clearResourcesPlan.js +12 -12
- package/lib/esm/lib/clearResourcesPlan.js.map +1 -1
- package/lib/esm/lib/deployPrompts.d.ts +2 -1
- package/lib/esm/lib/deployPrompts.js +17 -17
- package/lib/esm/lib/deployPrompts.js.map +1 -1
- package/lib/esm/lib/devServerEntry.js +5 -4
- package/lib/esm/lib/devServerEntry.js.map +1 -1
- package/lib/esm/lib/devServerPorts.js +2 -3
- package/lib/esm/lib/devServerPorts.js.map +1 -1
- package/lib/esm/lib/discovery.d.ts +0 -2
- package/lib/esm/lib/discovery.js +10 -38
- package/lib/esm/lib/discovery.js.map +1 -1
- package/lib/esm/lib/hooks.js +5 -3
- package/lib/esm/lib/hooks.js.map +1 -1
- package/lib/esm/lib/killChildWithEscalation.js +3 -1
- package/lib/esm/lib/killChildWithEscalation.js.map +1 -1
- package/lib/esm/lib/killStaleListeners.js +24 -37
- package/lib/esm/lib/killStaleListeners.js.map +1 -1
- package/lib/esm/lib/out.d.ts +11 -0
- package/lib/esm/lib/out.js +26 -0
- package/lib/esm/lib/out.js.map +1 -0
- package/lib/esm/lib/prompts.d.ts +1 -0
- package/lib/esm/lib/prompts.js +13 -1
- package/lib/esm/lib/prompts.js.map +1 -1
- package/lib/esm/lib/qpqConfigs.js +4 -4
- package/lib/esm/lib/qpqConfigs.js.map +1 -1
- package/lib/esm/lib/requireDriverCapability.d.ts +7 -0
- package/lib/esm/lib/requireDriverCapability.js +13 -0
- package/lib/esm/lib/requireDriverCapability.js.map +1 -0
- package/lib/esm/lib/resolveAppSelection.d.ts +1 -0
- package/lib/esm/lib/resolveAppSelection.js +17 -11
- package/lib/esm/lib/resolveAppSelection.js.map +1 -1
- package/lib/esm/lib/resolveCommandContext.d.ts +12 -0
- package/lib/esm/lib/resolveCommandContext.js +12 -0
- package/lib/esm/lib/resolveCommandContext.js.map +1 -0
- package/lib/esm/lib/resolveDeployment.d.ts +0 -1
- package/lib/esm/lib/resolveDeployment.js +13 -8
- package/lib/esm/lib/resolveDeployment.js.map +1 -1
- package/lib/esm/lib/runCommand.d.ts +20 -0
- package/lib/esm/lib/runCommand.js +52 -31
- package/lib/esm/lib/runCommand.js.map +1 -1
- package/lib/esm/lib/runTasks.js +8 -4
- package/lib/esm/lib/runTasks.js.map +1 -1
- package/lib/esm/lib/timing.js +5 -3
- package/lib/esm/lib/timing.js.map +1 -1
- package/lib/esm/lib/typeWatcher.d.ts +2 -1
- package/lib/esm/lib/typeWatcher.js +6 -13
- package/lib/esm/lib/typeWatcher.js.map +1 -1
- package/lib/esm/lib/userScriptBuilderLayer.d.ts +0 -2
- package/lib/esm/lib/userScriptBuilderLayer.js +5 -5
- package/lib/esm/lib/userScriptBuilderLayer.js.map +1 -1
- package/lib/esm/lib/views.js +3 -2
- package/lib/esm/lib/views.js.map +1 -1
- package/lib/esm/lib/webAddressingEnv.d.ts +0 -2
- package/lib/esm/lib/webAddressingEnv.js +1 -1
- package/lib/esm/lib/webAddressingEnv.js.map +1 -1
- package/lib/esm/platforms/aws/awsCredentials.js +3 -1
- package/lib/esm/platforms/aws/awsCredentials.js.map +1 -1
- package/lib/esm/platforms/aws/cdkApp.js +1 -1
- package/lib/esm/platforms/aws/cdkApp.js.map +1 -1
- package/lib/esm/platforms/aws/clearResources.js +16 -25
- package/lib/esm/platforms/aws/clearResources.js.map +1 -1
- package/lib/esm/platforms/aws/getDeployEnv.d.ts +1 -0
- package/lib/esm/platforms/aws/getDeployEnv.js +8 -0
- package/lib/esm/platforms/aws/getDeployEnv.js.map +1 -0
- package/lib/esm/platforms/aws/go.js +17 -15
- package/lib/esm/platforms/aws/go.js.map +1 -1
- package/lib/esm/platforms/aws/goDocker.js +29 -26
- package/lib/esm/platforms/aws/goDocker.js.map +1 -1
- package/lib/esm/platforms/aws/goDockerManifest.js +6 -1
- package/lib/esm/platforms/aws/goDockerManifest.js.map +1 -1
- package/lib/esm/platforms/aws/publish.js +13 -11
- package/lib/esm/platforms/aws/publish.js.map +1 -1
- package/lib/esm/platforms/aws/remote.js +9 -7
- package/lib/esm/platforms/aws/remote.js.map +1 -1
- package/lib/esm/platforms/aws/setup/buildBucketNamesStep.js +2 -2
- package/lib/esm/platforms/aws/setup/buildBucketNamesStep.js.map +1 -1
- package/lib/esm/platforms/aws/setup/buildGithubDeployRoleStep.js +4 -3
- package/lib/esm/platforms/aws/setup/buildGithubDeployRoleStep.js.map +1 -1
- package/lib/esm/platforms/aws/stacks.d.ts +0 -1
- package/lib/esm/platforms/aws/stacks.js +22 -30
- package/lib/esm/platforms/aws/stacks.js.map +1 -1
- package/lib/esm/platforms/aws/teardown.js +9 -7
- package/lib/esm/platforms/aws/teardown.js.map +1 -1
- package/lib/esm/platforms/aws/viewsSync.js +22 -10
- package/lib/esm/platforms/aws/viewsSync.js.map +1 -1
- package/lib/esm/platforms/docker/go.js +21 -19
- package/lib/esm/platforms/docker/go.js.map +1 -1
- package/lib/esm/platforms/docker/index.js +5 -4
- package/lib/esm/platforms/docker/index.js.map +1 -1
- package/lib/esm/platforms/docker/parseMounts.js +3 -2
- package/lib/esm/platforms/docker/parseMounts.js.map +1 -1
- package/lib/esm/platforms/index.js +4 -2
- package/lib/esm/platforms/index.js.map +1 -1
- package/lib/esm/platforms/types.d.ts +2 -2
- package/lib/esm/platforms/types.js.map +1 -1
- package/package.json +28 -15
- package/templates/user-script/README.md +1 -1
package/lib/esm/lib/hooks.js
CHANGED
|
@@ -3,6 +3,8 @@ import path from 'path';
|
|
|
3
3
|
import { getAppDirectory, getAppsDirectory, getAvailableApps, getRoot } from './discovery';
|
|
4
4
|
import { nextPrefixColor, runCommand, runCommandPrefixed } from './runCommand';
|
|
5
5
|
import { runDependencyTasks } from './runTasks';
|
|
6
|
+
import { createOutput } from './out';
|
|
7
|
+
const out = createOutput('hooks');
|
|
6
8
|
// App lifecycle hooks: apps/<app>/package.json scripts named `qpq:<hook>`
|
|
7
9
|
// (e.g. qpq:postinstall, qpq:prebuild). The CLI invokes them when present;
|
|
8
10
|
// apps without the hook are skipped silently.
|
|
@@ -16,7 +18,7 @@ export const runAppHook = async (appName, hook) => {
|
|
|
16
18
|
if (!packageJson.scripts?.[scriptName]) {
|
|
17
19
|
return false;
|
|
18
20
|
}
|
|
19
|
-
|
|
21
|
+
out.log(`Running ${scriptName} for [${appName}]`);
|
|
20
22
|
await runCommand('npm', ['run', scriptName], { cwd: getAppDirectory(appName) });
|
|
21
23
|
return true;
|
|
22
24
|
};
|
|
@@ -129,7 +131,7 @@ const runHookForPackages = async (candidates, hook, jobs) => {
|
|
|
129
131
|
.map((candidate) => ({ ...candidate, scriptName: resolveHookScript(candidate.pkg, hook) }))
|
|
130
132
|
.filter((candidate) => candidate.scriptName !== undefined);
|
|
131
133
|
if (hookPackages.length === 0) {
|
|
132
|
-
|
|
134
|
+
out.log(`No app or workspace package defines a "qpq:${hook}" or "${hook}" script, nothing to run.`);
|
|
133
135
|
return [];
|
|
134
136
|
}
|
|
135
137
|
// Dependency edges only count between packages that are part of this run:
|
|
@@ -141,7 +143,7 @@ const runHookForPackages = async (candidates, hook, jobs) => {
|
|
|
141
143
|
deps: getDeclaredDependencyNames(hookPackage.pkg).filter((name) => runSetNames.has(name) && name !== hookPackage.pkg.name),
|
|
142
144
|
run: () => runCommandPrefixed(hookPackage.label, 'npm', ['run', hookPackage.scriptName], { cwd: hookPackage.dir, color: nextPrefixColor() }),
|
|
143
145
|
}));
|
|
144
|
-
|
|
146
|
+
out.log(`Running ${hook} hooks in ${tasks.length} package(s) (${jobs} jobs, dependency ordered)`);
|
|
145
147
|
return runDependencyTasks(tasks, jobs);
|
|
146
148
|
};
|
|
147
149
|
/** Runs a hook in every app and workspace package that defines it. Returns the failures; callers decide fatality. */
|
package/lib/esm/lib/hooks.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hooks.js","sourceRoot":"","sources":["../../../src/lib/hooks.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAC3F,OAAO,EAAE,eAAe,EAAE,UAAU,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAC/E,OAAO,EAAE,kBAAkB,EAAe,MAAM,YAAY,CAAC;AAoB7D,0EAA0E;AAC1E,2EAA2E;AAC3E,8CAA8C;AAC9C,MAAM,CAAC,MAAM,UAAU,GAAG,KAAK,EAAE,OAAe,EAAE,IAAY,EAAoB,EAAE;IAClF,MAAM,eAAe,GAAG,IAAI,CAAC,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,EAAE,cAAc,CAAC,CAAC;IAC5E,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,eAAe,CAAC,EAAE,CAAC;QACpC,OAAO,KAAK,CAAC;IACf,CAAC;IAED,MAAM,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,CAAC,eAAe,EAAE,OAAO,CAAC,CAAC,CAAC;IAC1E,MAAM,UAAU,GAAG,OAAO,IAAI,EAAE,CAAC;IACjC,IAAI,CAAC,WAAW,CAAC,OAAO,EAAE,CAAC,UAAU,CAAC,EAAE,CAAC;QACvC,OAAO,KAAK,CAAC;IACf,CAAC;IAED,OAAO,CAAC,GAAG,CAAC,WAAW,UAAU,SAAS,OAAO,GAAG,CAAC,CAAC;IACtD,MAAM,UAAU,CAAC,KAAK,EAAE,CAAC,KAAK,EAAE,UAAU,CAAC,EAAE,EAAE,GAAG,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C,WAAW,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,WAAW,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,IAAI,KAAK,WAAW,CAAC,GAAG,CAAC,IAAI,CAAC;QAC1H,GAAG,EAAE,GAAG,EAAE,CAAC,kBAAkB,CAAC,WAAW,CAAC,KAAK,EAAE,KAAK,EAAE,CAAC,KAAK,EAAE,WAAW,CAAC,UAAU,CAAC,EAAE,EAAE,GAAG,EAAE,WAAW,CAAC,GAAG,EAAE,KAAK,EAAE,eAAe,EAAE,EAAE,CAAC;KAC7I,CAAC,CAAC,CAAC;IAEJ,OAAO,CAAC,GAAG,CAAC,WAAW,IAAI,aAAa,KAAK,CAAC,MAAM,gBAAgB,IAAI,4BAA4B,CAAC,CAAC;IACtG,OAAO,kBAAkB,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;AACzC,CAAC,CAAC;AAEF,qHAAqH;AACrH,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,IAAY,EAAE,IAAY,EAA0B,EAAE,CAAC,kBAAkB,CAAC,eAAe,EAAE,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AAE/I;;;GAGG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,IAAY,EAAE,OAAe,EAAE,IAAY,EAA0B,EAAE,CAC3G,kBAAkB,CAAC,kBAAkB,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC","sourcesContent":["import fs from 'fs';\nimport path from 'path';\n\nimport { getAppDirectory, getAppsDirectory, getAvailableApps, getRoot } from './discovery';\nimport { nextPrefixColor, runCommand, runCommandPrefixed } from './runCommand';\nimport { runDependencyTasks, TaskFailure } from './runTasks';\n\ninterface HookPackageJson {\n name?: string;\n scripts?: Record<string, string>;\n workspaces?: string[];\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n}\n\n// A directory whose package.json can carry qpq:<hook> scripts: either an app\n// (apps/<app>/package.json, which need not be an npm workspace) or any package\n// matched by the consumer root's `workspaces` globs.\ninterface HookPackage {\n dir: string;\n label: string; // app name or package name, for display\n pkg: HookPackageJson;\n}\n\n// App lifecycle hooks: apps/<app>/package.json scripts named `qpq:<hook>`\n// (e.g. qpq:postinstall, qpq:prebuild). The CLI invokes them when present;\n// apps without the hook are skipped silently.\nexport const runAppHook = async (appName: string, hook: string): Promise<boolean> => {\n const packageJsonPath = path.join(getAppDirectory(appName), 'package.json');\n if (!fs.existsSync(packageJsonPath)) {\n return false;\n }\n\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));\n const scriptName = `qpq:${hook}`;\n if (!packageJson.scripts?.[scriptName]) {\n return false;\n }\n\n console.log(`Running ${scriptName} for [${appName}]`);\n await runCommand('npm', ['run', scriptName], { cwd: getAppDirectory(appName) });\n return true;\n};\n\nconst isDirectory = (candidate: string): boolean => fs.existsSync(candidate) && fs.statSync(candidate).isDirectory();\n\nconst listSubdirectories = (dir: string): string[] => {\n if (!isDirectory(dir)) {\n return [];\n }\n return fs\n .readdirSync(dir)\n .map((name) => path.join(dir, name))\n .filter(isDirectory);\n};\n\n// Expand one `workspaces` glob. Only literal segments and bare `*` are\n// supported, which covers the patterns qpq repos use (e.g.\n// \"apps/*/services/*/models\"); anything fancier (\"**\", braces) matches nothing.\nconst expandWorkspacePattern = (root: string, pattern: string): string[] => {\n let dirs = [root];\n for (const segment of pattern.split('/')) {\n if (segment === '*') {\n dirs = dirs.flatMap(listSubdirectories);\n } else {\n dirs = dirs.map((dir) => path.join(dir, segment)).filter(isDirectory);\n }\n }\n return dirs;\n};\n\nconst readPackageJson = (dir: string): HookPackageJson | undefined => {\n const packageJsonPath = path.join(dir, 'package.json');\n if (!fs.existsSync(packageJsonPath)) {\n return undefined;\n }\n return JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8')) as HookPackageJson;\n};\n\n// Every directory that can carry hooks: app dirs plus all workspace packages,\n// deduped (an app dir could itself be a workspace).\nconst getHookPackages = (): HookPackage[] => {\n const root = getRoot();\n const rootPkg = readPackageJson(root);\n\n const appDirs = getAvailableApps().map((appName) => ({ dir: getAppDirectory(appName), fallbackLabel: appName }));\n const workspaceDirs = (rootPkg?.workspaces ?? [])\n .flatMap((pattern) => expandWorkspacePattern(root, pattern))\n .map((dir) => ({ dir, fallbackLabel: path.relative(root, dir) }));\n\n const packages: HookPackage[] = [];\n const seen = new Set<string>();\n for (const { dir, fallbackLabel } of [...appDirs, ...workspaceDirs]) {\n const resolved = path.resolve(dir);\n if (seen.has(resolved)) {\n continue;\n }\n seen.add(resolved);\n\n const pkg = readPackageJson(dir);\n if (pkg) {\n packages.push({ dir, label: pkg.name ?? fallbackLabel, pkg });\n }\n }\n\n return packages;\n};\n\n// The script a hook resolves to in one package: `qpq:<hook>` when defined,\n// otherwise the plain `<hook>` script. Empty-string scripts count as absent.\nconst resolveHookScript = (pkg: HookPackageJson, hook: string): string | undefined => {\n if (pkg.scripts?.[`qpq:${hook}`]) {\n return `qpq:${hook}`;\n }\n if (pkg.scripts?.[hook]) {\n return hook;\n }\n return undefined;\n};\n\nconst getDeclaredDependencyNames = (pkg: HookPackageJson): string[] =>\n Object.keys({ ...pkg.dependencies, ...pkg.devDependencies, ...pkg.peerDependencies });\n\n// True for a package inside apps/<some other app>/. Packages outside apps/\n// are shared, so they never count as another app's.\nconst isOtherAppPackage = (dir: string, appName: string): boolean => {\n const relative = path.relative(getAppsDirectory(), path.resolve(dir));\n if (relative === '' || relative.startsWith('..') || path.isAbsolute(relative)) {\n return false;\n }\n return relative.split(path.sep)[0] !== appName;\n};\n\n// The app's own packages and the shared ones, plus every package they depend\n// on wherever it lives, so a cross-app dependency still gets built.\nconst getAppHookPackages = (appName: string): HookPackage[] => {\n const allPackages = getHookPackages();\n const byName = new Map<string, HookPackage>();\n for (const hookPackage of allPackages) {\n if (hookPackage.pkg.name) {\n byName.set(hookPackage.pkg.name, hookPackage);\n }\n }\n\n const selected = new Set(allPackages.filter((hookPackage) => !isOtherAppPackage(hookPackage.dir, appName)));\n const pending = [...selected];\n for (let current = pending.pop(); current; current = pending.pop()) {\n for (const depName of getDeclaredDependencyNames(current.pkg)) {\n const dep = byName.get(depName);\n if (dep && !selected.has(dep)) {\n selected.add(dep);\n pending.push(dep);\n }\n }\n }\n\n return allPackages.filter((hookPackage) => selected.has(hookPackage));\n};\n\n// Run the hook's script in each of `candidates` that defines it (qpq:<hook>\n// preferred over a plain <hook> script), in dependency order (declared deps\n// resolved by package name), with up to `jobs` running concurrently. Packages\n// whose dependencies aren't part of this run don't wait on them.\nconst runHookForPackages = async (candidates: HookPackage[], hook: string, jobs: number): Promise<TaskFailure[]> => {\n const hookPackages = candidates\n .map((candidate) => ({ ...candidate, scriptName: resolveHookScript(candidate.pkg, hook) }))\n .filter((candidate): candidate is HookPackage & { scriptName: string } => candidate.scriptName !== undefined);\n\n if (hookPackages.length === 0) {\n console.log(`No app or workspace package defines a \"qpq:${hook}\" or \"${hook}\" script, nothing to run.`);\n return [];\n }\n\n // Dependency edges only count between packages that are part of this run:\n // a dep that doesn't define the hook has nothing to wait for.\n const runSetNames = new Set(hookPackages.map((hookPackage) => hookPackage.pkg.name).filter(Boolean));\n\n const tasks = hookPackages.map((hookPackage) => ({\n id: hookPackage.pkg.name ?? hookPackage.dir,\n label: hookPackage.label,\n deps: getDeclaredDependencyNames(hookPackage.pkg).filter((name) => runSetNames.has(name) && name !== hookPackage.pkg.name),\n run: () => runCommandPrefixed(hookPackage.label, 'npm', ['run', hookPackage.scriptName], { cwd: hookPackage.dir, color: nextPrefixColor() }),\n }));\n\n console.log(`Running ${hook} hooks in ${tasks.length} package(s) (${jobs} jobs, dependency ordered)`);\n return runDependencyTasks(tasks, jobs);\n};\n\n/** Runs a hook in every app and workspace package that defines it. Returns the failures; callers decide fatality. */\nexport const runHookForAllPackages = (hook: string, jobs: number): Promise<TaskFailure[]> => runHookForPackages(getHookPackages(), hook, jobs);\n\n/**\n * Runs a hook in one app's packages, the shared packages outside apps/, and anything those depend on.\n * Other apps' packages are skipped. Returns the failures; callers decide fatality.\n */\nexport const runHookForAppPackages = (hook: string, appName: string, jobs: number): Promise<TaskFailure[]> =>\n runHookForPackages(getAppHookPackages(appName), hook, jobs);\n"]}
|
|
1
|
+
{"version":3,"file":"hooks.js","sourceRoot":"","sources":["../../../src/lib/hooks.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAC3F,OAAO,EAAE,eAAe,EAAE,UAAU,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAC/E,OAAO,EAAE,kBAAkB,EAAe,MAAM,YAAY,CAAC;AAC7D,OAAO,EAAE,YAAY,EAAE,MAAM,OAAO,CAAC;AAErC,MAAM,GAAG,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC;AAoBlC,0EAA0E;AAC1E,2EAA2E;AAC3E,8CAA8C;AAC9C,MAAM,CAAC,MAAM,UAAU,GAAG,KAAK,EAAE,OAAe,EAAE,IAAY,EAAoB,EAAE;IAClF,MAAM,eAAe,GAAG,IAAI,CAAC,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,EAAE,cAAc,CAAC,CAAC;IAC5E,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,eAAe,CAAC,EAAE,CAAC;QACpC,OAAO,KAAK,CAAC;IACf,CAAC;IAED,MAAM,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,CAAC,eAAe,EAAE,OAAO,CAAC,CAAC,CAAC;IAC1E,MAAM,UAAU,GAAG,OAAO,IAAI,EAAE,CAAC;IACjC,IAAI,CAAC,WAAW,CAAC,OAAO,EAAE,CAAC,UAAU,CAAC,EAAE,CAAC;QACvC,OAAO,KAAK,C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WAAW,EAAE,EAAE,CAAC,CAAC;QAC/C,EAAE,EAAE,WAAW,CAAC,GAAG,CAAC,IAAI,IAAI,WAAW,CAAC,GAAG;QAC3C,KAAK,EAAE,WAAW,CAAC,KAAK;QACxB,IAAI,EAAE,0BAA0B,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,WAAW,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,IAAI,KAAK,WAAW,CAAC,GAAG,CAAC,IAAI,CAAC;QAC1H,GAAG,EAAE,GAAG,EAAE,CAAC,kBAAkB,CAAC,WAAW,CAAC,KAAK,EAAE,KAAK,EAAE,CAAC,KAAK,EAAE,WAAW,CAAC,UAAU,CAAC,EAAE,EAAE,GAAG,EAAE,WAAW,CAAC,GAAG,EAAE,KAAK,EAAE,eAAe,EAAE,EAAE,CAAC;KAC7I,CAAC,CAAC,CAAC;IAEJ,GAAG,CAAC,GAAG,CAAC,WAAW,IAAI,aAAa,KAAK,CAAC,MAAM,gBAAgB,IAAI,4BAA4B,CAAC,CAAC;IAClG,OAAO,kBAAkB,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;AACzC,CAAC,CAAC;AAEF,qHAAqH;AACrH,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,IAAY,EAAE,IAAY,EAA0B,EAAE,CAAC,kBAAkB,CAAC,eAAe,EAAE,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AAE/I;;;GAGG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,IAAY,EAAE,OAAe,EAAE,IAAY,EAA0B,EAAE,CAC3G,kBAAkB,CAAC,kBAAkB,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC","sourcesContent":["import fs from 'fs';\nimport path from 'path';\n\nimport { getAppDirectory, getAppsDirectory, getAvailableApps, getRoot } from './discovery';\nimport { nextPrefixColor, runCommand, runCommandPrefixed } from './runCommand';\nimport { runDependencyTasks, TaskFailure } from './runTasks';\nimport { createOutput } from './out';\n\nconst out = createOutput('hooks');\n\ntype HookPackageJson = {\n name?: string;\n scripts?: Record<string, string>;\n workspaces?: string[];\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n};\n\n// A directory whose package.json can carry qpq:<hook> scripts: either an app\n// (apps/<app>/package.json, which need not be an npm workspace) or any package\n// matched by the consumer root's `workspaces` globs.\ntype HookPackage = {\n dir: string;\n label: string; // app name or package name, for display\n pkg: HookPackageJson;\n};\n\n// App lifecycle hooks: apps/<app>/package.json scripts named `qpq:<hook>`\n// (e.g. qpq:postinstall, qpq:prebuild). The CLI invokes them when present;\n// apps without the hook are skipped silently.\nexport const runAppHook = async (appName: string, hook: string): Promise<boolean> => {\n const packageJsonPath = path.join(getAppDirectory(appName), 'package.json');\n if (!fs.existsSync(packageJsonPath)) {\n return false;\n }\n\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));\n const scriptName = `qpq:${hook}`;\n if (!packageJson.scripts?.[scriptName]) {\n return false;\n }\n\n out.log(`Running ${scriptName} for [${appName}]`);\n await runCommand('npm', ['run', scriptName], { cwd: getAppDirectory(appName) });\n return true;\n};\n\nconst isDirectory = (candidate: string): boolean => fs.existsSync(candidate) && fs.statSync(candidate).isDirectory();\n\nconst listSubdirectories = (dir: string): string[] => {\n if (!isDirectory(dir)) {\n return [];\n }\n return fs\n .readdirSync(dir)\n .map((name) => path.join(dir, name))\n .filter(isDirectory);\n};\n\n// Expand one `workspaces` glob. Only literal segments and bare `*` are\n// supported, which covers the patterns qpq repos use (e.g.\n// \"apps/*/services/*/models\"); anything fancier (\"**\", braces) matches nothing.\nconst expandWorkspacePattern = (root: string, pattern: string): string[] => {\n let dirs = [root];\n for (const segment of pattern.split('/')) {\n if (segment === '*') {\n dirs = dirs.flatMap(listSubdirectories);\n } else {\n dirs = dirs.map((dir) => path.join(dir, segment)).filter(isDirectory);\n }\n }\n return dirs;\n};\n\nconst readPackageJson = (dir: string): HookPackageJson | undefined => {\n const packageJsonPath = path.join(dir, 'package.json');\n if (!fs.existsSync(packageJsonPath)) {\n return undefined;\n }\n return JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8')) as HookPackageJson;\n};\n\n// Every directory that can carry hooks: app dirs plus all workspace packages,\n// deduped (an app dir could itself be a workspace).\nconst getHookPackages = (): HookPackage[] => {\n const root = getRoot();\n const rootPkg = readPackageJson(root);\n\n const appDirs = getAvailableApps().map((appName) => ({ dir: getAppDirectory(appName), fallbackLabel: appName }));\n const workspaceDirs = (rootPkg?.workspaces ?? [])\n .flatMap((pattern) => expandWorkspacePattern(root, pattern))\n .map((dir) => ({ dir, fallbackLabel: path.relative(root, dir) }));\n\n const packages: HookPackage[] = [];\n const seen = new Set<string>();\n for (const { dir, fallbackLabel } of [...appDirs, ...workspaceDirs]) {\n const resolved = path.resolve(dir);\n if (seen.has(resolved)) {\n continue;\n }\n seen.add(resolved);\n\n const pkg = readPackageJson(dir);\n if (pkg) {\n packages.push({ dir, label: pkg.name ?? fallbackLabel, pkg });\n }\n }\n\n return packages;\n};\n\n// The script a hook resolves to in one package: `qpq:<hook>` when defined,\n// otherwise the plain `<hook>` script. Empty-string scripts count as absent.\nconst resolveHookScript = (pkg: HookPackageJson, hook: string): string | undefined => {\n if (pkg.scripts?.[`qpq:${hook}`]) {\n return `qpq:${hook}`;\n }\n if (pkg.scripts?.[hook]) {\n return hook;\n }\n return undefined;\n};\n\nconst getDeclaredDependencyNames = (pkg: HookPackageJson): string[] =>\n Object.keys({ ...pkg.dependencies, ...pkg.devDependencies, ...pkg.peerDependencies });\n\n// True for a package inside apps/<some other app>/. Packages outside apps/\n// are shared, so they never count as another app's.\nconst isOtherAppPackage = (dir: string, appName: string): boolean => {\n const relative = path.relative(getAppsDirectory(), path.resolve(dir));\n if (relative === '' || relative.startsWith('..') || path.isAbsolute(relative)) {\n return false;\n }\n return relative.split(path.sep)[0] !== appName;\n};\n\n// The app's own packages and the shared ones, plus every package they depend\n// on wherever it lives, so a cross-app dependency still gets built.\nconst getAppHookPackages = (appName: string): HookPackage[] => {\n const allPackages = getHookPackages();\n const byName = new Map<string, HookPackage>();\n for (const hookPackage of allPackages) {\n if (hookPackage.pkg.name) {\n byName.set(hookPackage.pkg.name, hookPackage);\n }\n }\n\n const selected = new Set(allPackages.filter((hookPackage) => !isOtherAppPackage(hookPackage.dir, appName)));\n const pending = [...selected];\n for (let current = pending.pop(); current; current = pending.pop()) {\n for (const depName of getDeclaredDependencyNames(current.pkg)) {\n const dep = byName.get(depName);\n if (dep && !selected.has(dep)) {\n selected.add(dep);\n pending.push(dep);\n }\n }\n }\n\n return allPackages.filter((hookPackage) => selected.has(hookPackage));\n};\n\n// Run the hook's script in each of `candidates` that defines it (qpq:<hook>\n// preferred over a plain <hook> script), in dependency order (declared deps\n// resolved by package name), with up to `jobs` running concurrently. Packages\n// whose dependencies aren't part of this run don't wait on them.\nconst runHookForPackages = async (candidates: HookPackage[], hook: string, jobs: number): Promise<TaskFailure[]> => {\n const hookPackages = candidates\n .map((candidate) => ({ ...candidate, scriptName: resolveHookScript(candidate.pkg, hook) }))\n .filter((candidate): candidate is HookPackage & { scriptName: string } => candidate.scriptName !== undefined);\n\n if (hookPackages.length === 0) {\n out.log(`No app or workspace package defines a \"qpq:${hook}\" or \"${hook}\" script, nothing to run.`);\n return [];\n }\n\n // Dependency edges only count between packages that are part of this run:\n // a dep that doesn't define the hook has nothing to wait for.\n const runSetNames = new Set(hookPackages.map((hookPackage) => hookPackage.pkg.name).filter(Boolean));\n\n const tasks = hookPackages.map((hookPackage) => ({\n id: hookPackage.pkg.name ?? hookPackage.dir,\n label: hookPackage.label,\n deps: getDeclaredDependencyNames(hookPackage.pkg).filter((name) => runSetNames.has(name) && name !== hookPackage.pkg.name),\n run: () => runCommandPrefixed(hookPackage.label, 'npm', ['run', hookPackage.scriptName], { cwd: hookPackage.dir, color: nextPrefixColor() }),\n }));\n\n out.log(`Running ${hook} hooks in ${tasks.length} package(s) (${jobs} jobs, dependency ordered)`);\n return runDependencyTasks(tasks, jobs);\n};\n\n/** Runs a hook in every app and workspace package that defines it. Returns the failures; callers decide fatality. */\nexport const runHookForAllPackages = (hook: string, jobs: number): Promise<TaskFailure[]> => runHookForPackages(getHookPackages(), hook, jobs);\n\n/**\n * Runs a hook in one app's packages, the shared packages outside apps/, and anything those depend on.\n * Other apps' packages are skipped. Returns the failures; callers decide fatality.\n */\nexport const runHookForAppPackages = (hook: string, appName: string, jobs: number): Promise<TaskFailure[]> =>\n runHookForPackages(getAppHookPackages(appName), hook, jobs);\n"]}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { createOutput } from './out';
|
|
2
|
+
const out = createOutput('kill-child-with-escalation');
|
|
1
3
|
// Above the dev server's 5s worst-case shutdown budget, below docker's 10s
|
|
2
4
|
// default stop grace, so a container stop still exits cleanly rather than
|
|
3
5
|
// being SIGKILLed by docker mid-escalation.
|
|
@@ -16,7 +18,7 @@ export const killChildWithEscalation = (child, graceMs = DEFAULT_KILL_GRACE_MS)
|
|
|
16
18
|
}
|
|
17
19
|
return new Promise((resolve) => {
|
|
18
20
|
const timer = setTimeout(() => {
|
|
19
|
-
|
|
21
|
+
out.warn(`Dev server did not exit within ${graceMs}ms — sending SIGKILL.`);
|
|
20
22
|
child.kill('SIGKILL');
|
|
21
23
|
}, graceMs);
|
|
22
24
|
child.once('exit', () => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"killChildWithEscalation.js","sourceRoot":"","sources":["../../../src/lib/killChildWithEscalation.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"killChildWithEscalation.js","sourceRoot":"","sources":["../../../src/lib/killChildWithEscalation.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,YAAY,EAAE,MAAM,OAAO,CAAC;AAErC,MAAM,GAAG,GAAG,YAAY,CAAC,4BAA4B,CAAC,CAAC;AAEvD,2EAA2E;AAC3E,0EAA0E;AAC1E,4CAA4C;AAC5C,MAAM,qBAAqB,GAAG,IAAI,CAAC;AAEnC;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,KAAmB,EAAE,OAAO,GAAG,qBAAqB,EAAiB,EAAE;IAC7G,IAAI,KAAK,CAAC,QAAQ,KAAK,IAAI,IAAI,KAAK,CAAC,UAAU,KAAK,IAAI,EAAE,CAAC;QACzD,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IAED,OAAO,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE;QACnC,MAAM,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE;YAC5B,GAAG,CAAC,IAAI,CAAC,kCAAkC,OAAO,uBAAuB,CAAC,CAAC;YAC3E,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QACxB,CAAC,EAAE,OAAO,CAAC,CAAC;QAEZ,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE;YACtB,YAAY,CAAC,KAAK,CAAC,CAAC;YACpB,OAAO,EAAE,CAAC;QACZ,CAAC,CAAC,CAAC;QAEH,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IACxB,CAAC,CAAC,CAAC;AACL,CAAC,CAAC","sourcesContent":["// Stopping the dev server child, with a hard backstop.\n//\n// The dev server now runs an ordered shutdown on SIGTERM (drain in-flight\n// work, then checkpoint the stores) instead of dying instantly. That is the\n// point - it is what stops a save-triggered restart eating a queue message\n// mid-story - but it means a bare `child.kill()` followed by waiting for exit\n// can now wait forever if a teardown wedges. Without escalation this would\n// trade a data-loss bug for a hung-restart bug, and the next launch would find\n// its ports still held.\nimport { ChildProcess } from 'child_process';\nimport { createOutput } from './out';\n\nconst out = createOutput('kill-child-with-escalation');\n\n// Above the dev server's 5s worst-case shutdown budget, below docker's 10s\n// default stop grace, so a container stop still exits cleanly rather than\n// being SIGKILLed by docker mid-escalation.\nconst DEFAULT_KILL_GRACE_MS = 6000;\n\n/**\n * SIGTERM the child, resolve once it has actually exited, and SIGKILL it if it\n * has not gone within the grace window.\n *\n * Resolves rather than rejects on escalation: the caller's next move is the\n * same either way (start the replacement), and a rejection would only give\n * every call site a catch to write.\n */\nexport const killChildWithEscalation = (child: ChildProcess, graceMs = DEFAULT_KILL_GRACE_MS): Promise<void> => {\n if (child.exitCode !== null || child.signalCode !== null) {\n return Promise.resolve();\n }\n\n return new Promise<void>((resolve) => {\n const timer = setTimeout(() => {\n out.warn(`Dev server did not exit within ${graceMs}ms — sending SIGKILL.`);\n child.kill('SIGKILL');\n }, graceMs);\n\n child.once('exit', () => {\n clearTimeout(timer);\n resolve();\n });\n\n child.kill('SIGTERM');\n });\n};\n"]}
|
|
@@ -1,12 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
// wrapper died without killing its listener (closed terminal, SIGKILL) leaves
|
|
3
|
-
// an orphaned process holding a dev port, and the next launch dies with
|
|
4
|
-
// EADDRINUSE. Before starting, kill any listener on the given ports whose
|
|
5
|
-
// command line matches `isOurs`. Anything else on the ports is left alone
|
|
6
|
-
// and reported — it's not ours.
|
|
7
|
-
import { execSync } from 'child_process';
|
|
1
|
+
import { runCommandCaptureSync, sleepSync } from './runCommand';
|
|
8
2
|
import fs from 'fs';
|
|
9
3
|
import path from 'path';
|
|
4
|
+
import { createOutput } from './out';
|
|
5
|
+
const out = createOutput('kill-stale-listeners');
|
|
10
6
|
// Matches any invocation of the qpq CLI itself, regardless of how it was
|
|
11
7
|
// launched: `node node_modules/.bin/qpq ...` (the npm-script shim, which has
|
|
12
8
|
// no .js extension), a direct `node .../lib/commonjs/bin/qpq.js` call, a
|
|
@@ -21,22 +17,21 @@ export const isQpqCliCommand = (command) => command
|
|
|
21
17
|
const withoutExt = base.endsWith('.js') ? base.slice(0, -3) : base;
|
|
22
18
|
return withoutExt === 'qpq';
|
|
23
19
|
});
|
|
24
|
-
// SIGTERM only requests termination
|
|
20
|
+
// SIGTERM only requests termination, the caller (about to bind this same
|
|
25
21
|
// process's ports itself) needs it actually gone first. A stale dev server
|
|
26
22
|
// can be mid-startup when killed (still resolving config, not yet bound to
|
|
27
23
|
// every port it eventually binds) and keep running for a bit past the
|
|
28
|
-
// signal, going on to bind a LATER port
|
|
24
|
+
// signal, going on to bind a LATER port, waiting for just the one port that
|
|
29
25
|
// matched isn't enough; wait for the whole pid to disappear so it can't bind
|
|
30
26
|
// anything else afterward. Poll synchronously (this whole sweep runs before
|
|
31
|
-
// anything async starts) via `kill(pid, 0)
|
|
32
|
-
// these are unrelated
|
|
27
|
+
// anything async starts) via `kill(pid, 0)`, reliable and fast here because
|
|
28
|
+
// these are unrelated processes orphaned earlier, not children of this
|
|
33
29
|
// one (a real child can sit as a zombie answering `kill(pid, 0)` until this
|
|
34
30
|
// process's own event loop reaps it, which a tight sync loop would starve;
|
|
35
31
|
// doesn't apply to a process we didn't spawn).
|
|
36
32
|
//
|
|
37
33
|
// The default covers the dev server's graceful shutdown (drain in-flight work,
|
|
38
|
-
// then checkpoint the stores) with room to spare
|
|
39
|
-
// fine when the server died instantly and is not now. Returns whether the pid
|
|
34
|
+
// then checkpoint the stores) with room to spare. Returns whether the pid
|
|
40
35
|
// actually went, because a caller about to bind these ports has to escalate
|
|
41
36
|
// rather than hope: giving up while the old server still holds 8080 is exactly
|
|
42
37
|
// the EADDRINUSE this file exists to prevent.
|
|
@@ -49,13 +44,13 @@ const waitForPidGone = (pid, timeoutMs = 8000) => {
|
|
|
49
44
|
catch {
|
|
50
45
|
return true; // throws once the pid no longer exists
|
|
51
46
|
}
|
|
52
|
-
|
|
47
|
+
sleepSync(50);
|
|
53
48
|
}
|
|
54
49
|
return false;
|
|
55
50
|
};
|
|
56
51
|
// Last resort for a process that ignored, or wedged during, its graceful stop.
|
|
57
52
|
const killPidHard = (pid) => {
|
|
58
|
-
|
|
53
|
+
out.warn(`Process ${pid} did not exit gracefully — sending SIGKILL.`);
|
|
59
54
|
try {
|
|
60
55
|
process.kill(pid, 'SIGKILL');
|
|
61
56
|
}
|
|
@@ -70,8 +65,7 @@ const killPidHard = (pid) => {
|
|
|
70
65
|
// itself a symlink (a symlinked home directory, an NFS mount, etc).
|
|
71
66
|
const getProcessCwd = (pid) => {
|
|
72
67
|
try {
|
|
73
|
-
const line =
|
|
74
|
-
.toString()
|
|
68
|
+
const line = runCommandCaptureSync('lsof', ['-a', '-p', String(pid), '-d', 'cwd', '-Fn'])
|
|
75
69
|
.split('\n')
|
|
76
70
|
.find((l) => l.startsWith('n'));
|
|
77
71
|
return line ? fs.realpathSync(line.slice(1)) : null;
|
|
@@ -84,7 +78,7 @@ const getProcessCwd = (pid) => {
|
|
|
84
78
|
// `npx qpq go:dev:api` (or via any shell whose -c string names qpq), the
|
|
85
79
|
// ancestor chain (`sh -c "npx ... qpq ..."`, `npm exec qpq ...`) matches
|
|
86
80
|
// isQpqCliCommand and shares our cwd, so excluding just process.pid isn't
|
|
87
|
-
// enough
|
|
81
|
+
// enough, SIGINTing an ancestor tears down our own tree. Walk ppid to the
|
|
88
82
|
// top and exclude the whole chain.
|
|
89
83
|
const getOwnAncestorPids = () => {
|
|
90
84
|
const ancestors = new Set();
|
|
@@ -92,9 +86,7 @@ const getOwnAncestorPids = () => {
|
|
|
92
86
|
while (pid > 1 && !ancestors.has(pid)) {
|
|
93
87
|
ancestors.add(pid);
|
|
94
88
|
try {
|
|
95
|
-
pid = Number(
|
|
96
|
-
.toString()
|
|
97
|
-
.trim());
|
|
89
|
+
pid = Number(runCommandCaptureSync('ps', ['-o', 'ppid=', '-p', String(pid)]).trim());
|
|
98
90
|
}
|
|
99
91
|
catch {
|
|
100
92
|
break;
|
|
@@ -103,11 +95,11 @@ const getOwnAncestorPids = () => {
|
|
|
103
95
|
return ancestors;
|
|
104
96
|
};
|
|
105
97
|
// killStaleListeners only sees processes currently BOUND to one of the given
|
|
106
|
-
// ports
|
|
98
|
+
// ports, it can't catch a still-running `qpq go:dev*` watcher whose spawned
|
|
107
99
|
// dev-server child already died (a crash, or us killing just the child):
|
|
108
100
|
// the watcher itself holds no port at that moment, so it's invisible to a
|
|
109
|
-
// port scan, yet it's still alive and can spawn a fresh child
|
|
110
|
-
// port
|
|
101
|
+
// port scan, yet it's still alive and can spawn a fresh child, and bind a
|
|
102
|
+
// port, moments later, racing whatever we're about to start. Close that gap
|
|
111
103
|
// by finding any OTHER qpq CLI process rooted in the same repo checkout
|
|
112
104
|
// (matched by cwd, not by port or command-line args, which vary by how it
|
|
113
105
|
// was invoked) and killing it outright, regardless of what it currently has
|
|
@@ -118,9 +110,7 @@ export const killOtherQpqDevProcesses = (root) => {
|
|
|
118
110
|
const ownPids = getOwnAncestorPids();
|
|
119
111
|
let lines = [];
|
|
120
112
|
try {
|
|
121
|
-
lines =
|
|
122
|
-
.toString()
|
|
123
|
-
.split('\n');
|
|
113
|
+
lines = runCommandCaptureSync('ps', ['-axo', 'pid=,command=']).split('\n');
|
|
124
114
|
}
|
|
125
115
|
catch {
|
|
126
116
|
return;
|
|
@@ -138,7 +128,7 @@ export const killOtherQpqDevProcesses = (root) => {
|
|
|
138
128
|
continue;
|
|
139
129
|
if (getProcessCwd(pid) !== resolvedRoot)
|
|
140
130
|
continue;
|
|
141
|
-
|
|
131
|
+
out.log(`Killing other qpq dev process for this repo (pid ${pid}): ${command}`);
|
|
142
132
|
process.kill(pid, 'SIGINT');
|
|
143
133
|
if (!waitForPidGone(pid)) {
|
|
144
134
|
killPidHard(pid);
|
|
@@ -150,10 +140,7 @@ export const killOtherQpqDevProcesses = (root) => {
|
|
|
150
140
|
const getPortListeners = (port) => {
|
|
151
141
|
let pids = [];
|
|
152
142
|
try {
|
|
153
|
-
pids =
|
|
154
|
-
stdio: ['ignore', 'pipe', 'ignore'],
|
|
155
|
-
})
|
|
156
|
-
.toString()
|
|
143
|
+
pids = runCommandCaptureSync('lsof', ['-t', `-iTCP:${port}`, '-sTCP:LISTEN'])
|
|
157
144
|
.split('\n')
|
|
158
145
|
.map((line) => Number(line.trim()))
|
|
159
146
|
.filter(Boolean);
|
|
@@ -163,7 +150,7 @@ const getPortListeners = (port) => {
|
|
|
163
150
|
}
|
|
164
151
|
return pids.flatMap((pid) => {
|
|
165
152
|
try {
|
|
166
|
-
return [{ pid, command:
|
|
153
|
+
return [{ pid, command: runCommandCaptureSync('ps', ['-p', String(pid), '-o', 'command=']).trim() }];
|
|
167
154
|
}
|
|
168
155
|
catch {
|
|
169
156
|
return []; // already gone
|
|
@@ -186,8 +173,8 @@ const getPortListeners = (port) => {
|
|
|
186
173
|
export const reportPortHolders = (ports) => {
|
|
187
174
|
for (const port of ports) {
|
|
188
175
|
for (const { pid, command } of getPortListeners(port)) {
|
|
189
|
-
|
|
190
|
-
|
|
176
|
+
out.warn(`Port ${port} is currently held by pid ${pid}: ${command}`);
|
|
177
|
+
out.warn(` Starting anyway. If it still holds port ${port} once this server binds, startup will fail with EADDRINUSE.`);
|
|
191
178
|
}
|
|
192
179
|
}
|
|
193
180
|
};
|
|
@@ -195,14 +182,14 @@ export const killStaleListeners = (ports, isOurs) => {
|
|
|
195
182
|
for (const port of ports) {
|
|
196
183
|
for (const { pid, command } of getPortListeners(port)) {
|
|
197
184
|
if (isOurs(command)) {
|
|
198
|
-
|
|
185
|
+
out.log(`Killing stale dev server on port ${port} (pid ${pid})`);
|
|
199
186
|
process.kill(pid);
|
|
200
187
|
if (!waitForPidGone(pid)) {
|
|
201
188
|
killPidHard(pid);
|
|
202
189
|
}
|
|
203
190
|
}
|
|
204
191
|
else {
|
|
205
|
-
|
|
192
|
+
out.warn(`Port ${port} is in use by an unrelated process (pid ${pid}: ${command}) — not killing it.`);
|
|
206
193
|
}
|
|
207
194
|
}
|
|
208
195
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"killStaleListeners.js","sourceRoot":"","sources":["../../../src/lib/killStaleListeners.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,8EAA8E;AAC9E,wEAAwE;AACxE,0EAA0E;AAC1E,0EAA0E;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AAG,CAAC,oCAAoC,IAAI,SAAS,GAAG,GAAG,CAAC,CAAC;gBACrE,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;gBAClB,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,EAAE,CAAC;oBACzB,WAAW,CAAC,GAAG,CAAC,CAAC;gBACnB,CAAC;YACH,CAAC;iBAAM,CAAC;gBACN,OAAO,CAAC,IAAI,CAAC,QAAQ,IAAI,2CAA2C,GAAG,KAAK,OAAO,qBAAqB,CAAC,CAAC;YAC5G,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC,CAAC","sourcesContent":["// Pre-start sweep shared by the dev-server commands: a previous run whose\n// wrapper died without killing its listener (closed terminal, SIGKILL) leaves\n// an orphaned process holding a dev port, and the next launch dies with\n// EADDRINUSE. Before starting, kill any listener on the given ports whose\n// command line matches `isOurs`. Anything else on the ports is left alone\n// and reported — it's not ours.\nimport { execSync } from 'child_process';\nimport fs from 'fs';\nimport path from 'path';\n\n// Matches any invocation of the qpq CLI itself, regardless of how it was\n// launched: `node node_modules/.bin/qpq ...` (the npm-script shim, which has\n// no .js extension), a direct `node .../lib/commonjs/bin/qpq.js` call, a\n// global `qpq` shebang script, etc. Checks each whitespace-separated token's\n// basename (extension stripped) rather than a fixed substring like\n// 'bin/qpq.js', which only matches the last of those forms.\nexport const isQpqCliCommand = (command: string): boolean =>\n command\n .trim()\n .split(/\\s+/)\n .some((token) => {\n const base = path.basename(token);\n const withoutExt = base.endsWith('.js') ? base.slice(0, -3) : base;\n return withoutExt === 'qpq';\n });\n\n// SIGTERM only requests termination — the caller (about to bind this same\n// process's ports itself) needs it actually gone first. A stale dev server\n// can be mid-startup when killed (still resolving config, not yet bound to\n// every port it eventually binds) and keep running for a bit past the\n// signal, going on to bind a LATER port — waiting for just the one port that\n// matched isn't enough; wait for the whole pid to disappear so it can't bind\n// anything else afterward. Poll synchronously (this whole sweep runs before\n// anything async starts) via `kill(pid, 0)` — reliable and fast here because\n// these are unrelated, previously-orphaned processes, not children of this\n// one (a real child can sit as a zombie answering `kill(pid, 0)` until this\n// process's own event loop reaps it, which a tight sync loop would starve;\n// doesn't apply to a process we didn't spawn).\n//\n// The default covers the dev server's graceful shutdown (drain in-flight work,\n// then checkpoint the stores) with room to spare — it used to be 3s, which was\n// fine when the server died instantly and is not now. Returns whether the pid\n// actually went, because a caller about to bind these ports has to escalate\n// rather than hope: giving up while the old server still holds 8080 is exactly\n// the EADDRINUSE this file exists to prevent.\nconst waitForPidGone = (pid: number, timeoutMs = 8000): boolean => {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n try {\n process.kill(pid, 0);\n } catch {\n return true; // throws once the pid no longer exists\n }\n execSync('sleep 0.05');\n }\n\n return false;\n};\n\n// Last resort for a process that ignored, or wedged during, its graceful stop.\nconst killPidHard = (pid: number): void => {\n console.warn(`Process ${pid} did not exit gracefully — sending SIGKILL.`);\n try {\n process.kill(pid, 'SIGKILL');\n } catch {\n return; // raced us and exited after all\n }\n waitForPidGone(pid, 2000);\n};\n\n// realpath'd: lsof reports the canonical path (e.g. /private/tmp on macOS,\n// where /tmp is a symlink), so comparing against a caller-supplied root\n// verbatim would false-negative whenever any component of the repo path is\n// itself a symlink (a symlinked home directory, an NFS mount, etc).\nconst getProcessCwd = (pid: number): string | null => {\n try {\n const line = execSync(`lsof -a -p ${pid} -d cwd -Fn`, { stdio: ['ignore', 'pipe', 'ignore'] })\n .toString()\n .split('\\n')\n .find((l) => l.startsWith('n'));\n return line ? fs.realpathSync(line.slice(1)) : null;\n } catch {\n return null; // pid gone, or we don't have permission to inspect it\n }\n};\n\n// The sweep below must never target this process's own wrappers: launched as\n// `npx qpq go:dev:api` (or via any shell whose -c string names qpq), the\n// ancestor chain (`sh -c \"npx ... qpq ...\"`, `npm exec qpq ...`) matches\n// isQpqCliCommand and shares our cwd, so excluding just process.pid isn't\n// enough — SIGINTing an ancestor tears down our own tree. Walk ppid to the\n// top and exclude the whole chain.\nconst getOwnAncestorPids = (): Set<number> => {\n const ancestors = new Set<number>();\n let pid = process.pid;\n while (pid > 1 && !ancestors.has(pid)) {\n ancestors.add(pid);\n try {\n pid = Number(\n execSync(`ps -o ppid= -p ${pid}`, { stdio: ['ignore', 'pipe', 'ignore'] })\n .toString()\n .trim(),\n );\n } catch {\n break;\n }\n }\n return ancestors;\n};\n\n// killStaleListeners only sees processes currently BOUND to one of the given\n// ports — it can't catch a still-running `qpq go:dev*` watcher whose spawned\n// dev-server child already died (a crash, or us killing just the child):\n// the watcher itself holds no port at that moment, so it's invisible to a\n// port scan, yet it's still alive and can spawn a fresh child — and bind a\n// port — moments later, racing whatever we're about to start. Close that gap\n// by finding any OTHER qpq CLI process rooted in the same repo checkout\n// (matched by cwd, not by port or command-line args, which vary by how it\n// was invoked) and killing it outright, regardless of what it currently has\n// bound. SIGINT (not SIGTERM) so goDevApiCommand/goDevWebCommand's own\n// handler runs and tears down its child cleanly rather than orphaning it.\nexport const killOtherQpqDevProcesses = (root: string): void => {\n const resolvedRoot = fs.realpathSync(root);\n const ownPids = getOwnAncestorPids();\n\n let lines: string[] = [];\n try {\n lines = execSync('ps -axo pid=,command=', { stdio: ['ignore', 'pipe', 'ignore'] })\n .toString()\n .split('\\n');\n } catch {\n return;\n }\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n\n const spaceIndex = trimmed.indexOf(' ');\n if (spaceIndex === -1) continue;\n\n const pid = Number(trimmed.slice(0, spaceIndex));\n const command = trimmed.slice(spaceIndex + 1).trim();\n\n if (!pid || ownPids.has(pid) || !isQpqCliCommand(command)) continue;\n if (getProcessCwd(pid) !== resolvedRoot) continue;\n\n console.log(`Killing other qpq dev process for this repo (pid ${pid}): ${command}`);\n process.kill(pid, 'SIGINT');\n if (!waitForPidGone(pid)) {\n killPidHard(pid);\n }\n }\n};\n\n// Whatever is currently listening on a port, as pid + command line. Empty when\n// the port is free, or when lsof is unavailable.\nconst getPortListeners = (port: number): { pid: number; command: string }[] => {\n let pids: number[] = [];\n try {\n pids = execSync(`lsof -t -iTCP:${port} -sTCP:LISTEN`, {\n stdio: ['ignore', 'pipe', 'ignore'],\n })\n .toString()\n .split('\\n')\n .map((line) => Number(line.trim()))\n .filter(Boolean);\n } catch {\n return []; // lsof exits non-zero when nothing is listening\n }\n\n return pids.flatMap((pid) => {\n try {\n return [{ pid, command: execSync(`ps -p ${pid} -o command=`).toString().trim() }];\n } catch {\n return []; // already gone\n }\n });\n};\n\n/**\n * Say what is holding these ports, without touching it.\n *\n * The other half of --keep-other-dev-servers: sparing a sibling checkout's dev\n * server means this one cannot bind, and an unexplained EADDRINUSE is a worse\n * experience than the silent kill it replaces. Naming the pid and the command\n * turns \"it just died\" into something you can act on.\n *\n * Worded as a prediction, not a fact, because it IS one: this runs before the\n * bundle step, so by the time anything binds - seconds later - the holder may\n * well have gone. Stating \"port in use\" and then starting cleanly reads like\n * the warning was wrong.\n */\nexport const reportPortHolders = (ports: number[]): void => {\n for (const port of ports) {\n for (const { pid, command } of getPortListeners(port)) {\n console.warn(`Port ${port} is currently held by pid ${pid}: ${command}`);\n console.warn(` Starting anyway. If it still holds port ${port} once this server binds, startup will fail with EADDRINUSE.`);\n }\n }\n};\n\nexport const killStaleListeners = (ports: number[], isOurs: (command: string) => boolean): void => {\n for (const port of ports) {\n for (const { pid, command } of getPortListeners(port)) {\n if (isOurs(command)) {\n console.log(`Killing stale dev server on port ${port} (pid ${pid})`);\n process.kill(pid);\n if (!waitForPidGone(pid)) {\n killPidHard(pid);\n }\n } else {\n console.warn(`Port ${port} is in use by an unrelated process (pid ${pid}: ${command}) — not killing it.`);\n }\n }\n }\n};\n"]}
|
|
1
|
+
{"version":3,"file":"killStaleListeners.js","sourceRoot":"","sources":["../../../src/lib/killStaleListeners.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAShE,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM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C,cAAc,CAAC,GAAG,CAAC,EAAE,CAAC;oBACzB,WAAW,CAAC,GAAG,CAAC,CAAC;gBACnB,CAAC;YACH,CAAC;iBAAM,CAAC;gBACN,GAAG,CAAC,IAAI,CAAC,QAAQ,IAAI,2CAA2C,GAAG,KAAK,OAAO,qBAAqB,CAAC,CAAC;YACxG,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC,CAAC","sourcesContent":["import { runCommandCaptureSync, sleepSync } from './runCommand';\n// Pre-start sweep shared by the dev-server commands: a previous run whose\n// wrapper died without killing its listener (closed terminal, SIGKILL) leaves\n// an orphaned process holding a dev port, and the next launch dies with\n// EADDRINUSE. Before starting, kill any listener on the given ports whose\n// command line matches `isOurs`. Anything else on the ports is left alone\n// and reported, it's not ours.\nimport { Nullable } from '@qpqjs/core';\n\nimport fs from 'fs';\nimport path from 'path';\nimport { createOutput } from './out';\n\nconst out = createOutput('kill-stale-listeners');\n\n// Matches any invocation of the qpq CLI itself, regardless of how it was\n// launched: `node node_modules/.bin/qpq ...` (the npm-script shim, which has\n// no .js extension), a direct `node .../lib/commonjs/bin/qpq.js` call, a\n// global `qpq` shebang script, etc. Checks each whitespace-separated token's\n// basename (extension stripped) rather than a fixed substring like\n// 'bin/qpq.js', which only matches the last of those forms.\nexport const isQpqCliCommand = (command: string): boolean =>\n command\n .trim()\n .split(/\\s+/)\n .some((token) => {\n const base = path.basename(token);\n const withoutExt = base.endsWith('.js') ? base.slice(0, -3) : base;\n return withoutExt === 'qpq';\n });\n\n// SIGTERM only requests termination, the caller (about to bind this same\n// process's ports itself) needs it actually gone first. A stale dev server\n// can be mid-startup when killed (still resolving config, not yet bound to\n// every port it eventually binds) and keep running for a bit past the\n// signal, going on to bind a LATER port, waiting for just the one port that\n// matched isn't enough; wait for the whole pid to disappear so it can't bind\n// anything else afterward. Poll synchronously (this whole sweep runs before\n// anything async starts) via `kill(pid, 0)`, reliable and fast here because\n// these are unrelated processes orphaned earlier, not children of this\n// one (a real child can sit as a zombie answering `kill(pid, 0)` until this\n// process's own event loop reaps it, which a tight sync loop would starve;\n// doesn't apply to a process we didn't spawn).\n//\n// The default covers the dev server's graceful shutdown (drain in-flight work,\n// then checkpoint the stores) with room to spare. Returns whether the pid\n// actually went, because a caller about to bind these ports has to escalate\n// rather than hope: giving up while the old server still holds 8080 is exactly\n// the EADDRINUSE this file exists to prevent.\nconst waitForPidGone = (pid: number, timeoutMs = 8000): boolean => {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n try {\n process.kill(pid, 0);\n } catch {\n return true; // throws once the pid no longer exists\n }\n sleepSync(50);\n }\n\n return false;\n};\n\n// Last resort for a process that ignored, or wedged during, its graceful stop.\nconst killPidHard = (pid: number): void => {\n out.warn(`Process ${pid} did not exit gracefully — sending SIGKILL.`);\n try {\n process.kill(pid, 'SIGKILL');\n } catch {\n return; // raced us and exited after all\n }\n waitForPidGone(pid, 2000);\n};\n\n// realpath'd: lsof reports the canonical path (e.g. /private/tmp on macOS,\n// where /tmp is a symlink), so comparing against a caller-supplied root\n// verbatim would false-negative whenever any component of the repo path is\n// itself a symlink (a symlinked home directory, an NFS mount, etc).\nconst getProcessCwd = (pid: number): Nullable<string> => {\n try {\n const line = runCommandCaptureSync('lsof', ['-a', '-p', String(pid), '-d', 'cwd', '-Fn'])\n .split('\\n')\n .find((l) => l.startsWith('n'));\n return line ? fs.realpathSync(line.slice(1)) : null;\n } catch {\n return null; // pid gone, or we don't have permission to inspect it\n }\n};\n\n// The sweep below must never target this process's own wrappers: launched as\n// `npx qpq go:dev:api` (or via any shell whose -c string names qpq), the\n// ancestor chain (`sh -c \"npx ... qpq ...\"`, `npm exec qpq ...`) matches\n// isQpqCliCommand and shares our cwd, so excluding just process.pid isn't\n// enough, SIGINTing an ancestor tears down our own tree. Walk ppid to the\n// top and exclude the whole chain.\nconst getOwnAncestorPids = (): Set<number> => {\n const ancestors = new Set<number>();\n let pid = process.pid;\n while (pid > 1 && !ancestors.has(pid)) {\n ancestors.add(pid);\n try {\n pid = Number(runCommandCaptureSync('ps', ['-o', 'ppid=', '-p', String(pid)]).trim());\n } catch {\n break;\n }\n }\n return ancestors;\n};\n\n// killStaleListeners only sees processes currently BOUND to one of the given\n// ports, it can't catch a still-running `qpq go:dev*` watcher whose spawned\n// dev-server child already died (a crash, or us killing just the child):\n// the watcher itself holds no port at that moment, so it's invisible to a\n// port scan, yet it's still alive and can spawn a fresh child, and bind a\n// port, moments later, racing whatever we're about to start. Close that gap\n// by finding any OTHER qpq CLI process rooted in the same repo checkout\n// (matched by cwd, not by port or command-line args, which vary by how it\n// was invoked) and killing it outright, regardless of what it currently has\n// bound. SIGINT (not SIGTERM) so goDevApiCommand/goDevWebCommand's own\n// handler runs and tears down its child cleanly rather than orphaning it.\nexport const killOtherQpqDevProcesses = (root: string): void => {\n const resolvedRoot = fs.realpathSync(root);\n const ownPids = getOwnAncestorPids();\n\n let lines: string[] = [];\n try {\n lines = runCommandCaptureSync('ps', ['-axo', 'pid=,command=']).split('\\n');\n } catch {\n return;\n }\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n\n const spaceIndex = trimmed.indexOf(' ');\n if (spaceIndex === -1) continue;\n\n const pid = Number(trimmed.slice(0, spaceIndex));\n const command = trimmed.slice(spaceIndex + 1).trim();\n\n if (!pid || ownPids.has(pid) || !isQpqCliCommand(command)) continue;\n if (getProcessCwd(pid) !== resolvedRoot) continue;\n\n out.log(`Killing other qpq dev process for this repo (pid ${pid}): ${command}`);\n process.kill(pid, 'SIGINT');\n if (!waitForPidGone(pid)) {\n killPidHard(pid);\n }\n }\n};\n\n// Whatever is currently listening on a port, as pid + command line. Empty when\n// the port is free, or when lsof is unavailable.\nconst getPortListeners = (port: number): { pid: number; command: string }[] => {\n let pids: number[] = [];\n try {\n pids = runCommandCaptureSync('lsof', ['-t', `-iTCP:${port}`, '-sTCP:LISTEN'])\n .split('\\n')\n .map((line) => Number(line.trim()))\n .filter(Boolean);\n } catch {\n return []; // lsof exits non-zero when nothing is listening\n }\n\n return pids.flatMap((pid) => {\n try {\n return [{ pid, command: runCommandCaptureSync('ps', ['-p', String(pid), '-o', 'command=']).trim() }];\n } catch {\n return []; // already gone\n }\n });\n};\n\n/**\n * Say what is holding these ports, without touching it.\n *\n * The other half of --keep-other-dev-servers: sparing a sibling checkout's dev\n * server means this one cannot bind, and an unexplained EADDRINUSE is a worse\n * experience than the silent kill it replaces. Naming the pid and the command\n * turns \"it just died\" into something you can act on.\n *\n * Worded as a prediction, not a fact, because it IS one: this runs before the\n * bundle step, so by the time anything binds - seconds later - the holder may\n * well have gone. Stating \"port in use\" and then starting cleanly reads like\n * the warning was wrong.\n */\nexport const reportPortHolders = (ports: number[]): void => {\n for (const port of ports) {\n for (const { pid, command } of getPortListeners(port)) {\n out.warn(`Port ${port} is currently held by pid ${pid}: ${command}`);\n out.warn(` Starting anyway. If it still holds port ${port} once this server binds, startup will fail with EADDRINUSE.`);\n }\n }\n};\n\nexport const killStaleListeners = (ports: number[], isOurs: (command: string) => boolean): void => {\n for (const port of ports) {\n for (const { pid, command } of getPortListeners(port)) {\n if (isOurs(command)) {\n out.log(`Killing stale dev server on port ${port} (pid ${pid})`);\n process.kill(pid);\n if (!waitForPidGone(pid)) {\n killPidHard(pid);\n }\n } else {\n out.warn(`Port ${port} is in use by an unrelated process (pid ${pid}: ${command}) — not killing it.`);\n }\n }\n }\n};\n"]}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
type Print = (...parts: unknown[]) => void;
|
|
2
|
+
export type Output = {
|
|
3
|
+
log: Print;
|
|
4
|
+
info: Print;
|
|
5
|
+
warn: Print;
|
|
6
|
+
error: Print;
|
|
7
|
+
time: (label: string) => void;
|
|
8
|
+
timeEnd: (label: string) => void;
|
|
9
|
+
};
|
|
10
|
+
export declare const createOutput: (area: string) => Output;
|
|
11
|
+
export {};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// Every line the cli prints carries `[qpq:<area>]`, so output from the concurrent and nested
|
|
2
|
+
// commands reads as one program. This is the only place the cli touches the console.
|
|
3
|
+
export const createOutput = (area) => {
|
|
4
|
+
const prefix = `[qpq:${area}]`;
|
|
5
|
+
// A leading string is joined onto the prefix; anything else (an error, an object) is printed
|
|
6
|
+
// after it as its own argument so the console keeps formatting it. The console method is
|
|
7
|
+
// looked up per call, not captured, so a test can spy on it after this module loads.
|
|
8
|
+
const withPrefix = (method) => {
|
|
9
|
+
return (...parts) => {
|
|
10
|
+
const [first, ...rest] = parts;
|
|
11
|
+
if (typeof first === 'string') {
|
|
12
|
+
return console[method](`${prefix} ${first}`, ...rest);
|
|
13
|
+
}
|
|
14
|
+
return console[method](prefix, ...parts);
|
|
15
|
+
};
|
|
16
|
+
};
|
|
17
|
+
return {
|
|
18
|
+
log: withPrefix('log'),
|
|
19
|
+
info: withPrefix('info'),
|
|
20
|
+
warn: withPrefix('warn'),
|
|
21
|
+
error: withPrefix('error'),
|
|
22
|
+
time: (label) => console.time(`${prefix} ${label}`),
|
|
23
|
+
timeEnd: (label) => console.timeEnd(`${prefix} ${label}`),
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
//# sourceMappingURL=out.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"out.js","sourceRoot":"","sources":["../../../src/lib/out.ts"],"names":[],"mappings":"AAaA,6FAA6F;AAC7F,qFAAqF;AACrF,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,IAAY,EAAU,EAAE;IACnD,MAAM,MAAM,GAAG,QAAQ,IAAI,GAAG,CAAC;IAE/B,6FAA6F;IAC7F,yFAAyF;IACzF,qFAAqF;IACrF,MAAM,UAAU,GAAG,CAAC,MAAyC,EAAS,EAAE;QACtE,OAAO,CAAC,GAAG,KAAK,EAAE,EAAE;YAClB,MAAM,CAAC,KAAK,EAAE,GAAG,IAAI,CAAC,GAAG,KAAK,CAAC;YAE/B,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;gBAC9B,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC,GAAG,MAAM,IAAI,KAAK,EAAE,EAAE,GAAG,IAAI,CAAC,CAAC;YACxD,CAAC;YAED,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,GAAG,KAAK,CAAC,CAAC;QAC3C,CAAC,CAAC;IACJ,CAAC,CAAC;IAEF,OAAO;QACL,GAAG,EAAE,UAAU,CAAC,KAAK,CAAC;QACtB,IAAI,EAAE,UAAU,CAAC,MAAM,CAAC;QACxB,IAAI,EAAE,UAAU,CAAC,MAAM,CAAC;QACxB,KAAK,EAAE,UAAU,CAAC,OAAO,CAAC;QAC1B,IAAI,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,MAAM,IAAI,KAAK,EAAE,CAAC;QACnD,OAAO,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,MAAM,IAAI,KAAK,EAAE,CAAC;KAC1D,CAAC;AACJ,CAAC,CAAC","sourcesContent":["/* eslint-disable no-console */\ntype Print = (...parts: unknown[]) => void;\n\nexport type Output = {\n log: Print;\n info: Print;\n warn: Print;\n error: Print;\n // A named stopwatch, printed on end.\n time: (label: string) => void;\n timeEnd: (label: string) => void;\n};\n\n// Every line the cli prints carries `[qpq:<area>]`, so output from the concurrent and nested\n// commands reads as one program. This is the only place the cli touches the console.\nexport const createOutput = (area: string): Output => {\n const prefix = `[qpq:${area}]`;\n\n // A leading string is joined onto the prefix; anything else (an error, an object) is printed\n // after it as its own argument so the console keeps formatting it. The console method is\n // looked up per call, not captured, so a test can spy on it after this module loads.\n const withPrefix = (method: 'log' | 'info' | 'warn' | 'error'): Print => {\n return (...parts) => {\n const [first, ...rest] = parts;\n\n if (typeof first === 'string') {\n return console[method](`${prefix} ${first}`, ...rest);\n }\n\n return console[method](prefix, ...parts);\n };\n };\n\n return {\n log: withPrefix('log'),\n info: withPrefix('info'),\n warn: withPrefix('warn'),\n error: withPrefix('error'),\n time: (label) => console.time(`${prefix} ${label}`),\n timeEnd: (label) => console.timeEnd(`${prefix} ${label}`),\n };\n};\n"]}
|
package/lib/esm/lib/prompts.d.ts
CHANGED
|
@@ -7,6 +7,7 @@ export declare const promptSelectDetailed: <T>(message: string, choices: {
|
|
|
7
7
|
}[]) => Promise<T>;
|
|
8
8
|
export declare const promptYesNo: (message: string) => Promise<boolean>;
|
|
9
9
|
export declare const promptText: (message: string) => Promise<string>;
|
|
10
|
+
export declare const promptTypedConfirmation: (target: string) => Promise<boolean>;
|
|
10
11
|
export declare const promptCheckbox: <T>(message: string, choices: {
|
|
11
12
|
name: string;
|
|
12
13
|
value: T;
|
package/lib/esm/lib/prompts.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { createOutput } from './out';
|
|
2
|
+
const out = createOutput('prompts');
|
|
1
3
|
// Present a single-choice list prompt and return the selected value.
|
|
2
4
|
// @inquirer/prompts is imported lazily so commands only pay for it when
|
|
3
5
|
// actually prompting.
|
|
@@ -14,12 +16,22 @@ export const promptSelectDetailed = async (message, choices) => {
|
|
|
14
16
|
};
|
|
15
17
|
// A yes/no list prompt, returning true for "Yes".
|
|
16
18
|
export const promptYesNo = async (message) => (await promptSelect(message, ['No', 'Yes'])) === 'Yes';
|
|
17
|
-
// A free-text prompt
|
|
19
|
+
// A free-text prompt, used where a y/n is too easy to fat-finger (destructive
|
|
18
20
|
// confirmations that require typing the target name back).
|
|
19
21
|
export const promptText = async (message) => {
|
|
20
22
|
const { input } = await import('@inquirer/prompts');
|
|
21
23
|
return input({ message });
|
|
22
24
|
};
|
|
25
|
+
// The friction for destructive commands: the target has to be typed back exactly. Resolves
|
|
26
|
+
// true when it was; prints why it stops otherwise, so callers only have to bail out.
|
|
27
|
+
export const promptTypedConfirmation = async (target) => {
|
|
28
|
+
const confirmation = await promptText(`Type '${target}' to confirm`);
|
|
29
|
+
if (confirmation !== target) {
|
|
30
|
+
out.log('Confirmation did not match. Exiting!');
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
return true;
|
|
34
|
+
};
|
|
23
35
|
// A multi-select checkbox prompt over labelled values; `checked` preselects a choice.
|
|
24
36
|
export const promptCheckbox = async (message, choices) => {
|
|
25
37
|
const { checkbox } = await import('@inquirer/prompts');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompts.js","sourceRoot":"","sources":["../../../src/lib/prompts.ts"],"names":[],"mappings":"AAAA,qEAAqE;AACrE,wEAAwE;AACxE,sBAAsB;AACtB,MAAM,CAAC,MAAM,YAAY,GAAG,KAAK,EAAE,OAAe,EAAE,OAAiB,EAAE,aAAsB,EAAmB,EAAE;IAChH,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,MAAM,CAAC,mBAAmB,CAAC,CAAC;IACrD,OAAO,MAAM,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,aAAa,EAAE,CAAC,CAAC;AAC9D,CAAC,CAAC;AAEF,wEAAwE;AACxE,6EAA6E;AAC7E,gEAAgE;AAChE,MAAM,CAAC,MAAM,oBAAoB,GAAG,KAAK,EACvC,OAAe,EACf,OAA2E,EAC/D,EAAE;IACd,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,MAAM,CAAC,mBAAmB,CAAC,CAAC;IACrD,OAAO,MAAM,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,CAAC;AACtC,CAAC,CAAC;AAEF,kDAAkD;AAClD,MAAM,CAAC,MAAM,WAAW,GAAG,KAAK,EAAE,OAAe,EAAoB,EAAE,CAAC,CAAC,MAAM,YAAY,CAAC,OAAO,EAAE,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,KAAK,KAAK,CAAC;AAE/H
|
|
1
|
+
{"version":3,"file":"prompts.js","sourceRoot":"","sources":["../../../src/lib/prompts.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,OAAO,CAAC;AAErC,MAAM,GA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AAc,CAAC,CAAC;IAErE,IAAI,YAAY,KAAK,MAAM,EAAE,CAAC;QAC5B,GAAG,CAAC,GAAG,CAAC,sCAAsC,CAAC,CAAC;QAChD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC,CAAC;AAEF,sFAAsF;AACtF,MAAM,CAAC,MAAM,cAAc,GAAG,KAAK,EACjC,OAAe,EACf,OAA8E,EAChE,EAAE;IAChB,MAAM,EAAE,QAAQ,EAAE,GAAG,MAAM,MAAM,CAAC,mBAAmB,CAAC,CAAC;IACvD,OAAO,QAAQ,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,CAAC;AACxC,CAAC,CAAC","sourcesContent":["import { createOutput } from './out';\n\nconst out = createOutput('prompts');\n// Present a single-choice list prompt and return the selected value.\n// @inquirer/prompts is imported lazily so commands only pay for it when\n// actually prompting.\nexport const promptSelect = async (message: string, choices: string[], defaultChoice?: string): Promise<string> => {\n const { select } = await import('@inquirer/prompts');\n return select({ message, choices, default: defaultChoice });\n};\n\n// A single-choice list prompt over labelled values; a choice's optional\n// `short` replaces its name in the answer line once picked, and its optional\n// `description` renders under the list while it is highlighted.\nexport const promptSelectDetailed = async <T>(\n message: string,\n choices: { name: string; value: T; short?: string; description?: string }[],\n): Promise<T> => {\n const { select } = await import('@inquirer/prompts');\n return select({ message, choices });\n};\n\n// A yes/no list prompt, returning true for \"Yes\".\nexport const promptYesNo = async (message: string): Promise<boolean> => (await promptSelect(message, ['No', 'Yes'])) === 'Yes';\n\n// A free-text prompt, used where a y/n is too easy to fat-finger (destructive\n// confirmations that require typing the target name back).\nexport const promptText = async (message: string): Promise<string> => {\n const { input } = await import('@inquirer/prompts');\n return input({ message });\n};\n\n// The friction for destructive commands: the target has to be typed back exactly. Resolves\n// true when it was; prints why it stops otherwise, so callers only have to bail out.\nexport const promptTypedConfirmation = async (target: string): Promise<boolean> => {\n const confirmation = await promptText(`Type '${target}' to confirm`);\n\n if (confirmation !== target) {\n out.log('Confirmation did not match. Exiting!');\n return false;\n }\n\n return true;\n};\n\n// A multi-select checkbox prompt over labelled values; `checked` preselects a choice.\nexport const promptCheckbox = async <T>(\n message: string,\n choices: { name: string; value: T; checked?: boolean; description?: string }[],\n): Promise<T[]> => {\n const { checkbox } = await import('@inquirer/prompts');\n return checkbox({ message, choices });\n};\n"]}
|
|
@@ -6,15 +6,15 @@ import { getRoot, getServiceNames } from './discovery';
|
|
|
6
6
|
// workspace symlinks).
|
|
7
7
|
export const loadServiceQpqConfig = (appName, service) => getWorkspaceServiceQpqConfig(getRoot(), appName, service);
|
|
8
8
|
export const getAppPrefix = (appName) => {
|
|
9
|
-
const
|
|
10
|
-
if (
|
|
9
|
+
const [firstService] = getServiceNames(appName);
|
|
10
|
+
if (firstService === undefined)
|
|
11
11
|
throw new Error(`No services found for app ${appName}`);
|
|
12
|
-
return qpqCoreUtils.getApplicationName(loadServiceQpqConfig(appName,
|
|
12
|
+
return qpqCoreUtils.getApplicationName(loadServiceQpqConfig(appName, firstService));
|
|
13
13
|
};
|
|
14
14
|
// The subset of the given services that opt into module-federation publishing,
|
|
15
15
|
// i.e. declare defineFederatedModuleStore(...). Federation is a config setting,
|
|
16
16
|
// not a directory convention (unlike views/ backends), so detecting it means
|
|
17
|
-
// loading each service's config
|
|
17
|
+
// loading each service's config, which is why this lives here and not in the
|
|
18
18
|
// directory-only discovery module. Used by the deploy drivers to decide which
|
|
19
19
|
// backends to publish federated remotes for after a deploy.
|
|
20
20
|
export const getServiceNamesWithFederation = (appName, serviceNames) => serviceNames.filter((service) => !!qpqCoreUtils.getFederatedModuleStore(loadServiceQpqConfig(appName, service)));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"qpqConfigs.js","sourceRoot":"","sources":["../../../src/lib/qpqConfigs.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3D,OAAO,EAAE,4BAA4B,EAAE,MAAM,mBAA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AG,CAAC,OAAe,EAAE,YAAsB,EAAY,EAAE,CACjG,YAAY,CAAC,MAAM,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC,YAAY,CAAC,uBAAuB,CAAC,oBAAoB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC","sourcesContent":["import { type QPQConfig, qpqCoreUtils } from '@qpqjs/core';\nimport { getWorkspaceServiceQpqConfig } from '@qpqjs/deploy-aws';\n\nimport { getRoot, getServiceNames } from './discovery';\n\n// Loads a service's live infrastructure.ts (qpq runs with ts-node hooks\n// registered, so requiring TS works and `@scope/*` imports resolve through\n// workspace symlinks).\nexport const loadServiceQpqConfig = (appName: string, service: string): QPQConfig => getWorkspaceServiceQpqConfig(getRoot(), appName, service);\n\nexport const getAppPrefix = (appName: string): string => {\n const [firstService] = getServiceNames(appName);\n if (firstService === undefined) throw new Error(`No services found for app ${appName}`);\n return qpqCoreUtils.getApplicationName(loadServiceQpqConfig(appName, firstService));\n};\n\n// The subset of the given services that opt into module-federation publishing,\n// i.e. declare defineFederatedModuleStore(...). Federation is a config setting,\n// not a directory convention (unlike views/ backends), so detecting it means\n// loading each service's config, which is why this lives here and not in the\n// directory-only discovery module. Used by the deploy drivers to decide which\n// backends to publish federated remotes for after a deploy.\nexport const getServiceNamesWithFederation = (appName: string, serviceNames: string[]): string[] =>\n serviceNames.filter((service) => !!qpqCoreUtils.getFederatedModuleStore(loadServiceQpqConfig(appName, service)));\n"]}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { QpqPlatformDriver } from '../platforms';
|
|
2
|
+
import { CommandContext } from './resolveCommandContext';
|
|
3
|
+
type OptionalCapability = {
|
|
4
|
+
[K in keyof QpqPlatformDriver]-?: undefined extends QpqPlatformDriver[K] ? K : never;
|
|
5
|
+
}[keyof QpqPlatformDriver];
|
|
6
|
+
export declare const requireDriverCapability: <K extends OptionalCapability>(context: CommandContext, capability: K, hint?: string) => NonNullable<QpqPlatformDriver[K]>;
|
|
7
|
+
export {};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { CliError } from './CliError';
|
|
2
|
+
import { createOutput } from './out';
|
|
3
|
+
const out = createOutput('require-driver-capability');
|
|
4
|
+
// Hands back a driver's optional capability, or stops the command with a message naming the
|
|
5
|
+
// platform that lacks it. The capability name doubles as the strategy name in that message.
|
|
6
|
+
export const requireDriverCapability = (context, capability, hint = '') => {
|
|
7
|
+
const implementation = context.driver[capability];
|
|
8
|
+
if (!implementation) {
|
|
9
|
+
throw new CliError(`The '${context.deployment.platform}' platform has no ${capability} strategy.${hint ? ` ${hint}` : ''}`);
|
|
10
|
+
}
|
|
11
|
+
return implementation;
|
|
12
|
+
};
|
|
13
|
+
//# sourceMappingURL=requireDriverCapability.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"requireDriverCapability.js","sourceRoot":"","sources":["../../../src/lib/requireDriverCapability.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,YAAY,EAAE,MAAM,OAAO,CAAC;AAErC,MAAM,GAAG,GAAG,YAAY,CAAC,2BAA2B,CAAC,CAAC;AAMtD,4FAA4F;AAC5F,4FAA4F;AAC5F,MAAM,CAAC,MAAM,uBAAuB,GAAG,CACrC,OAAuB,EACvB,UAAa,EACb,OAAe,EAAE,EACkB,EAAE;IACrC,MAAM,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;IAElD,IAAI,CAAC,cAAc,EAAE,CAAC;QACpB,MAAM,IAAI,QAAQ,CAAC,QAAQ,OAAO,CAAC,UAAU,CAAC,QAAQ,qBAAqB,UAAU,aAAa,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;IAC9H,CAAC;IAED,OAAO,cAAmD,CAAC;AAC7D,CAAC,CAAC","sourcesContent":["import { QpqPlatformDriver } from '../platforms';\nimport { CommandContext } from './resolveCommandContext';\nimport { CliError } from './CliError';\nimport { createOutput } from './out';\n\nconst out = createOutput('require-driver-capability');\n\ntype OptionalCapability = {\n [K in keyof QpqPlatformDriver]-?: undefined extends QpqPlatformDriver[K] ? K : never;\n}[keyof QpqPlatformDriver];\n\n// Hands back a driver's optional capability, or stops the command with a message naming the\n// platform that lacks it. The capability name doubles as the strategy name in that message.\nexport const requireDriverCapability = <K extends OptionalCapability>(\n context: CommandContext,\n capability: K,\n hint: string = '',\n): NonNullable<QpqPlatformDriver[K]> => {\n const implementation = context.driver[capability];\n\n if (!implementation) {\n throw new CliError(`The '${context.deployment.platform}' platform has no ${capability} strategy.${hint ? ` ${hint}` : ''}`);\n }\n\n return implementation as NonNullable<QpqPlatformDriver[K]>;\n};\n"]}
|