@w5s/managed-script 1.0.0-alpha.2

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 +121 -0
  2. package/dist/ManagedScript-DIacNHCc.js +149 -0
  3. package/dist/ManagedScript-DIacNHCc.js.map +1 -0
  4. package/dist/cli.d.ts +1 -0
  5. package/dist/cli.js +2808 -0
  6. package/dist/cli.js.map +1 -0
  7. package/dist/defaultContext-D_QWP9aF.js +98 -0
  8. package/dist/defaultContext-D_QWP9aF.js.map +1 -0
  9. package/dist/index.d.ts +155 -0
  10. package/dist/index.js +79 -0
  11. package/dist/index.js.map +1 -0
  12. package/dist/type-DQiyX1q_.d.ts +53 -0
  13. package/dist/zx.d.ts +48 -0
  14. package/dist/zx.js +76 -0
  15. package/dist/zx.js.map +1 -0
  16. package/package.json +53 -0
  17. package/src/ManagedScript/defaultContext.ts +34 -0
  18. package/src/ManagedScript/execute.ts +98 -0
  19. package/src/ManagedScript/resolveScripts.ts +25 -0
  20. package/src/ManagedScript/runScript.ts +9 -0
  21. package/src/ManagedScript.ts +8 -0
  22. package/src/ManagedScriptEnv.ts +37 -0
  23. package/src/cli/RootCommand.ts +88 -0
  24. package/src/cli/runCLI.ts +27 -0
  25. package/src/cli.ts +4 -0
  26. package/src/defineConfig.ts +16 -0
  27. package/src/index.ts +6 -0
  28. package/src/internal/ConfigLoader.ts +33 -0
  29. package/src/internal/Executor.ts +27 -0
  30. package/src/internal/Logger.ts +58 -0
  31. package/src/internal/ScriptNameResolver.ts +17 -0
  32. package/src/mergeConfig.ts +70 -0
  33. package/src/meta.ts +12 -0
  34. package/src/type/Command.ts +37 -0
  35. package/src/type/CommandContext.ts +48 -0
  36. package/src/type/ResolvedConfig.ts +18 -0
  37. package/src/type/UserConfig.ts +5 -0
  38. package/src/type.ts +4 -0
  39. package/src/zx/ZXOptions.ts +1 -0
  40. package/src/zx/ZXShell.ts +1 -0
  41. package/src/zx/defaultZXOptions.ts +37 -0
  42. package/src/zx/zx.ts +51 -0
  43. package/src/zx.ts +19 -0
