@w5s/managed-script 1.0.0-alpha.4 → 1.0.0-alpha.5

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 (43) hide show
  1. package/README.md +37 -0
  2. package/dist/ManagedScript-B8d632d3.js +321 -0
  3. package/dist/ManagedScript-B8d632d3.js.map +1 -0
  4. package/dist/cli.js +27 -43
  5. package/dist/cli.js.map +1 -1
  6. package/dist/{defaultContext-BthxLDX3.js → defaultContext-Xl2iA7UM.js} +38 -9
  7. package/dist/defaultContext-Xl2iA7UM.js.map +1 -0
  8. package/dist/index.d.ts +27 -54
  9. package/dist/index.js +23 -8
  10. package/dist/index.js.map +1 -1
  11. package/dist/type-hvsy_R0f.d.ts +103 -0
  12. package/dist/zx.d.ts +45 -14
  13. package/dist/zx.js +47 -17
  14. package/dist/zx.js.map +1 -1
  15. package/package.json +3 -2
  16. package/src/ManagedScript/defaultContext.ts +2 -4
  17. package/src/ManagedScript/execute.ts +45 -24
  18. package/src/ManagedScript/resolveScripts.ts +52 -5
  19. package/src/cli/RootCommand.ts +2 -3
  20. package/src/internal/Executor.ts +27 -10
  21. package/src/internal/Logger.ts +10 -3
  22. package/src/internal/PackageScriptOverride.ts +43 -0
  23. package/src/internal/ScriptInvocation.ts +55 -0
  24. package/src/internal/ScriptNameResolver.ts +5 -4
  25. package/src/internal/Stdio.ts +41 -0
  26. package/src/internal/lazy.ts +7 -0
  27. package/src/mergeConfig.ts +28 -0
  28. package/src/type/CommandContext.ts +6 -7
  29. package/src/type/ResolvedConfig.ts +27 -8
  30. package/src/type/StdOptions.ts +1 -0
  31. package/src/type/UserConfig.ts +38 -1
  32. package/src/type.ts +1 -0
  33. package/src/zx/ZXOptions.ts +73 -1
  34. package/src/zx/ZXShell.ts +18 -1
  35. package/src/zx/defaults.ts +6 -0
  36. package/src/zx/isCI.ts +26 -0
  37. package/src/zx/zx.ts +7 -13
  38. package/src/zx.ts +2 -0
  39. package/dist/ManagedScript-CLp9a43o.js +0 -193
  40. package/dist/ManagedScript-CLp9a43o.js.map +0 -1
  41. package/dist/defaultContext-BthxLDX3.js.map +0 -1
  42. package/dist/type-DQiyX1q_.d.ts +0 -53
  43. package/src/zx/defaultZXOptions.ts +0 -58
package/src/type.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from './type/Command.js';
2
2
  export * from './type/CommandContext.js';
3
3
  export * from './type/ResolvedConfig.js';
4
+ export * from './type/StdOptions.js';
4
5
  export * from './type/UserConfig.js';