@@ -0,0 +1,155 @@
1
+ import { n as UserConfig, t as CommandContext } from "./type-DQiyX1q_.js";
2
+ //#region src/defineConfig.d.ts
3
+ /**
4
+ * Define the configuration for the managed script.
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * // managed-script.config.ts or @acme/managed-script-config/index.ts
9
+ * export default defineConfig({
10
+ * // your configuration here
11
+ * });
12
+ * ```
13
+ */
14
+ export declare const defineConfig: import("c12").DefineConfig<UserConfig, import("c12").ConfigLayerMeta>;
15
+ //#endregion
16
+ //#region src/type/Command.d.ts
17
+ export type ManagedScriptCommand = ManagedScriptCommand.RunScript;
18
+ export declare namespace ManagedScriptCommand {
19
+ interface Base<TName extends string, TParameters extends object> {
20
+ /**
21
+ * Name of the command.
22
+ */
23
+ readonly _: TName;
24
+ /**
25
+ * Context in which the command is executed.
26
+ */
27
+ readonly context: CommandContext;
28
+ /**
29
+ * Parameters provided to the command.
30
+ */
31
+ readonly parameters: Readonly<TParameters>;
32
+ }
33
+ type Parameters<T extends Base<string, object>> = Omit<T, '_'>;
34
+ interface RunScript extends Base<'RunScript', {
35
+ scriptArgs?: ReadonlyArray<string>;
36
+ scriptName: string | undefined;
37
+ }> {}
38
+ }
39
+ export declare const ManagedScriptCommand: Readonly<{
40
+ RunScript: (args: ManagedScriptCommand.Parameters<ManagedScriptCommand.RunScript>) => ManagedScriptCommand.RunScript;
41
+ }>;
42
+ //#endregion
43
+ //#region src/type/ResolvedConfig.d.ts
44
+ export interface ResolvedConfig {
45
+ readonly scripts: Record<string, {
46
+ /**
47
+ * Command to execute
48
+ */
49
+ readonly command: string;
50
+ /**
51
+ * File path of the configuration file that defined this script
52
+ */
53
+ readonly configDir: string | undefined;
54
+ /**
55
+ * Directory of the configuration file that defined this script
56
+ */
57
+ readonly configFile: string | undefined;
58
+ }>;
59
+ }
60
+ //#endregion
61
+ //#region src/ManagedScript/execute.d.ts
62
+ declare const handlers: {
63
+ RunScript: (command: ManagedScriptCommand.RunScript) => Promise<number>;
64
+ };
65
+ type ExecuteCommand<T extends ManagedScriptCommand> = Omit<T, 'context'> & {
66
+ /**
67
+ * Context is optional
68
+ */
69
+ context?: Partial<ManagedScriptCommand['context']>;
70
+ };
71
+ /**
72
+ * Extract command parameter from execute handler
73
+ */
74
+ type ExecuteCommandParameters<T extends ManagedScriptCommand> = Omit<Parameters<typeof execute<T>>[0], '_'>;
75
+ /**
76
+ * Dispatch the command to the appropriate handler based on its type.
77
+ *
78
+ * @param command
79
+ */
80
+ declare function execute<T extends ManagedScriptCommand>(command: ExecuteCommand<T>): Promise<Awaited<ReturnType<typeof handlers[T['_']]>>>;
81
+ //#endregion
82
+ //#region src/ManagedScript/runScript.d.ts
83
+ declare function runScript(options: ExecuteCommandParameters<ManagedScriptCommand.RunScript>): Promise<number>;
84
+ //#endregion
85
+ //#region src/ManagedScript.d.ts
86
+ /**
87
+ * @namespace
88
+ */
89
+ export declare const ManagedScript: Readonly<{
90
+ runScript: typeof runScript;
91
+ }>;
92
+ //#endregion
93
+ //#region src/ManagedScriptEnv.d.ts
94
+ /**
95
+ * Enum for managed script environment variables.
96
+ *
97
+ * @enum
98
+ */
99
+ export declare const ManagedScriptEnv: Readonly<{
100
+ /**
101
+ * The color mode used for messages.
102
+ */
103
+ Color: "MANAGED_SCRIPT_COLOR";
104
+ /**
105
+ * The directory where the managed script configuration is located.
106
+ */
107
+ ConfigDir: "MANAGED_SCRIPT_CONFIG_DIR";
108
+ /**
109
+ * The file where the managed script configuration is located.
110
+ */
111
+ ConfigFile: "MANAGED_SCRIPT_CONFIG_FILE";
112
+ /**
113
+ * The invocation directory used to resolve configuration and spawn the script.
114
+ */
115
+ Cwd: "MANAGED_SCRIPT_CWD";
116
+ /**
117
+ * The resolved log level.
118
+ */
119
+ LogLevel: "MANAGED_SCRIPT_LOGLEVEL";
120
+ /**
121
+ * The name of the managed script.
122
+ */
123
+ Name: "MANAGED_SCRIPT_NAME";
124
+ }>;
125
+ export type ManagedScriptEnv = typeof ManagedScriptEnv[keyof typeof ManagedScriptEnv];
126
+ //#endregion
127
+ //#region src/mergeConfig.d.ts
128
+ /**
129
+ * Merge two managed-script configs using the same heuristic as Vite and Vitest:
130
+ * later values win, plain objects merge recursively, and arrays concatenate.
131
+ *
132
+ * @param defaults
133
+ * @param overrides
134
+ * @example
135
+ * ```ts
136
+ * export default defineConfig(mergeConfig(
137
+ * { scripts: { build: 'echo base', test: 'echo test' } },
138
+ * { scripts: { build: 'echo override' } },
139
+ * ));
140
+ * ```
141
+ */
142
+ export declare function mergeConfig(defaults: UserConfig, overrides: UserConfig): UserConfig;
143
+ //#endregion
144
+ //#region src/meta.d.ts
145
+ export declare const meta: Readonly<{
146
+ binaryLabel: "W5S Managed Script";
147
+ binaryName: "managed-script";
148
+ binaryVersion: string;
149
+ buildNumber: 1;
150
+ name: string;
151
+ version: string;
152
+ }>;
153
+ //#endregion
154
+ export { CommandContext, UserConfig };
155
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,79 @@
1
+ import { n as meta, t as ManagedScript } from "./ManagedScript-DIacNHCc.js";
2
+ import { n as ManagedScriptEnv } from "./defaultContext-D_QWP9aF.js";
3
+ import { createDefineConfig } from "c12";
4
+ //#region src/defineConfig.ts
5
+ /**
6
+ * Define the configuration for the managed script.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * // managed-script.config.ts or @acme/managed-script-config/index.ts
11
+ * export default defineConfig({
12
+ * // your configuration here
13
+ * });
14
+ * ```
15
+ */
16
+ const defineConfig = createDefineConfig();
17
+ //#endregion
18
+ //#region src/type/Command.ts
19
+ const ManagedScriptCommand = Object.freeze({ RunScript: (args) => ({
20
+ _: "RunScript",
21
+ ...args
22
+ }) });
23
+ //#endregion
24
+ //#region src/mergeConfig.ts
25
+ const DANGEROUS_KEYS = /* @__PURE__ */ new Set([
26
+ "__proto__",
27
+ "constructor",
28
+ "prototype"
29
+ ]);
30
+ /**
31
+ * Merge two managed-script configs using the same heuristic as Vite and Vitest:
32
+ * later values win, plain objects merge recursively, and arrays concatenate.
33
+ *
34
+ * @param defaults
35
+ * @param overrides
36
+ * @example
37
+ * ```ts
38
+ * export default defineConfig(mergeConfig(
39
+ * { scripts: { build: 'echo base', test: 'echo test' } },
40
+ * { scripts: { build: 'echo override' } },
41
+ * ));
42
+ * ```
43
+ */
44
+ function mergeConfig(defaults, overrides) {
45
+ if (typeof defaults === "function" || typeof overrides === "function") throw new TypeError("Cannot merge config in form of callback");
46
+ return mergeConfigRecursively({ ...defaults }, { ...overrides });
47
+ }
48
+ function isObject(value) {
49
+ return Object.prototype.toString.call(value) === "[object Object]";
50
+ }
51
+ function mergeConfigRecursively(defaults, overrides) {
52
+ const merged = { ...defaults };
53
+ for (const [key, value] of Object.entries(overrides)) {
54
+ if (DANGEROUS_KEYS.has(key)) continue;
55
+ if (value == null) continue;
56
+ const existing = merged[key];
57
+ if (existing == null) {
58
+ merged[key] = value;
59
+ continue;
60
+ }
61
+ if (Array.isArray(existing) || Array.isArray(value)) {
62
+ merged[key] = [...toArray(existing), ...toArray(value)];
63
+ continue;
64
+ }
65
+ if (isObject(existing) && isObject(value)) {
66
+ merged[key] = mergeConfigRecursively(existing, value);
67
+ continue;
68
+ }
69
+ merged[key] = value;
70
+ }
71
+ return merged;
72
+ }
73
+ function toArray(target) {
74
+ return Array.isArray(target) ? target : [target];
75
+ }
76
+ //#endregion
77
+ export { ManagedScript, ManagedScriptCommand, ManagedScriptEnv, defineConfig, mergeConfig, meta };
78
+
79
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/defineConfig.ts","../src/type/Command.ts","../src/mergeConfig.ts"],"sourcesContent":["import { createDefineConfig } from 'c12';\n\nimport type { UserConfig } from './type/UserConfig.js';\n\n/**\n * Define the configuration for the managed script.\n *\n * @example\n * ```ts\n * // managed-script.config.ts or @acme/managed-script-config/index.ts\n * export default defineConfig({\n * // your configuration here\n * });\n * ```\n */\nexport const defineConfig = createDefineConfig<UserConfig>();\n","import type { CommandContext } from './CommandContext.js';\n\nexport type ManagedScriptCommand =\n | ManagedScriptCommand.RunScript;\n\nexport namespace ManagedScriptCommand {\n export interface Base<TName extends string, TParameters extends object> {\n /**\n * Name of the command.\n */\n readonly _: TName;\n\n /**\n * Context in which the command is executed.\n */\n readonly context: CommandContext;\n\n /**\n * Parameters provided to the command.\n */\n readonly parameters: Readonly<TParameters>;\n }\n\n export type Parameters<T extends Base<string, object>> = Omit<T, '_'>;\n\n export interface RunScript extends Base<'RunScript', {\n scriptArgs?: ReadonlyArray<string>;\n scriptName: string | undefined;\n }> {}\n}\n\nexport const ManagedScriptCommand = Object.freeze({\n RunScript: (args: ManagedScriptCommand.Parameters<ManagedScriptCommand.RunScript>): ManagedScriptCommand.RunScript => ({\n _: 'RunScript' as const,\n ...args,\n }),\n});\n","import type { UserConfig } from './type/UserConfig.js';\n\nconst DANGEROUS_KEYS = new Set(['__proto__', 'constructor', 'prototype']);\n\n/**\n * Merge two managed-script configs using the same heuristic as Vite and Vitest:\n * later values win, plain objects merge recursively, and arrays concatenate.\n *\n * @param defaults\n * @param overrides\n * @example\n * ```ts\n * export default defineConfig(mergeConfig(\n * { scripts: { build: 'echo base', test: 'echo test' } },\n * { scripts: { build: 'echo override' } },\n * ));\n * ```\n */\nexport function mergeConfig(defaults: UserConfig, overrides: UserConfig): UserConfig {\n if (typeof defaults === 'function' || typeof overrides === 'function') {\n throw new TypeError('Cannot merge config in form of callback');\n }\n\n return mergeConfigRecursively({ ...defaults }, { ...overrides });\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return Object.prototype.toString.call(value) === '[object Object]';\n}\n\nfunction mergeConfigRecursively(\n defaults: Record<string, unknown>,\n overrides: Record<string, unknown>,\n): Record<string, unknown> {\n const merged: Record<string, unknown> = { ...defaults };\n\n for (const [key, value] of Object.entries(overrides)) {\n if (DANGEROUS_KEYS.has(key)) {\n continue;\n }\n\n if (value == null) {\n continue;\n }\n\n const existing = merged[key];\n if (existing == null) {\n merged[key] = value;\n continue;\n }\n\n if (Array.isArray(existing) || Array.isArray(value)) {\n merged[key] = [...toArray(existing), ...toArray(value)];\n continue;\n }\n\n if (isObject(existing) && isObject(value)) {\n merged[key] = mergeConfigRecursively(existing, value);\n continue;\n }\n\n merged[key] = value;\n }\n\n return merged;\n}\n\nfunction toArray<T>(target: Array<T> | T): Array<T> {\n return Array.isArray(target) ? target : [target];\n}\n"],"mappings":";;;;;;;;;;;;;;;AAeA,MAAa,eAAe,mBAA+B;;;ACgB3D,MAAa,uBAAuB,OAAO,OAAO,EAChD,YAAY,UAA2G;CACrH,GAAG;CACH,GAAG;AACL,GACF,CAAC;;;AClCD,MAAM,iCAAiB,IAAI,IAAI;CAAC;CAAa;CAAe;AAAW,CAAC;;;;;;;;;;;;;;;AAgBxE,SAAgB,YAAY,UAAsB,WAAmC;CACnF,IAAI,OAAO,aAAa,cAAc,OAAO,cAAc,YACzD,MAAM,IAAI,UAAU,yCAAyC;CAG/D,OAAO,uBAAuB,EAAE,GAAG,SAAS,GAAG,EAAE,GAAG,UAAU,CAAC;AACjE;AAEA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,SAAS,KAAK,KAAK,MAAM;AACnD;AAEA,SAAS,uBACP,UACA,WACyB;CACzB,MAAM,SAAkC,EAAE,GAAG,SAAS;CAEtD,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,SAAS,GAAG;EACpD,IAAI,eAAe,IAAI,GAAG,GACxB;EAGF,IAAI,SAAS,MACX;EAGF,MAAM,WAAW,OAAO;EACxB,IAAI,YAAY,MAAM;GACpB,OAAO,OAAO;GACd;EACF;EAEA,IAAI,MAAM,QAAQ,QAAQ,KAAK,MAAM,QAAQ,KAAK,GAAG;GACnD,OAAO,OAAO,CAAC,GAAG,QAAQ,QAAQ,GAAG,GAAG,QAAQ,KAAK,CAAC;GACtD;EACF;EAEA,IAAI,SAAS,QAAQ,KAAK,SAAS,KAAK,GAAG;GACzC,OAAO,OAAO,uBAAuB,UAAU,KAAK;GACpD;EACF;EAEA,OAAO,OAAO;CAChB;CAEA,OAAO;AACT;AAEA,SAAS,QAAW,QAAgC;CAClD,OAAO,MAAM,QAAQ,MAAM,IAAI,SAAS,CAAC,MAAM;AACjD"}
@@ -0,0 +1,53 @@
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
package/dist/zx.d.ts ADDED
@@ -0,0 +1,48 @@
1
+ import { t as CommandContext } from "./type-DQiyX1q_.js";
2
+ import { Options as ZXOptions, Shell as ZXShell } from "zx";
3
+ //#region src/zx/zx.d.ts
4
+ export interface CreateZXOptions {
5
+ /**
6
+ * Working directory for spawned commands. Defaults to `MANAGED_SCRIPT_CWD`, then `process.cwd()`.
7
+ */
8
+ readonly cwd?: string | undefined;
9
+ /**
10
+ * Environment variables passed to spawned commands. Merged over `process.env`.
11
+ */
12
+ readonly env?: NodeJS.ProcessEnv | undefined;
13
+ /**
14
+ * Log level used to derive zx `verbose` / `quiet` and command instrumentation.
15
+ * Defaults to `MANAGED_SCRIPT_LOGLEVEL`, then `info`.
16
+ */
17
+ readonly logLevel?: CommandContext['logLevel'] | undefined;
18
+ /**
19
+ * Stream used to write instrumented command logs at the error and warn levels.
20
+ */
21
+ readonly stderr?: NodeJS.WritableStream | undefined;
22
+ /**
23
+ * Stream used to write instrumented command logs at the info and debug levels.
24
+ */
25
+ readonly stdout?: NodeJS.WritableStream | undefined;
26
+ }
27
+ /**
28
+ * Creates a zx `$` preset configured from managed-script context and environment variables.
29
+ *
30
+ * @param options
31
+ */
32
+ export declare function zx(options?: CreateZXOptions): ZXShell;
33
+ //#endregion
34
+ //#region src/zx.d.ts
35
+ /**
36
+ * Default `$` preset for scripts launched by managed-script.
37
+ * Reads `MANAGED_SCRIPT_*` from the process environment at import time.
38
+ *
39
+ * @example
40
+ * ```ts
41
+ * import { $ } from '@w5s/managed-script/zx';
42
+ * await $`echo Hello, world!`;
43
+ * ```
44
+ */
45
+ export declare const $: ZXShell;
46
+ //#endregion
47
+ export type { ZXOptions, ZXShell };
48
+ //# sourceMappingURL=zx.d.ts.map
package/dist/zx.js ADDED
@@ -0,0 +1,76 @@
1
+ import { r as Logger, t as defaultContext } from "./defaultContext-D_QWP9aF.js";
2
+ import { $ as $$1, log } from "zx";
3
+ //#region src/zx/defaultZXOptions.ts
4
+ function defaultZXOptions(options) {
5
+ const { cwd: optionsCwd, env: optionsEnv, logLevel: optionsLogLevel, stderr: optionsStderr, stdout: optionsStdout, ...optionsRest } = options;
6
+ const env = optionsEnv == null ? process.env : {
7
+ ...process.env,
8
+ ...optionsEnv
9
+ };
10
+ const context = defaultContext({
11
+ env,
12
+ ...optionsCwd == null ? {} : { cwd: optionsCwd },
13
+ ...optionsLogLevel == null ? {} : { logLevel: optionsLogLevel },
14
+ ...optionsStderr == null ? {} : { stderr: optionsStderr },
15
+ ...optionsStdout == null ? {} : { stdout: optionsStdout }
16
+ });
17
+ const logger = Logger.create({
18
+ color: context.color,
19
+ level: context.logLevel,
20
+ stderr: context.stderr,
21
+ stdout: context.stdout
22
+ });
23
+ return {
24
+ cwd: context.cwd,
25
+ env: context.env,
26
+ log: (entry) => {
27
+ if (entry.kind === "cmd") {
28
+ logger.info(entry.cmd);
29
+ return;
30
+ }
31
+ log(entry);
32
+ },
33
+ preferLocal: true,
34
+ quiet: context.logLevel === "silent",
35
+ stdio: "inherit",
36
+ verbose: context.logLevel === "debug",
37
+ ...optionsRest
38
+ };
39
+ }
40
+ //#endregion
41
+ //#region src/zx/zx.ts
42
+ /**
43
+ * Creates a zx `$` preset configured from managed-script context and environment variables.
44
+ *
45
+ * @param options
46
+ */
47
+ function zx(options = {}) {
48
+ const env = options.env == null ? process.env : {
49
+ ...process.env,
50
+ ...options.env
51
+ };
52
+ return $$1(defaultZXOptions({
53
+ env,
54
+ ...options.cwd == null ? {} : { cwd: options.cwd },
55
+ ...options.logLevel == null ? {} : { logLevel: options.logLevel },
56
+ ...options.stderr == null ? {} : { stderr: options.stderr },
57
+ ...options.stdout == null ? {} : { stdout: options.stdout }
58
+ }));
59
+ }
60
+ //#endregion
61
+ //#region src/zx.ts
62
+ /**
63
+ * Default `$` preset for scripts launched by managed-script.
64
+ * Reads `MANAGED_SCRIPT_*` from the process environment at import time.
65
+ *
66
+ * @example
67
+ * ```ts
68
+ * import { $ } from '@w5s/managed-script/zx';
69
+ * await $`echo Hello, world!`;
70
+ * ```
71
+ */
72
+ const $ = zx();
73
+ //#endregion
74
+ export { $, zx };
75
+
76
+ //# sourceMappingURL=zx.js.map
package/dist/zx.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"zx.js","names":["zxDefault"],"sources":["../src/zx/defaultZXOptions.ts","../src/zx/zx.ts","../src/zx.ts"],"sourcesContent":["import { log as zxLog } from 'zx';\n\nimport type { LogLevel } from '../internal/Logger.js';\nimport type { ZXOptions } from './ZXOptions.js';\n\nimport { Logger } from '../internal/Logger.js';\nimport { defaultContext } from '../ManagedScript/defaultContext.js';\n\nexport function defaultZXOptions(options: Partial<ZXOptions> & { logLevel?: LogLevel | undefined; stderr?: NodeJS.WritableStream | undefined; stdout?: NodeJS.WritableStream | undefined }): Partial<ZXOptions> {\n const { cwd: optionsCwd, env: optionsEnv, logLevel: optionsLogLevel, stderr: optionsStderr, stdout: optionsStdout, ...optionsRest } = options;\n const env = optionsEnv == null ? process.env : { ...process.env, ...optionsEnv };\n const context = defaultContext({\n env,\n ...(optionsCwd == null ? {} : { cwd: optionsCwd }),\n ...(optionsLogLevel == null ? {} : { logLevel: optionsLogLevel }),\n ...(optionsStderr == null ? {} : { stderr: optionsStderr }),\n ...(optionsStdout == null ? {} : { stdout: optionsStdout }),\n });\n const logger = Logger.create({ color: context.color, level: context.logLevel, stderr: context.stderr, stdout: context.stdout });\n\n return {\n cwd: context.cwd,\n env: context.env,\n log: (entry) => {\n if (entry.kind === 'cmd') {\n logger.info(entry.cmd);\n return;\n }\n zxLog(entry);\n },\n preferLocal: true,\n quiet: context.logLevel === 'silent',\n stdio: 'inherit',\n verbose: context.logLevel === 'debug',\n ...optionsRest,\n };\n}\n","import { $ as zxDefault } from 'zx';\n\nimport type { CommandContext } from '../type.js';\nimport type { ZXShell } from './ZXShell.js';\n\nimport { defaultZXOptions } from './defaultZXOptions.js';\n\nexport interface CreateZXOptions {\n /**\n * Working directory for spawned commands. Defaults to `MANAGED_SCRIPT_CWD`, then `process.cwd()`.\n */\n readonly cwd?: string | undefined;\n\n /**\n * Environment variables passed to spawned commands. Merged over `process.env`.\n */\n readonly env?: NodeJS.ProcessEnv | undefined;\n\n /**\n * Log level used to derive zx `verbose` / `quiet` and command instrumentation.\n * Defaults to `MANAGED_SCRIPT_LOGLEVEL`, then `info`.\n */\n readonly logLevel?: CommandContext['logLevel'] | undefined;\n\n /**\n * Stream used to write instrumented command logs at the error and warn levels.\n */\n readonly stderr?: NodeJS.WritableStream | undefined;\n\n /**\n * Stream used to write instrumented command logs at the info and debug levels.\n */\n readonly stdout?: NodeJS.WritableStream | undefined;\n}\n\n/**\n * Creates a zx `$` preset configured from managed-script context and environment variables.\n *\n * @param options\n */\nexport function zx(options: CreateZXOptions = {}): ZXShell {\n const env = options.env == null ? process.env : { ...process.env, ...options.env };\n\n return zxDefault(defaultZXOptions({\n env,\n ...(options.cwd == null ? {} : { cwd: options.cwd }),\n ...(options.logLevel == null ? {} : { logLevel: options.logLevel }),\n ...(options.stderr == null ? {} : { stderr: options.stderr }),\n ...(options.stdout == null ? {} : { stdout: options.stdout }),\n }));\n}\n","import type { ZXShell } from './zx/ZXShell.js';\n\nimport { zx } from './zx/zx.js';\n\nexport * from './zx/zx.js';\nexport type * from './zx/ZXOptions.js';\nexport type * from './zx/ZXShell.js';\n\n/**\n * Default `$` preset for scripts launched by managed-script.\n * Reads `MANAGED_SCRIPT_*` from the process environment at import time.\n *\n * @example\n * ```ts\n * import { $ } from '@w5s/managed-script/zx';\n * await $`echo Hello, world!`;\n * ```\n */\nexport const $: ZXShell = zx();\n"],"mappings":";;;AAQA,SAAgB,iBAAiB,SAA+K;CAC9M,MAAM,EAAE,KAAK,YAAY,KAAK,YAAY,UAAU,iBAAiB,QAAQ,eAAe,QAAQ,eAAe,GAAG,gBAAgB;CACtI,MAAM,MAAM,cAAc,OAAO,QAAQ,MAAM;EAAE,GAAG,QAAQ;EAAK,GAAG;CAAW;CAC/E,MAAM,UAAU,eAAe;EAC7B;EACA,GAAI,cAAc,OAAO,CAAC,IAAI,EAAE,KAAK,WAAW;EAChD,GAAI,mBAAmB,OAAO,CAAC,IAAI,EAAE,UAAU,gBAAgB;EAC/D,GAAI,iBAAiB,OAAO,CAAC,IAAI,EAAE,QAAQ,cAAc;EACzD,GAAI,iBAAiB,OAAO,CAAC,IAAI,EAAE,QAAQ,cAAc;CAC3D,CAAC;CACD,MAAM,SAAS,OAAO,OAAO;EAAE,OAAO,QAAQ;EAAO,OAAO,QAAQ;EAAU,QAAQ,QAAQ;EAAQ,QAAQ,QAAQ;CAAO,CAAC;CAE9H,OAAO;EACL,KAAK,QAAQ;EACb,KAAK,QAAQ;EACb,MAAM,UAAU;GACd,IAAI,MAAM,SAAS,OAAO;IACxB,OAAO,KAAK,MAAM,GAAG;IACrB;GACF;GACA,IAAM,KAAK;EACb;EACA,aAAa;EACb,OAAO,QAAQ,aAAa;EAC5B,OAAO;EACP,SAAS,QAAQ,aAAa;EAC9B,GAAG;CACL;AACF;;;;;;;;ACIA,SAAgB,GAAG,UAA2B,CAAC,GAAY;CACzD,MAAM,MAAM,QAAQ,OAAO,OAAO,QAAQ,MAAM;EAAE,GAAG,QAAQ;EAAK,GAAG,QAAQ;CAAI;CAEjF,OAAOA,IAAU,iBAAiB;EAChC;EACA,GAAI,QAAQ,OAAO,OAAO,CAAC,IAAI,EAAE,KAAK,QAAQ,IAAI;EAClD,GAAI,QAAQ,YAAY,OAAO,CAAC,IAAI,EAAE,UAAU,QAAQ,SAAS;EACjE,GAAI,QAAQ,UAAU,OAAO,CAAC,IAAI,EAAE,QAAQ,QAAQ,OAAO;EAC3D,GAAI,QAAQ,UAAU,OAAO,CAAC,IAAI,EAAE,QAAQ,QAAQ,OAAO;CAC7D,CAAC,CAAC;AACJ;;;;;;;;;;;;;AChCA,MAAa,IAAa,GAAG"}
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@w5s/managed-script",
3
+ "version": "1.0.0-alpha.2",
4
+ "description": "CLI tool to run project scripts from a shared configuration",
5
+ "keywords": [
6
+ "cli",
7
+ "config",
8
+ "scripts"
9
+ ],
10
+ "homepage": "https://github.com/w5s/project-config/blob/main/packages/managed-script#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/w5s/project-config/issues"
13
+ },
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/w5s/project-config.git",
17
+ "directory": "packages/managed-script"
18
+ },
19
+ "license": "MIT",
20
+ "author": "Julien Polo <julien.polo@gmail.com>",
21
+ "sideEffects": false,
22
+ "type": "module",
23
+ "exports": {
24
+ "./package.json": "./package.json",
25
+ ".": "./dist/index.js",
26
+ "./zx": "./dist/zx.js",
27
+ "./internal/*": null
28
+ },
29
+ "bin": {
30
+ "managed-script": "dist/cli.js"
31
+ },
32
+ "files": [
33
+ "dist/",
34
+ "src/",
35
+ "index.js",
36
+ "index.d.ts",
37
+ "!**/*.spec.*",
38
+ "!**/__tests__/**"
39
+ ],
40
+ "scripts": {
41
+ "postpack": "clean-package restore"
42
+ },
43
+ "dependencies": {
44
+ "c12": "^3.2.0",
45
+ "zx": "8.8.5-lite"
46
+ },
47
+ "engines": {
48
+ "node": ">=22.0.0"
49
+ },
50
+ "publishConfig": {
51
+ "access": "public"
52
+ }
53
+ }
@@ -0,0 +1,34 @@
1
+ import type { LogLevel } from '../internal/Logger.js';
2
+ import type { CommandContext } from '../type.js';
3
+
4
+ import { ManagedScriptEnv } from '../ManagedScriptEnv.js';
5
+
6
+ export function defaultContext(context: Partial<CommandContext> | undefined): CommandContext {
7
+ const {
8
+ cli = {},
9
+ color,
10
+ cwd,
11
+ dryRun,
12
+ env = process.env,
13
+ logLevel,
14
+ stderr = process.stderr,
15
+ stdout = process.stdout,
16
+ } = context ?? {};
17
+ const envLogLevel = env[ManagedScriptEnv.LogLevel];
18
+ return {
19
+ cli,
20
+ color: color ?? cli.color ?? 'auto',
21
+ cwd: cwd ?? cli.cwd ?? env[ManagedScriptEnv.Cwd] ?? process.cwd(),
22
+ dryRun: dryRun ?? cli.dryRun ?? false,
23
+ env,
24
+ logLevel: logLevel ?? cli.logLevel ?? (isLogLevel(envLogLevel) ? envLogLevel : 'info'),
25
+ stderr,
26
+ stdout,
27
+ };
28
+ }
29
+
30
+ const knownLogLevels = new Set<LogLevel>(['debug', 'error', 'info', 'silent', 'warn']);
31
+
32
+ function isLogLevel(value: string | undefined): value is LogLevel {
33
+ return knownLogLevels.has(value as LogLevel);
34
+ }
@@ -0,0 +1,98 @@
1
+ import type { ManagedScriptCommand } from '../type.js';
2
+
3
+ import { ConfigLoader } from '../internal/ConfigLoader.js';
4
+ import { Executor } from '../internal/Executor.js';
5
+ import { Logger } from '../internal/Logger.js';
6
+ import { ScriptNameResolver } from '../internal/ScriptNameResolver.js';
7
+ import { ManagedScriptEnv } from '../ManagedScriptEnv.js';
8
+ import { defaultContext } from './defaultContext.js';
9
+ import { resolveScripts } from './resolveScripts.js';
10
+
11
+ const handlers = {
12
+ RunScript: async (command: ManagedScriptCommand.RunScript): Promise<number> => {
13
+ const {
14
+ context: { color, cwd, dryRun, env, logLevel, stderr, stdout },
15
+ parameters: { scriptArgs = [], scriptName },
16
+ } = command;
17
+ const logger = Logger.create({ color, level: logLevel, stderr, stdout });
18
+ const loaded = await ConfigLoader.load({ cwd });
19
+ logger.debug(`Resolved configuration from ${loaded.configFile ?? 'defaults (no config file found)'}.`);
20
+ const resolved = resolveScripts(loaded);
21
+ const { scripts } = resolved;
22
+
23
+ const name = ScriptNameResolver.resolve({ env, scriptName: scriptName });
24
+ if (name == null) {
25
+ throw new Error(
26
+ '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).',
27
+ );
28
+ }
29
+
30
+ const script = scripts[name];
31
+ if (script == null) {
32
+ const available = Object.keys(scripts);
33
+ throw new Error(
34
+ `No script named "${name}" found in the configuration.${
35
+ available.length > 0 ? ` Available scripts: ${available.join(', ')}.` : ' No scripts are configured.'
36
+ }`,
37
+ );
38
+ }
39
+
40
+ const commandLine = [
41
+ script.command,
42
+ ...scriptArgs.map((argument) => `'${argument.replaceAll("'", String.raw`'\''`)}'`),
43
+ ].join(' ');
44
+
45
+ if (dryRun) {
46
+ stdout.write(`${commandLine}\n`);
47
+ return 0;
48
+ }
49
+
50
+ logger.info(`Running script "${name}": ${commandLine}`);
51
+
52
+ // Prepare the environment variables for the script execution.
53
+ const scriptEnv = {
54
+ [ManagedScriptEnv.Color]: color,
55
+ [ManagedScriptEnv.ConfigDir]: script.configDir,
56
+ [ManagedScriptEnv.ConfigFile]: script.configFile,
57
+ [ManagedScriptEnv.Cwd]: cwd,
58
+ [ManagedScriptEnv.LogLevel]: logLevel,
59
+ [ManagedScriptEnv.Name]: name,
60
+ };
61
+
62
+ const exitCode = await Executor.run(commandLine, { cwd, env: scriptEnv });
63
+
64
+ if (exitCode !== 0) {
65
+ throw new Error(`Script "${name}" exited with code ${exitCode}.`);
66
+ }
67
+
68
+ return exitCode;
69
+ },
70
+ } satisfies {
71
+ [K in ManagedScriptCommand['_']]: (command: Extract<ManagedScriptCommand, { _: K }>) => Promise<any>;
72
+ };
73
+
74
+ export type ExecuteCommand<T extends ManagedScriptCommand> = Omit<T, 'context'> & {
75
+ /**
76
+ * Context is optional
77
+ */
78
+ context?: Partial<ManagedScriptCommand['context']>;
79
+ };
80
+
81
+ /**
82
+ * Extract command parameter from execute handler
83
+ */
84
+ export type ExecuteCommandParameters<T extends ManagedScriptCommand> = Omit<Parameters<typeof execute<T>>[0], '_'>;
85
+
86
+ /**
87
+ * Dispatch the command to the appropriate handler based on its type.
88
+ *
89
+ * @param command
90
+ */
91
+ export async function execute<T extends ManagedScriptCommand>(command: ExecuteCommand<T>): Promise<Awaited<ReturnType<typeof handlers[T['_']]>>> {
92
+ const context = defaultContext(command.context);
93
+ // @ts-ignore we know this works
94
+ return handlers[command._]({
95
+ ...command,
96
+ context,
97
+ });
98
+ }
@@ -0,0 +1,25 @@
1
+ import path from 'node:path/win32';
2
+
3
+ import type { ConfigLoaderResult } from '../internal/ConfigLoader.js';
4
+ import type { ResolvedConfig } from '../type/ResolvedConfig.js';
5
+
6
+ export function resolveScripts(loaded: ConfigLoaderResult): ResolvedConfig {
7
+ const scripts: ResolvedConfig['scripts'] = {};
8
+ const layers = loaded.layers.length > 0 ? loaded.layers : [{ config: loaded.config }];
9
+
10
+ for (const layer of layers) {
11
+ for (const [name, command] of Object.entries(layer.config?.scripts ?? {})) {
12
+ const configFile = layer.configFile ?? loaded.configFile;
13
+ const configDir = configFile == null ? undefined : path.dirname(configFile);
14
+ scripts[name] ??= {
15
+ command,
16
+ configDir,
17
+ configFile,
18
+ };
19
+ }
20
+ }
21
+
22
+ return {
23
+ scripts,
24
+ };
25
+ }
@@ -0,0 +1,9 @@
1
+ import { ManagedScriptCommand } from '../type.js';
2
+ import { execute, type ExecuteCommandParameters } from './execute.js';
3
+
4
+ export async function runScript(options: ExecuteCommandParameters<ManagedScriptCommand.RunScript>) {
5
+ return execute({
6
+ _: 'RunScript',
7
+ ...options,
8
+ });
9
+ }
@@ -0,0 +1,8 @@
1
+ import { runScript } from './ManagedScript/runScript.js';
2
+
3
+ /**
4
+ * @namespace
5
+ */
6
+ export const ManagedScript = Object.freeze({
7
+ runScript,
8
+ });