@@ -1 +1,73 @@
1
- export type { Options as ZXOptions } from 'zx';
1
+ import { stripVTControlCharacters } from 'node:util';
2
+ import { chalk, log as zxLog } from 'zx';
3
+
4
+ import type { LogLevel } from '../internal/Logger.js';
5
+ import type { ZXDefaultOptions } from '../zx.js';
6
+
7
+ import { Stdio } from '../internal/Stdio.js';
8
+ import { defaultContext } from '../ManagedScript/defaultContext.js';
9
+
10
+ export type { Options as ZXDefaultOptions } from 'zx';
11
+
12
+ export interface ZXOptions extends ZXDefaultOptions {
13
+ /**
14
+ *
15
+ */
16
+ logLevel?: LogLevel | undefined;
17
+ }
18
+
19
+ /**
20
+ * @namespace
21
+ */
22
+ export const ZXOptions = {
23
+ create(options: Partial<ZXOptions>): Partial<ZXOptions> {
24
+ const { cwd: optionsCwd, env: optionsEnv, logLevel: optionsLogLevel, stdio: optionsStdio, ...optionsRest } = options;
25
+ const env = optionsEnv == null ? process.env : { ...process.env, ...optionsEnv };
26
+ const context = defaultContext({
27
+ env,
28
+ ...(optionsCwd == null ? {} : { cwd: optionsCwd }),
29
+ ...(optionsLogLevel == null ? {} : { logLevel: optionsLogLevel }),
30
+ ...(optionsStdio == null ? {} : { stdio: optionsStdio }),
31
+ });
32
+ const { stderr, stdout } = Stdio.resolve(context.stdio);
33
+
34
+ return {
35
+ cwd: context.cwd,
36
+ env: context.env,
37
+ log: (entry) => {
38
+ const target = (entry.kind === 'cmd' || entry.kind === 'stdout' ? stdout : stderr) as NodeJS.WriteStream;
39
+ const colorEnabled = context.color === 'always' || (context.color === 'auto' && autoColor(context.env, target));
40
+ const previousOutput = zxLog.output;
41
+ const previousLevel = chalk.level;
42
+ zxLog.output = colorEnabled
43
+ ? target
44
+ : ({ write: (chunk: string) => target.write(stripVTControlCharacters(chunk)) } as unknown as NodeJS.WriteStream);
45
+ if (colorEnabled && !chalk.level) {
46
+ chalk.level = 1;
47
+ } else if (!colorEnabled) {
48
+ chalk.level = 0;
49
+ }
50
+ try {
51
+ zxLog(entry.kind === 'cmd' && (context.logLevel === 'info' || context.logLevel === 'debug') ? { ...entry, verbose: true } : entry);
52
+ } finally {
53
+ // eslint-disable-next-line ts/no-non-null-assertion
54
+ zxLog.output = previousOutput!;
55
+ chalk.level = previousLevel;
56
+ }
57
+ },
58
+ preferLocal: true,
59
+ quiet: context.logLevel === 'silent',
60
+ stdio: 'inherit',
61
+ verbose: context.logLevel === 'debug',
62
+ ...optionsRest,
63
+ };
64
+ },
65
+ };
66
+
67
+ function autoColor(env: NodeJS.ProcessEnv, stream: NodeJS.WriteStream): boolean {
68
+ if (env['NO_COLOR'] != null && env['NO_COLOR'] !== '') {
69
+ return false;
70
+ }
71
+ const force = env['FORCE_COLOR'];
72
+ return force == null ? stream.isTTY === true : force !== '0' && force !== 'false';
73
+ }
package/src/zx/ZXShell.ts CHANGED
@@ -1 +1,18 @@
1
- export type { Shell as ZXShell } from 'zx';
1
+ /* eslint-disable ts/no-shadow */
2
+ import type { ProcessOutput, ProcessPromise } from 'zx';
3
+
4
+ import type { ZXOptions } from './ZXOptions.js';
5
+
6
+ /**
7
+ * Shell interface with some extensions
8
+ */
9
+ export interface ZXShell<S = false, R = S extends true ? ProcessOutput : ProcessPromise> {
10
+ (pieces: TemplateStringsArray, ...args: Array<any>): R;
11
+ <O extends Partial<ZXOptions> = Partial<ZXOptions>, R = O extends {
12
+ sync: true;
13
+ } ? ZXShell<true> : ZXShell>(opts: O): R;
14
+ sync: {
15
+ (pieces: TemplateStringsArray, ...args: Array<any>): ProcessOutput;
16
+ (opts: Partial<Omit<ZXOptions, 'sync'>>): ZXShell<true>;
17
+ };
18
+ }
@@ -0,0 +1,6 @@
1
+ import { ZXOptions } from './ZXOptions.js';
2
+
3
+ /**
4
+ * Default ZX options for the managed script environment.
5
+ */
6
+ export const defaults = ZXOptions.create({});
package/src/zx/isCI.ts ADDED
@@ -0,0 +1,26 @@
1
+ import { bool, cleanEnv } from 'envalid';
2
+
3
+ import { lazy } from '../internal/lazy.js';
4
+
5
+ const envSchema = {
6
+ CI: bool({ default: false }),
7
+ CONTINUOUS_INTEGRATION: bool({ default: false }),
8
+ };
9
+
10
+ const getEnvClean = lazy(() =>
11
+ cleanEnv(process.env, envSchema, {
12
+ reporter: null,
13
+ }),
14
+ );
15
+
16
+ /**
17
+ * Determines if the current environment is a CI (Continuous Integration) environment.
18
+ * Checks the `CI` and `CONTINUOUS_INTEGRATION` environment variables to determine if the current environment is a CI environment.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * const ci = isCI();
23
+ * ```
24
+ * @returns `true` if the current environment is a CI environment, otherwise `false`
25
+ */
26
+ export const isCI = lazy(() => getEnvClean().CI || getEnvClean().CONTINUOUS_INTEGRATION);
package/src/zx/zx.ts CHANGED
@@ -1,9 +1,9 @@
1
- import { $ as zxDefault } from 'zx';
1
+ import { $ as zxFn } from 'zx';
2
2
 
3
- import type { CommandContext } from '../type.js';
3
+ import type { CommandContext, StdioOptions } from '../type.js';
4
4
  import type { ZXShell } from './ZXShell.js';
5
5
 
6
- import { defaultZXOptions } from './defaultZXOptions.js';
6
+ import { ZXOptions } from './ZXOptions.js';
7
7
 
8
8
  export interface CreateZXOptions {
9
9
  /**
@@ -23,14 +23,9 @@ export interface CreateZXOptions {
23
23
  readonly logLevel?: CommandContext['logLevel'] | undefined;
24
24
 
25
25
  /**
26
- * Stream used to write instrumented command logs at the error and warn levels.
26
+ * Standard I/O used to write instrumented command logs (index `1` for command lines and output, index `2` for the rest).
27
27
  */
28
- readonly stderr?: NodeJS.WritableStream | undefined;
29
-
30
- /**
31
- * Stream used to write instrumented command logs at the info and debug levels.
32
- */
33
- readonly stdout?: NodeJS.WritableStream | undefined;
28
+ readonly stdio?: StdioOptions | undefined;
34
29
  }
35
30
 
36
31
  /**
@@ -41,11 +36,10 @@ export interface CreateZXOptions {
41
36
  export function zx(options: CreateZXOptions = {}): ZXShell {
42
37
  const env = options.env == null ? process.env : { ...process.env, ...options.env };
43
38
 
44
- return zxDefault(defaultZXOptions({
39
+ return zxFn(ZXOptions.create({
45
40
  env,
46
41
  ...(options.cwd == null ? {} : { cwd: options.cwd }),
47
42
  ...(options.logLevel == null ? {} : { logLevel: options.logLevel }),
48
- ...(options.stderr == null ? {} : { stderr: options.stderr }),
49
- ...(options.stdout == null ? {} : { stdout: options.stdout }),
43
+ ...(options.stdio == null ? {} : { stdio: options.stdio }),
50
44
  }));
51
45
  }
package/src/zx.ts CHANGED
@@ -2,6 +2,8 @@ import type { ZXShell } from './zx/ZXShell.js';
2
2
 
3
3
  import { zx } from './zx/zx.js';
4
4
 
5
+ export * from './zx/defaults.js';
6
+ export * from './zx/isCI.js';
5
7
  export * from './zx/zx.js';
6
8
  export type * from './zx/ZXOptions.js';
7
9
  export type * from './zx/ZXShell.js';
@@ -1,193 +0,0 @@
1
- import { n as ManagedScriptEnv, t as defaultContext } from "./defaultContext-BthxLDX3.js";
2
- import { loadConfig } from "c12";
3
- import path from "node:path";
4
- import { spawn } from "node:child_process";
5
- import path$1 from "node:path/win32";
6
- //#region src/meta.ts
7
- const meta = Object.freeze({
8
- binaryLabel: "W5S Managed Script",
9
- binaryName: "managed-script",
10
- binaryVersion: "1.0.0-alpha.4",
11
- buildNumber: 1,
12
- name: "@w5s/managed-script",
13
- version: "1.0.0-alpha.4"
14
- });
15
- //#endregion
16
- //#region src/internal/ConfigLoader.ts
17
- const ConfigLoader = { async load(options) {
18
- const result = await loadConfig({
19
- cwd: options.cwd,
20
- name: meta.binaryName,
21
- packageJson: [meta.binaryName]
22
- });
23
- return {
24
- config: result.config,
25
- configFile: result.configFile ?? void 0,
26
- layers: result.layers ?? []
27
- };
28
- } };
29
- //#endregion
30
- //#region src/internal/Executor.ts
31
- /**
32
- * Executes a command via the system shell, inheriting stdio and forwarding its exit code.
33
- */
34
- const Executor = { async run(command, options = {}) {
35
- return new Promise((resolve, reject) => {
36
- const child = spawn(command, {
37
- cwd: options.cwd,
38
- env: options.env == null ? process.env : {
39
- ...process.env,
40
- ...options.env
41
- },
42
- shell: true,
43
- stdio: "inherit"
44
- });
45
- child.on("error", reject);
46
- child.on("close", (code, signal) => {
47
- resolve(code ?? (signal == null ? 1 : 128));
48
- });
49
- });
50
- } };
51
- //#endregion
52
- //#region src/internal/Logger.ts
53
- /**
54
- * Rank order used to compare log levels, higher means more verbose.
55
- */
56
- const logLevelRank = {
57
- debug: 4,
58
- error: 1,
59
- info: 3,
60
- silent: 0,
61
- warn: 2
62
- };
63
- /**
64
- * Creates a logger writing to `stream`, filtering out messages above the configured `level`.
65
- */
66
- const Logger = { create({ color = "auto", level, name = meta.binaryName, stderr }) {
67
- const write = (messageLevel, message) => {
68
- if (!(logLevelRank[messageLevel] <= logLevelRank[level])) return;
69
- const outputStream = stderr;
70
- const shouldColor = color === "always" || color === "auto" && "isTTY" in outputStream && outputStream.isTTY === true;
71
- const colorCode = {
72
- debug: "\x1B[36m",
73
- error: "\x1B[31m",
74
- info: "",
75
- silent: "",
76
- warn: "\x1B[33m"
77
- }[messageLevel];
78
- const label = {
79
- debug: "debug",
80
- error: "error",
81
- info: "",
82
- silent: "",
83
- warn: "warning"
84
- }[messageLevel];
85
- const coloredLabel = shouldColor && colorCode !== "" ? `${colorCode}${label}\u{1B}[0m` : label;
86
- const prefix = label === "" ? `${name}: ` : `${name}: ${coloredLabel}: `;
87
- outputStream.write(`${prefix}${message}\n`);
88
- };
89
- return {
90
- debug: (message) => write("debug", message),
91
- error: (message) => write("error", message),
92
- info: (message) => write("info", message),
93
- warn: (message) => write("warn", message)
94
- };
95
- } };
96
- //#endregion
97
- //#region src/internal/ScriptNameResolver.ts
98
- /**
99
- * Resolves the script name to run.
100
- *
101
- * Priority: first positional CLI argument > `MANAGED_SCRIPT_NAME` env var > `npm_lifecycle_event` env var.
102
- */
103
- const ScriptNameResolver = { resolve({ env, scriptName }) {
104
- return scriptName ?? env[ManagedScriptEnv.Name] ?? env["npm_lifecycle_event"];
105
- } };
106
- //#endregion
107
- //#region src/ManagedScript/resolveScripts.ts
108
- function resolveScripts(loaded) {
109
- const scripts = {};
110
- const layers = loaded.layers.length > 0 ? loaded.layers : [{ config: loaded.config }];
111
- for (const layer of layers) for (const [name, command] of Object.entries(layer.config?.scripts ?? {})) {
112
- const configFile = layer.configFile ?? loaded.configFile;
113
- const configDir = configFile == null ? void 0 : path$1.dirname(configFile);
114
- scripts[name] ??= {
115
- command,
116
- configDir,
117
- configFile
118
- };
119
- }
120
- return { scripts };
121
- }
122
- //#endregion
123
- //#region src/ManagedScript/execute.ts
124
- const handlers = { RunScript: async (command) => {
125
- const { context: { color, cwd, dryRun, env, logLevel, stderr, stdout }, parameters: { scriptArgs = [], scriptName } } = command;
126
- const logger = Logger.create({
127
- color,
128
- level: logLevel,
129
- stderr,
130
- stdout
131
- });
132
- const loaded = await ConfigLoader.load({ cwd });
133
- logger.debug(`Resolved configuration from ${loaded.configFile ?? "defaults (no config file found)"}`);
134
- const { scripts } = resolveScripts(loaded);
135
- const name = ScriptNameResolver.resolve({
136
- env,
137
- scriptName
138
- });
139
- if (name == null) throw new Error("Unable to resolve the script name. Pass it as the first argument, set the MANAGED_SCRIPT_NAME environment variable, or run through an npm/pnpm script (npm_lifecycle_event).");
140
- const script = scripts[name];
141
- if (script == null) {
142
- const available = Object.keys(scripts);
143
- throw new Error(`No script named "${name}" found in the configuration.${available.length > 0 ? ` Available scripts: ${available.join(", ")}.` : " No scripts are configured."}`);
144
- }
145
- const commandLine = [script.command, ...scriptArgs.map((argument) => `'${argument.replaceAll("'", String.raw`'\''`)}'`)].join(" ");
146
- logger.debug(`Script found in configuration: ${path.relative(cwd, script.configFile)}`);
147
- stdout.write(`$ ${commandLine}\n`);
148
- if (dryRun) return 0;
149
- const scriptEnv = {
150
- [ManagedScriptEnv.Color]: color,
151
- [ManagedScriptEnv.ConfigDir]: script.configDir,
152
- [ManagedScriptEnv.ConfigFile]: script.configFile,
153
- [ManagedScriptEnv.Cwd]: cwd,
154
- [ManagedScriptEnv.LogLevel]: logLevel,
155
- [ManagedScriptEnv.Name]: name
156
- };
157
- const exitCode = await Executor.run(commandLine, {
158
- cwd,
159
- env: scriptEnv
160
- });
161
- if (exitCode !== 0) throw new Error(`Script "${name}" exited with code ${exitCode}.`);
162
- return exitCode;
163
- } };
164
- /**
165
- * Dispatch the command to the appropriate handler based on its type.
166
- *
167
- * @param command
168
- */
169
- async function execute(command) {
170
- const context = defaultContext(command.context);
171
- return handlers[command._]({
172
- ...command,
173
- context
174
- });
175
- }
176
- //#endregion
177
- //#region src/ManagedScript/runScript.ts
178
- async function runScript(options) {
179
- return execute({
180
- _: "RunScript",
181
- ...options
182
- });
183
- }
184
- //#endregion
185
- //#region src/ManagedScript.ts
186
- /**
187
- * @namespace
188
- */
189
- const ManagedScript = Object.freeze({ runScript });
190
- //#endregion
191
- export { meta as n, ManagedScript as t };
192
-
193
- //# sourceMappingURL=ManagedScript-CLp9a43o.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ManagedScript-CLp9a43o.js","names":["path"],"sources":["../src/meta.ts","../src/internal/ConfigLoader.ts","../src/internal/Executor.ts","../src/internal/Logger.ts","../src/internal/ScriptNameResolver.ts","../src/ManagedScript/resolveScripts.ts","../src/ManagedScript/execute.ts","../src/ManagedScript/runScript.ts","../src/ManagedScript.ts"],"sourcesContent":["export const meta = Object.freeze({\n binaryLabel: 'W5S Managed Script',\n binaryName: 'managed-script',\n // @ts-ignore - these variables are injected at build time\n binaryVersion: (typeof __PACKAGE_VERSION__ === 'undefined' ? '' : __PACKAGE_VERSION__) as string,\n // @ts-ignore - these variables are injected at build time\n buildNumber: 1, // (typeof __PACKAGE_BUILD_NUMBER__ === 'undefined' ? 0 : __PACKAGE_BUILD_NUMBER__) as number,\n // @ts-ignore - these variables are injected at build time\n name: (typeof __PACKAGE_NAME__ === 'undefined' ? '' : __PACKAGE_NAME__) as string,\n // @ts-ignore - these variables are injected at build time\n version: (typeof __PACKAGE_VERSION__ === 'undefined' ? '' : __PACKAGE_VERSION__) as string,\n});\n","import type { ConfigLayer } from 'c12';\n\nimport { loadConfig } from 'c12';\n\nimport type { UserConfig } from '../type/UserConfig.js';\n\nimport { meta } from '../meta.js';\n\nexport interface ConfigLoaderOptions {\n readonly cwd: string;\n}\n\nexport interface ConfigLoaderResult {\n readonly config: UserConfig;\n readonly configFile: string | undefined;\n readonly layers: Array<ConfigLayer<UserConfig>>;\n}\n\nexport const ConfigLoader = {\n async load(options: ConfigLoaderOptions): Promise<ConfigLoaderResult> {\n const result = await loadConfig<UserConfig>({\n cwd: options.cwd,\n name: meta.binaryName,\n packageJson: [meta.binaryName],\n });\n\n return {\n config: result.config,\n configFile: result.configFile ?? undefined,\n layers: result.layers ?? [],\n };\n },\n};\n","import { spawn } from 'node:child_process';\n\nexport interface ExecutorRunOptions {\n readonly cwd?: string | undefined;\n readonly env?: NodeJS.ProcessEnv | undefined;\n}\n\n/**\n * Executes a command via the system shell, inheriting stdio and forwarding its exit code.\n */\nexport const Executor = {\n async run(command: string, options: ExecutorRunOptions = {}): Promise<number> {\n return new Promise((resolve, reject) => {\n const child = spawn(command, {\n cwd: options.cwd,\n env: options.env == null ? process.env : { ...process.env, ...options.env },\n shell: true,\n stdio: 'inherit',\n });\n\n child.on('error', reject);\n child.on('close', (code, signal) => {\n resolve(code ?? (signal == null ? 1 : 128));\n });\n });\n },\n};\n","import { meta } from '../meta.js';\n\nexport type ColorMode = 'always' | 'auto' | 'never';\nexport type LogLevel = 'debug' | 'error' | 'info' | 'silent' | 'warn';\n\n/**\n * Rank order used to compare log levels, higher means more verbose.\n */\nconst logLevelRank: Record<LogLevel, number> = {\n debug: 4,\n error: 1,\n info: 3,\n silent: 0,\n warn: 2,\n};\n\nexport interface CreateLoggerOptions {\n readonly color?: ColorMode;\n readonly level: LogLevel;\n\n /**\n * Program name used as message prefix (default: binary name)\n */\n readonly name?: string;\n readonly stderr: NodeJS.WritableStream;\n readonly stdout?: NodeJS.WritableStream | undefined;\n}\n\nexport interface Logger {\n debug(message: string): void;\n error(message: string): void;\n info(message: string): void;\n warn(message: string): void;\n}\n\n/**\n * Creates a logger writing to `stream`, filtering out messages above the configured `level`.\n */\nexport const Logger = {\n create({ color = 'auto', level, name = meta.binaryName, stderr }: CreateLoggerOptions): Logger {\n const write = (messageLevel: LogLevel, message: string) => {\n if (!(logLevelRank[messageLevel] <= logLevelRank[level])) {\n return;\n }\n // Keep stdout free for command output that may be consumed by another process.\n const outputStream = stderr;\n const shouldColor = color === 'always' || (color === 'auto' && 'isTTY' in outputStream && outputStream.isTTY === true);\n const colorCode = {\n debug: '\\u{1B}[36m',\n error: '\\u{1B}[31m',\n info: '',\n silent: '',\n warn: '\\u{1B}[33m',\n }[messageLevel];\n // Unix convention: `program: [level: ]message`, info has no level label\n const label = { debug: 'debug', error: 'error', info: '', silent: '', warn: 'warning' }[messageLevel];\n const coloredLabel = shouldColor && colorCode !== '' ? `${colorCode}${label}\\u{1B}[0m` : label;\n const prefix = label === '' ? `${name}: ` : `${name}: ${coloredLabel}: `;\n outputStream.write(`${prefix}${message}\\n`);\n };\n\n return {\n debug: (message) => write('debug', message),\n error: (message) => write('error', message),\n info: (message) => write('info', message),\n warn: (message) => write('warn', message),\n };\n },\n};\n","import { ManagedScriptEnv } from '../ManagedScriptEnv.js';\n\nexport interface ScriptNameResolverOptions {\n readonly env: NodeJS.ProcessEnv;\n readonly scriptName: string | undefined;\n}\n\n/**\n * Resolves the script name to run.\n *\n * Priority: first positional CLI argument > `MANAGED_SCRIPT_NAME` env var > `npm_lifecycle_event` env var.\n */\nexport const ScriptNameResolver = {\n resolve({ env, scriptName }: ScriptNameResolverOptions): string | undefined {\n return scriptName ?? env[ManagedScriptEnv.Name] ?? env['npm_lifecycle_event'];\n },\n};\n","import path from 'node:path/win32';\n\nimport type { ConfigLoaderResult } from '../internal/ConfigLoader.js';\nimport type { ResolvedConfig } from '../type/ResolvedConfig.js';\n\nexport function resolveScripts(loaded: ConfigLoaderResult): ResolvedConfig {\n const scripts: ResolvedConfig['scripts'] = {};\n const layers = loaded.layers.length > 0 ? loaded.layers : [{ config: loaded.config }];\n\n for (const layer of layers) {\n for (const [name, command] of Object.entries(layer.config?.scripts ?? {})) {\n const configFile = layer.configFile ?? loaded.configFile;\n const configDir = configFile == null ? undefined : path.dirname(configFile);\n scripts[name] ??= {\n command,\n configDir,\n configFile,\n };\n }\n }\n\n return {\n scripts,\n };\n}\n","import path from 'node:path';\n\nimport type { ManagedScriptCommand } from '../type.js';\n\nimport { ConfigLoader } from '../internal/ConfigLoader.js';\nimport { Executor } from '../internal/Executor.js';\nimport { Logger } from '../internal/Logger.js';\nimport { ScriptNameResolver } from '../internal/ScriptNameResolver.js';\nimport { ManagedScriptEnv } from '../ManagedScriptEnv.js';\nimport { defaultContext } from './defaultContext.js';\nimport { resolveScripts } from './resolveScripts.js';\n\nconst handlers = {\n RunScript: async (command: ManagedScriptCommand.RunScript): Promise<number> => {\n const {\n context: { color, cwd, dryRun, env, logLevel, stderr, stdout },\n parameters: { scriptArgs = [], scriptName },\n } = command;\n const logger = Logger.create({ color, level: logLevel, stderr, stdout });\n const loaded = await ConfigLoader.load({ cwd });\n logger.debug(`Resolved configuration from ${loaded.configFile ?? 'defaults (no config file found)'}`);\n const resolved = resolveScripts(loaded);\n const { scripts } = resolved;\n\n const name = ScriptNameResolver.resolve({ env, scriptName: scriptName });\n if (name == null) {\n throw new Error(\n 'Unable to resolve the script name. Pass it as the first argument, set the MANAGED_SCRIPT_NAME environment variable, or run through an npm/pnpm script (npm_lifecycle_event).',\n );\n }\n\n const script = scripts[name];\n if (script == null) {\n const available = Object.keys(scripts);\n throw new Error(\n `No script named \"${name}\" found in the configuration.${\n available.length > 0 ? ` Available scripts: ${available.join(', ')}.` : ' No scripts are configured.'\n }`,\n );\n }\n\n const commandLine = [\n script.command,\n ...scriptArgs.map((argument) => `'${argument.replaceAll(\"'\", String.raw`'\\''`)}'`),\n ].join(' ');\n\n // relative to cwd\n // eslint-disable-next-line ts/no-non-null-assertion\n logger.debug(`Script found in configuration: ${path.relative(cwd, script.configFile!)}`);\n stdout.write(`$ ${commandLine}\\n`);\n if (dryRun) {\n return 0;\n }\n\n // Prepare the environment variables for the script execution.\n const scriptEnv = {\n [ManagedScriptEnv.Color]: color,\n [ManagedScriptEnv.ConfigDir]: script.configDir,\n [ManagedScriptEnv.ConfigFile]: script.configFile,\n [ManagedScriptEnv.Cwd]: cwd,\n [ManagedScriptEnv.LogLevel]: logLevel,\n [ManagedScriptEnv.Name]: name,\n };\n const exitCode = await Executor.run(commandLine, { cwd, env: scriptEnv });\n\n if (exitCode !== 0) {\n throw new Error(`Script \"${name}\" exited with code ${exitCode}.`);\n }\n\n return exitCode;\n },\n} satisfies {\n [K in ManagedScriptCommand['_']]: (command: Extract<ManagedScriptCommand, { _: K }>) => Promise<any>;\n};\n\nexport type ExecuteCommand<T extends ManagedScriptCommand> = Omit<T, 'context'> & {\n /**\n * Context is optional\n */\n context?: Partial<ManagedScriptCommand['context']>;\n};\n\n/**\n * Extract command parameter from execute handler\n */\nexport type ExecuteCommandParameters<T extends ManagedScriptCommand> = Omit<Parameters<typeof execute<T>>[0], '_'>;\n\n/**\n * Dispatch the command to the appropriate handler based on its type.\n *\n * @param command\n */\nexport async function execute<T extends ManagedScriptCommand>(command: ExecuteCommand<T>): Promise<Awaited<ReturnType<typeof handlers[T['_']]>>> {\n const context = defaultContext(command.context);\n // @ts-ignore we know this works\n return handlers[command._]({\n ...command,\n context,\n });\n}\n","import { ManagedScriptCommand } from '../type.js';\nimport { execute, type ExecuteCommandParameters } from './execute.js';\n\nexport async function runScript(options: ExecuteCommandParameters<ManagedScriptCommand.RunScript>) {\n return execute({\n _: 'RunScript',\n ...options,\n });\n}\n","import { runScript } from './ManagedScript/runScript.js';\n\n/**\n * @namespace\n */\nexport const ManagedScript = Object.freeze({\n runScript,\n});\n"],"mappings":";;;;;;AAAA,MAAa,OAAO,OAAO,OAAO;CAChC,aAAa;CACb,YAAY;CAEZ,eAAA;CAEA,aAAa;CAEb,MAAA;CAEA,SAAA;AACF,CAAC;;;ACOD,MAAa,eAAe,EAC1B,MAAM,KAAK,SAA2D;CACpE,MAAM,SAAS,MAAM,WAAuB;EAC1C,KAAK,QAAQ;EACb,MAAM,KAAK;EACX,aAAa,CAAC,KAAK,UAAU;CAC/B,CAAC;CAED,OAAO;EACL,QAAQ,OAAO;EACf,YAAY,OAAO,cAAc,KAAA;EACjC,QAAQ,OAAO,UAAU,CAAC;CAC5B;AACF,EACF;;;;;;ACtBA,MAAa,WAAW,EACtB,MAAM,IAAI,SAAiB,UAA8B,CAAC,GAAoB;CAC5E,OAAO,IAAI,SAAS,SAAS,WAAW;EACtC,MAAM,QAAQ,MAAM,SAAS;GAC3B,KAAK,QAAQ;GACb,KAAK,QAAQ,OAAO,OAAO,QAAQ,MAAM;IAAE,GAAG,QAAQ;IAAK,GAAG,QAAQ;GAAI;GAC1E,OAAO;GACP,OAAO;EACT,CAAC;EAED,MAAM,GAAG,SAAS,MAAM;EACxB,MAAM,GAAG,UAAU,MAAM,WAAW;GAClC,QAAQ,SAAS,UAAU,OAAO,IAAI,IAAI;EAC5C,CAAC;CACH,CAAC;AACH,EACF;;;;;;AClBA,MAAM,eAAyC;CAC7C,OAAO;CACP,OAAO;CACP,MAAM;CACN,QAAQ;CACR,MAAM;AACR;;;;AAwBA,MAAa,SAAS,EACpB,OAAO,EAAE,QAAQ,QAAQ,OAAO,OAAO,KAAK,YAAY,UAAuC;CAC7F,MAAM,SAAS,cAAwB,YAAoB;EACzD,IAAI,EAAE,aAAa,iBAAi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;;;AAqBA,eAAsB,QAAwC,SAAmF;CAC/I,MAAM,UAAU,eAAe,QAAQ,OAAO;CAE9C,OAAO,SAAS,QAAQ,EAAE,CAAC;EACzB,GAAG;EACH;CACF,CAAC;AACH;;;AChGA,eAAsB,UAAU,SAAmE;CACjG,OAAO,QAAQ;EACb,GAAG;EACH,GAAG;CACL,CAAC;AACH;;;;;;ACHA,MAAa,gBAAgB,OAAO,OAAO,EACzC,UACF,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"defaultContext-BthxLDX3.js","names":[],"sources":["../src/ManagedScriptEnv.ts","../src/ManagedScript/defaultContext.ts"],"sourcesContent":["/**\n * Enum for managed script environment variables.\n *\n * @enum\n */\nexport const ManagedScriptEnv = Object.freeze({\n /**\n * The color mode used for messages.\n */\n Color: 'MANAGED_SCRIPT_COLOR',\n\n /**\n * The directory where the managed script configuration is located.\n */\n ConfigDir: 'MANAGED_SCRIPT_CONFIG_DIR',\n\n /**\n * The file where the managed script configuration is located.\n */\n ConfigFile: 'MANAGED_SCRIPT_CONFIG_FILE',\n\n /**\n * The invocation directory used to resolve configuration and spawn the script.\n */\n Cwd: 'MANAGED_SCRIPT_CWD',\n\n /**\n * The resolved log level.\n */\n LogLevel: 'MANAGED_SCRIPT_LOGLEVEL',\n\n /**\n * The name of the managed script.\n */\n Name: 'MANAGED_SCRIPT_NAME',\n});\nexport type ManagedScriptEnv = typeof ManagedScriptEnv[keyof typeof ManagedScriptEnv];\n","import type { LogLevel } from '../internal/Logger.js';\nimport type { CommandContext } from '../type.js';\n\nimport { ManagedScriptEnv } from '../ManagedScriptEnv.js';\n\nexport function defaultContext(context: Partial<CommandContext> | undefined): CommandContext {\n const {\n cli = {},\n color,\n cwd,\n dryRun,\n env = process.env,\n logLevel,\n stderr = process.stderr,\n stdout = process.stdout,\n } = context ?? {};\n const envLogLevel = env[ManagedScriptEnv.LogLevel];\n return {\n cli,\n color: color ?? cli.color ?? 'auto',\n cwd: cwd ?? cli.cwd ?? env[ManagedScriptEnv.Cwd] ?? process.cwd(),\n dryRun: dryRun ?? cli.dryRun ?? false,\n env,\n logLevel: logLevel ?? cli.logLevel ?? (isLogLevel(envLogLevel) ? envLogLevel : 'info'),\n stderr,\n stdout,\n };\n}\n\nconst knownLogLevels = new Set<LogLevel>(['debug', 'error', 'info', 'silent', 'warn']);\n\nfunction isLogLevel(value: string | undefined): value is LogLevel {\n return knownLogLevels.has(value as LogLevel);\n}\n"],"mappings":";;;;;;AAKA,MAAa,mBAAmB,OAAO,OAAO;;;;CAI5C,OAAO;;;;CAKP,WAAW;;;;CAKX,YAAY;;;;CAKZ,KAAK;;;;CAKL,UAAU;;;;CAKV,MAAM;AACR,CAAC;;;AC9BD,SAAgB,eAAe,SAA8D;CAC3F,MAAM,EACJ,MAAM,CAAC,GACP,OACA,KACA,QACA,MAAM,QAAQ,KACd,UACA,SAAS,QAAQ,QACjB,SAAS,QAAQ,WACf,WAAW,CAAC;CAChB,MAAM,cAAc,IAAI,iBAAiB;CACzC,OAAO;EACL;EACA,OAAO,SAAS,IAAI,SAAS;EAC7B,KAAK,OAAO,IAAI,OAAO,IAAI,iBAAiB,QAAQ,QAAQ,IAAI;EAChE,QAAQ,UAAU,IAAI,UAAU;EAChC;EACA,UAAU,YAAY,IAAI,aAAa,WAAW,WAAW,IAAI,cAAc;EAC/E;EACA;CACF;AACF;AAEA,MAAM,iCAAiB,IAAI,IAAc;CAAC;CAAS;CAAS;CAAQ;CAAU;AAAM,CAAC;AAErF,SAAS,WAAW,OAA8C;CAChE,OAAO,eAAe,IAAI,KAAiB;AAC7C"}
@@ -1,53 +0,0 @@
1
- import { InputConfig } from "c12";
2
- //#region src/type/UserConfig.d.ts
3
- interface UserConfig extends InputConfig<{
4
- readonly scripts?: Record<string, string> | undefined;
5
- }> {}
6
- //#endregion
7
- //#region src/internal/Logger.d.ts
8
- type ColorMode = 'always' | 'auto' | 'never';
9
- type LogLevel = 'debug' | 'error' | 'info' | 'silent' | 'warn';
10
- //#endregion
11
- //#region src/type/CommandContext.d.ts
12
- interface CommandContext {
13
- /**
14
- * Command-line arguments passed to the script.
15
- */
16
- readonly cli: {
17
- color?: ColorMode | undefined;
18
- cwd?: string | undefined;
19
- dryRun?: boolean | undefined;
20
- logLevel?: LogLevel | undefined;
21
- };
22
- /**
23
- * Color mode used for status messages.
24
- */
25
- readonly color: ColorMode;
26
- /**
27
- * Current working directory of the script.
28
- */
29
- readonly cwd: string;
30
- /**
31
- * When `true`, the resolved command is printed instead of being executed.
32
- */
33
- readonly dryRun: boolean;
34
- /**
35
- * Environment variables available to the script.
36
- */
37
- readonly env: NodeJS.ProcessEnv;
38
- /**
39
- * Resolved log level used to filter status messages.
40
- */
41
- readonly logLevel: LogLevel;
42
- /**
43
- * Stream used to write error log messages.
44
- */
45
- readonly stderr: NodeJS.WritableStream;
46
- /**
47
- * Stream used to write standard log messages.
48
- */
49
- readonly stdout: NodeJS.WritableStream;
50
- }
51
- //#endregion
52
- export { UserConfig as n, CommandContext as t };
53
- //# sourceMappingURL=type-DQiyX1q_.d.ts.map
@@ -1,58 +0,0 @@
1
- import { stripVTControlCharacters } from 'node:util';
2
- import { chalk, log as zxLog } from 'zx';
3
-
4
- import type { LogLevel } from '../internal/Logger.js';
5
- import type { ZXOptions } from './ZXOptions.js';
6
-
7
- import { defaultContext } from '../ManagedScript/defaultContext.js';
8
-
9
- export function defaultZXOptions(options: Partial<ZXOptions> & { logLevel?: LogLevel | undefined; stderr?: NodeJS.WritableStream | undefined; stdout?: NodeJS.WritableStream | undefined }): Partial<ZXOptions> {
10
- const { cwd: optionsCwd, env: optionsEnv, logLevel: optionsLogLevel, stderr: optionsStderr, stdout: optionsStdout, ...optionsRest } = options;
11
- const env = optionsEnv == null ? process.env : { ...process.env, ...optionsEnv };
12
- const context = defaultContext({
13
- env,
14
- ...(optionsCwd == null ? {} : { cwd: optionsCwd }),
15
- ...(optionsLogLevel == null ? {} : { logLevel: optionsLogLevel }),
16
- ...(optionsStderr == null ? {} : { stderr: optionsStderr }),
17
- ...(optionsStdout == null ? {} : { stdout: optionsStdout }),
18
- });
19
-
20
- return {
21
- cwd: context.cwd,
22
- env: context.env,
23
- log: (entry) => {
24
- const target = (entry.kind === 'cmd' || entry.kind === 'stdout' ? context.stdout : context.stderr) as NodeJS.WriteStream;
25
- const colorEnabled = context.color === 'always' || (context.color === 'auto' && autoColor(context.env, target));
26
- const previousOutput = zxLog.output;
27
- const previousLevel = chalk.level;
28
- zxLog.output = colorEnabled
29
- ? target
30
- : ({ write: (chunk: string) => target.write(stripVTControlCharacters(chunk)) } as unknown as NodeJS.WriteStream);
31
- if (colorEnabled && !chalk.level) {
32
- chalk.level = 1;
33
- } else if (!colorEnabled) {
34
- chalk.level = 0;
35
- }
36
- try {
37
- zxLog(entry.kind === 'cmd' && (context.logLevel === 'info' || context.logLevel === 'debug') ? { ...entry, verbose: true } : entry);
38
- } finally {
39
- // eslint-disable-next-line ts/no-non-null-assertion
40
- zxLog.output = previousOutput!;
41
- chalk.level = previousLevel;
42
- }
43
- },
44
- preferLocal: true,
45
- quiet: context.logLevel === 'silent',
46
- stdio: 'inherit',
47
- verbose: context.logLevel === 'debug',
48
- ...optionsRest,
49
- };
50
- }
51
-
52
- function autoColor(env: NodeJS.ProcessEnv, stream: NodeJS.WriteStream): boolean {
53
- if (env['NO_COLOR'] != null && env['NO_COLOR'] !== '') {
54
- return false;
55
- }
56
- const force = env['FORCE_COLOR'];
57
- return force == null ? stream.isTTY === true : force !== '0' && force !== 'false';
58
- }