symlx 0.1.4 → 0.1.7

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.
@@ -0,0 +1,169 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.serveCommand = serveCommand;
40
+ const path_1 = __importDefault(require("path"));
41
+ const node_os_1 = __importDefault(require("node:os"));
42
+ const log = __importStar(require("../ui/logger"));
43
+ const utils_1 = require("../lib/utils");
44
+ const link_manager_1 = require("../lib/link-manager");
45
+ const bin_targets_1 = require("../lib/bin-targets");
46
+ const lifecycle_1 = require("../lib/lifecycle");
47
+ const session_store_1 = require("../lib/session-store");
48
+ const prompts_1 = require("../ui/prompts");
49
+ const options_1 = require("../lib/options");
50
+ const schema_1 = require("../lib/schema");
51
+ // Prompts require an interactive terminal; scripts/CI should avoid prompt mode.
52
+ function isInteractiveSession() {
53
+ return Boolean(process.stdin.isTTY && process.stdout.isTTY);
54
+ }
55
+ function prepareRuntimeDirectories(binDirectory, sessionDirectory) {
56
+ (0, session_store_1.ensureSymlxDirectories)(binDirectory, sessionDirectory);
57
+ (0, session_store_1.cleanupStaleSessions)(sessionDirectory);
58
+ }
59
+ function resolveRuntimeCollisionMode(options) {
60
+ if (options.collision !== 'prompt') {
61
+ return { policy: options.collision };
62
+ }
63
+ const canPromptForCollision = !options.nonInteractive && isInteractiveSession();
64
+ if (canPromptForCollision) {
65
+ return {
66
+ policy: 'prompt',
67
+ resolver: prompts_1.promptCollisionDecision,
68
+ };
69
+ }
70
+ log.warn('prompt collision mode requested but session is non-interactive; falling back to skip (use --collision overwrite|fail to avoid skips)');
71
+ return { policy: 'skip' };
72
+ }
73
+ function buildServeRuntime(options) {
74
+ const currentWorkingDirectory = process.cwd();
75
+ const sessionDirectory = path_1.default.join(node_os_1.default.homedir(), '.symlx', 'sessions');
76
+ prepareRuntimeDirectories(options.binDir, sessionDirectory);
77
+ (0, bin_targets_1.assertValidBinTargets)(options.bin);
78
+ return {
79
+ cwd: currentWorkingDirectory,
80
+ options,
81
+ sessionDirectory,
82
+ bins: new Map(Object.entries(options.bin)),
83
+ collisionMode: resolveRuntimeCollisionMode(options),
84
+ };
85
+ }
86
+ async function createRuntimeLinks(runtime) {
87
+ return (0, link_manager_1.createLinks)({
88
+ bins: runtime.bins,
89
+ binDir: runtime.options.binDir,
90
+ policy: runtime.collisionMode.policy,
91
+ collisionResolver: runtime.collisionMode.resolver,
92
+ });
93
+ }
94
+ function formatSkippedLinks(skippedLinks) {
95
+ const maxVisibleSkips = 5;
96
+ const visibleSkips = skippedLinks.slice(0, maxVisibleSkips);
97
+ const visibleSkipLines = visibleSkips
98
+ .map((skip) => `- ${skip.name}: ${skip.reason}`)
99
+ .join('\n');
100
+ const hiddenSkipsCount = skippedLinks.length - maxVisibleSkips;
101
+ const hiddenSkipsLine = hiddenSkipsCount > 0 ? `\n- ...and ${hiddenSkipsCount} more` : '';
102
+ return `${visibleSkipLines}${hiddenSkipsLine}`;
103
+ }
104
+ function assertLinkCreationSucceeded(linkResult) {
105
+ if (linkResult.created.length > 0) {
106
+ return;
107
+ }
108
+ if (linkResult.skipped.length === 0) {
109
+ throw new Error('no links were created');
110
+ }
111
+ throw new Error([
112
+ 'no links were created because all candidate commands were skipped.',
113
+ formatSkippedLinks(linkResult.skipped),
114
+ 'use --collision overwrite or --collision fail for stricter behavior.',
115
+ ].join('\n'));
116
+ }
117
+ function persistServeSession(runtime, links) {
118
+ const sessionPath = (0, session_store_1.createSessionFilePath)(runtime.sessionDirectory);
119
+ const record = {
120
+ pid: process.pid,
121
+ cwd: runtime.cwd,
122
+ createdAt: new Date().toISOString(),
123
+ links,
124
+ };
125
+ (0, session_store_1.persistSession)(sessionPath, record);
126
+ return { sessionPath, record };
127
+ }
128
+ function registerServeSessionCleanup(session) {
129
+ (0, lifecycle_1.registerLifecycleCleanup)(() => {
130
+ (0, session_store_1.cleanupSession)(session.sessionPath, session.record.links);
131
+ });
132
+ }
133
+ function reportLinkCreation(runtime, linkResult) {
134
+ const createdLinks = linkResult.created;
135
+ log.info(`linked ${createdLinks.length} command${createdLinks.length > 1 ? 's' : ''} into ${runtime.options.binDir}`);
136
+ for (const link of createdLinks) {
137
+ log.info(`${link.name} -> ${link.target}`);
138
+ }
139
+ for (const skippedLink of linkResult.skipped) {
140
+ log.warn(`skip "${skippedLink.name}": ${skippedLink.reason} (${skippedLink.linkPath})`);
141
+ }
142
+ }
143
+ function reportPathHint(binDirectory) {
144
+ if ((0, utils_1.pathContainsDir)(process.env.PATH, binDirectory)) {
145
+ return;
146
+ }
147
+ log.info(`add this to your shell config if needed:\nexport PATH="${binDirectory}:$PATH"`);
148
+ }
149
+ function waitUntilProcessExit() {
150
+ return new Promise(() => {
151
+ setInterval(() => undefined, 60_000);
152
+ });
153
+ }
154
+ async function run(options) {
155
+ const runtime = buildServeRuntime(options);
156
+ const linkResult = await createRuntimeLinks(runtime);
157
+ assertLinkCreationSucceeded(linkResult);
158
+ const session = persistServeSession(runtime, linkResult.created);
159
+ registerServeSessionCleanup(session);
160
+ reportLinkCreation(runtime, linkResult);
161
+ reportPathHint(runtime.options.binDir);
162
+ log.info('running. press Ctrl+C to cleanup links.');
163
+ await waitUntilProcessExit();
164
+ }
165
+ function serveCommand(inlineOptions) {
166
+ const currentWorkingDirectory = process.cwd();
167
+ const options = (0, options_1.resolveOptions)(currentWorkingDirectory, schema_1.serveInlineOptionsSchema, inlineOptions);
168
+ return run(options);
169
+ }
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.assertValidBinTargets = assertValidBinTargets;
6
+ exports.prepareBinTargets = prepareBinTargets;
7
7
  const node_fs_1 = __importDefault(require("node:fs"));
8
8
  function isExecutable(filePath) {
9
9
  if (process.platform === 'win32') {
@@ -17,6 +17,23 @@ function isExecutable(filePath) {
17
17
  return false;
18
18
  }
19
19
  }
20
+ function ensureExecutable(filePath, currentMode) {
21
+ if (process.platform === 'win32' || isExecutable(filePath)) {
22
+ return undefined;
23
+ }
24
+ const executeBits = (currentMode & 0o444) >> 2;
25
+ const nextMode = (currentMode | executeBits) & 0o777;
26
+ try {
27
+ node_fs_1.default.chmodSync(filePath, nextMode);
28
+ }
29
+ catch (error) {
30
+ return `target permissions could not be updated (${String(error)})`;
31
+ }
32
+ if (isExecutable(filePath)) {
33
+ return undefined;
34
+ }
35
+ return 'target permissions could not be updated';
36
+ }
20
37
  function inspectBinTarget(name, target) {
21
38
  if (!node_fs_1.default.existsSync(target)) {
22
39
  return {
@@ -43,11 +60,12 @@ function inspectBinTarget(name, target) {
43
60
  reason: 'target is a directory',
44
61
  };
45
62
  }
46
- if (!isExecutable(target)) {
63
+ const executableIssue = ensureExecutable(target, stats.mode);
64
+ if (executableIssue) {
47
65
  return {
48
66
  name,
49
67
  target,
50
- reason: 'target is not executable',
68
+ reason: executableIssue,
51
69
  hint: `run: chmod +x ${target}`,
52
70
  };
53
71
  }
@@ -61,7 +79,7 @@ function formatIssues(issues) {
61
79
  })
62
80
  .join('\n');
63
81
  }
64
- function assertValidBinTargets(bin) {
82
+ function prepareBinTargets(bin) {
65
83
  const issues = [];
66
84
  for (const [name, target] of Object.entries(bin)) {
67
85
  const issue = inspectBinTarget(name, target);
@@ -75,6 +93,6 @@ function assertValidBinTargets(bin) {
75
93
  throw new Error([
76
94
  'invalid bin targets:',
77
95
  formatIssues(issues),
78
- 'fix bin paths/permissions in package.json, symlx.config.json, or inline --bin and run again.',
96
+ 'fix bin paths or file permissions in package.json, symlx.config.json, or inline --bin and run again.',
79
97
  ].join('\n'));
80
98
  }
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PROMPT_FALLBACK_WARNING = void 0;
4
+ exports.PROMPT_FALLBACK_WARNING = 'prompt collision mode requested but session is non-interactive; falling back to skip (use --collision overwrite|fail to avoid skips)';
@@ -4,8 +4,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.createLinks = createLinks;
7
+ exports.assertLinksCreated = assertLinksCreated;
7
8
  const node_fs_1 = __importDefault(require("node:fs"));
8
9
  const node_path_1 = __importDefault(require("node:path"));
10
+ const prompts_1 = require("../ui/prompts");
9
11
  // lstat wrapper that treats missing files as "not found" but rethrows real IO errors.
10
12
  function tryLstat(filePath) {
11
13
  try {
@@ -69,13 +71,15 @@ function toConflict(name, linkPath, target, node) {
69
71
  }
70
72
  // Creates symlinks for all project bins according to the selected collision strategy.
71
73
  // This function is pure with regard to policy: caller decides interactive vs non-interactive.
72
- async function createLinks(params) {
73
- const { bins, binDir, policy, collisionResolver } = params;
74
+ async function createLinks(bins, binDir, collisionOption) {
74
75
  const created = [];
75
76
  const skipped = [];
76
- for (const [name, target] of bins.entries()) {
77
+ // Link every executable in the bin options
78
+ for (const [name, target] of Object.entries(bins)) {
77
79
  const linkPath = node_path_1.default.join(binDir, name);
80
+ // check is there's an existing binary on the device
78
81
  const existingNode = inspectExistingNode(linkPath);
82
+ // If there's a conflicting binary, handle the conflict
79
83
  if (existingNode) {
80
84
  const conflict = toConflict(name, linkPath, target, existingNode);
81
85
  // Reusing the exact same link is always a no-op.
@@ -88,25 +92,21 @@ async function createLinks(params) {
88
92
  });
89
93
  continue;
90
94
  }
91
- let decision;
92
- if (policy === 'skip') {
93
- decision = 'skip';
94
- }
95
- else if (policy === 'overwrite') {
96
- decision = 'overwrite';
97
- }
98
- else if (policy === 'fail') {
95
+ if (collisionOption === 'fail') {
99
96
  throw new Error(`command "${name}" conflicts at ${linkPath}: ${conflict.reason}`);
100
97
  }
101
- else {
102
- decision = collisionResolver
103
- ? await collisionResolver(conflict)
104
- : 'skip';
98
+ let collisionDecision;
99
+ if (collisionOption === 'prompt') {
100
+ collisionDecision = await (0, prompts_1.promptCollisionResolver)(conflict);
101
+ if (collisionDecision === 'abort') {
102
+ throw new Error(`aborted on collision for command "${name}"`);
103
+ }
105
104
  }
106
- if (decision === 'abort') {
107
- throw new Error(`aborted on collision for command "${name}"`);
105
+ else {
106
+ // After here, resulting decision can only either be 'skip' or 'overwrite'
107
+ collisionDecision = collisionOption;
108
108
  }
109
- if (decision === 'skip') {
109
+ if (collisionDecision === 'skip') {
110
110
  skipped.push({ name, linkPath, reason: conflict.reason });
111
111
  continue;
112
112
  }
@@ -117,3 +117,22 @@ async function createLinks(params) {
117
117
  }
118
118
  return { created, skipped };
119
119
  }
120
+ function assertLinksCreated(linkResult) {
121
+ if (linkResult.created.length > 0) {
122
+ return;
123
+ }
124
+ if (linkResult.skipped.length === 0) {
125
+ throw new Error('no links were created');
126
+ }
127
+ const details = linkResult.skipped
128
+ .slice(0, 5)
129
+ .map((skip) => `- ${skip.name}: ${skip.reason}`)
130
+ .join('\n');
131
+ const remainingCount = linkResult.skipped.length - 5;
132
+ const remaining = remainingCount > 0 ? `\n- ...and ${remainingCount} more` : '';
133
+ throw new Error([
134
+ 'no links were created because all candidate commands were skipped.',
135
+ details,
136
+ `${remaining}\nuse --collision overwrite or --collision fail for stricter behavior.`,
137
+ ].join('\n'));
138
+ }
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.assertLinksCreated = assertLinksCreated;
4
+ function assertLinksCreated(linkResult) {
5
+ if (linkResult.created.length > 0) {
6
+ return;
7
+ }
8
+ if (linkResult.skipped.length === 0) {
9
+ throw new Error('no links were created');
10
+ }
11
+ const details = linkResult.skipped
12
+ .slice(0, 5)
13
+ .map((skip) => `- ${skip.name}: ${skip.reason}`)
14
+ .join('\n');
15
+ const remainingCount = linkResult.skipped.length - 5;
16
+ const remaining = remainingCount > 0 ? `\n- ...and ${remainingCount} more` : '';
17
+ throw new Error([
18
+ 'no links were created because all candidate commands were skipped.',
19
+ details,
20
+ `${remaining}\nuse --collision overwrite or --collision fail for stricter behavior.`,
21
+ ].join('\n'));
22
+ }
@@ -1,11 +1,46 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
2
35
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
37
  };
5
38
  Object.defineProperty(exports, "__esModule", { value: true });
6
39
  exports.resolveOptions = resolveOptions;
40
+ exports.resolveInternalCollisionOption = resolveInternalCollisionOption;
7
41
  const path_1 = __importDefault(require("path"));
8
42
  const node_os_1 = __importDefault(require("node:os"));
43
+ const log = __importStar(require("../ui/logger"));
9
44
  const utils_1 = require("./utils");
10
45
  const validator_1 = require("./validator");
11
46
  const DEFAULT_OPTIONS = {
@@ -44,6 +79,9 @@ function withCwdPrefixedBin(cwd, bin) {
44
79
  path_1.default.resolve(cwd, target),
45
80
  ]));
46
81
  }
82
+ function isInteractiveSession() {
83
+ return Boolean(process.stdin.isTTY && process.stdout.isTTY);
84
+ }
47
85
  // Function to aggregate all options from different sources in order or priority
48
86
  function resolveOptions(cwd, inlineOptionsSchema, inlineOptions) {
49
87
  const packageJSONLoadResult = (0, utils_1.loadPackageJSONOptions)(cwd);
@@ -52,14 +90,7 @@ function resolveOptions(cwd, inlineOptionsSchema, inlineOptions) {
52
90
  ...packageJSONLoadResult.issues,
53
91
  ...validatedPackageJSONOptions.issues,
54
92
  ];
55
- const fatalPackageIssue = packageJSONIssues.find((issue) => issue.startsWith('invalid package.json'));
56
- if (fatalPackageIssue) {
57
- throw new Error(fatalPackageIssue);
58
- }
59
93
  const configFileLoadResult = (0, utils_1.loadConfigFileOptions)(cwd);
60
- if (configFileLoadResult.issue) {
61
- throw new Error(configFileLoadResult.issue);
62
- }
63
94
  const validatedConfigFileOptions = (0, validator_1.validateConfigFileOptions)(configFileLoadResult.options);
64
95
  const validatedInlineOptions = (0, validator_1.validateInlineOptions)(inlineOptionsSchema, inlineOptions);
65
96
  const inlineBin = validatedInlineOptions
@@ -76,8 +107,16 @@ function resolveOptions(cwd, inlineOptionsSchema, inlineOptions) {
76
107
  bin: withCwdPrefixedBin(cwd, resolvedBin),
77
108
  };
78
109
  if (Object.keys(finalOptions.bin).length > 0) {
110
+ if (finalOptions.binResolutionStrategy === 'merge' &&
111
+ packageJSONIssues.length > 0) {
112
+ log.warn([
113
+ 'bin resolution strategy is merge, but could not resolve bin from package.json:',
114
+ ...packageJSONIssues,
115
+ ].join('\n'));
116
+ }
79
117
  return finalOptions;
80
118
  }
119
+ // only throw package.json error if no bin was resolved
81
120
  const primaryIssue = packageJSONIssues[0];
82
121
  if (primaryIssue) {
83
122
  throw new Error(primaryIssue);
@@ -90,3 +129,12 @@ function resolveOptions(cwd, inlineOptionsSchema, inlineOptions) {
90
129
  '3) inline CLI -> symlx serve --bin my-cli=./cli.js',
91
130
  ].join('\n'));
92
131
  }
132
+ function resolveInternalCollisionOption(collisionOptions, nonInteractiveOptions) {
133
+ if (collisionOptions !== 'prompt') {
134
+ return collisionOptions;
135
+ }
136
+ if (nonInteractiveOptions || !isInteractiveSession()) {
137
+ return 'skip';
138
+ }
139
+ return 'prompt';
140
+ }
@@ -56,6 +56,7 @@ const binEntriesToRecordSchema = zod_1.z
56
56
  const [name, target] = entry.split('=', 2);
57
57
  return [name, target];
58
58
  })));
59
+ const collisionOptionEnum = zod_1.z.enum(['prompt', 'skip', 'fail', 'overwrite']);
59
60
  // -------------------------------------------
60
61
  // package.json Schema: Just bin for now
61
62
  // -------------------------------------------
@@ -71,10 +72,7 @@ const configFileOptionsSchema = zod_1.z.object({
71
72
  .string()
72
73
  .regex(/(^|[\\/])\.[^\\/]+([\\/]|$)/, 'binDir must include a dotted folder segment')
73
74
  .optional(),
74
- collision: zod_1.z
75
- .enum(['prompt', 'skip', 'fail', 'overwrite'])
76
- .optional()
77
- .catch(() => {
75
+ collision: collisionOptionEnum.optional().catch(() => {
78
76
  log.warn('invalid "collision" value in config file; using default.');
79
77
  return undefined;
80
78
  }),
@@ -0,0 +1,81 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.startServeSession = startServeSession;
7
+ const node_path_1 = __importDefault(require("node:path"));
8
+ function resolveCollisionSummary(options, dependencies) {
9
+ if (options.collision !== 'prompt') {
10
+ return {
11
+ requested: options.collision,
12
+ effective: options.collision,
13
+ };
14
+ }
15
+ const shouldFallbackToSkip = options.nonInteractive || !dependencies.isInteractiveSession();
16
+ if (!shouldFallbackToSkip) {
17
+ return {
18
+ requested: options.collision,
19
+ effective: 'prompt',
20
+ };
21
+ }
22
+ return {
23
+ requested: options.collision,
24
+ effective: 'skip',
25
+ warning: 'prompt collision mode requested but session is non-interactive; falling back to skip (use --collision overwrite|fail to avoid skips)',
26
+ };
27
+ }
28
+ function formatSkippedLinks(skippedLinks) {
29
+ const visibleSkippedLinks = skippedLinks.slice(0, 5);
30
+ const details = visibleSkippedLinks
31
+ .map((skip) => `- ${skip.name}: ${skip.reason}`)
32
+ .join('\n');
33
+ const remainingCount = skippedLinks.length - visibleSkippedLinks.length;
34
+ const remaining = remainingCount > 0 ? `\n- ...and ${remainingCount} more` : '';
35
+ return `${details}${remaining}`;
36
+ }
37
+ function assertLinksCreated(linkResult) {
38
+ if (linkResult.created.length > 0) {
39
+ return;
40
+ }
41
+ if (linkResult.skipped.length === 0) {
42
+ throw new Error('no links were created');
43
+ }
44
+ throw new Error([
45
+ 'no links were created because all candidate commands were skipped.',
46
+ formatSkippedLinks(linkResult.skipped),
47
+ 'use --collision overwrite or --collision fail for stricter behavior.',
48
+ ].join('\n'));
49
+ }
50
+ async function startServeSession(params) {
51
+ const { options, dependencies, promptCollisionResolver } = params;
52
+ const currentWorkingDirectory = dependencies.resolveWorkingDirectory();
53
+ const homeDirectory = dependencies.resolveHomeDirectory();
54
+ const sessionDirectory = node_path_1.default.join(homeDirectory, '.symlx', 'sessions');
55
+ const collision = resolveCollisionSummary(options, dependencies);
56
+ dependencies.cleanupStaleSessions(sessionDirectory);
57
+ dependencies.ensureDirectories(options.binDir, sessionDirectory);
58
+ dependencies.assertValidBinTargets(options.bin);
59
+ const linkResult = await dependencies.createLinks({
60
+ bins: options.bin,
61
+ binDir: options.binDir,
62
+ policy: collision.effective,
63
+ collisionResolver: collision.effective === 'prompt' ? promptCollisionResolver : undefined,
64
+ });
65
+ assertLinksCreated(linkResult);
66
+ const sessionPath = dependencies.createSessionFilePath(sessionDirectory);
67
+ const sessionRecord = {
68
+ pid: dependencies.resolveProcessId(),
69
+ cwd: currentWorkingDirectory,
70
+ createdAt: dependencies.resolveTimestamp(),
71
+ links: linkResult.created,
72
+ };
73
+ dependencies.persistSession(sessionPath, sessionRecord);
74
+ dependencies.registerLifecycleCleanup(() => {
75
+ dependencies.cleanupSession(sessionPath, sessionRecord.links);
76
+ });
77
+ return {
78
+ collision,
79
+ waitUntilStopped: dependencies.waitUntilStopped,
80
+ };
81
+ }
@@ -36,11 +36,13 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
36
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.cleanupLinks = cleanupLinks;
39
40
  exports.ensureSymlxDirectories = ensureSymlxDirectories;
40
41
  exports.cleanupStaleSessions = cleanupStaleSessions;
42
+ exports.generateSessionFilePath = generateSessionFilePath;
43
+ exports.generateSessionRecord = generateSessionRecord;
41
44
  exports.persistSession = persistSession;
42
- exports.createSessionFilePath = createSessionFilePath;
43
- exports.cleanupSession = cleanupSession;
45
+ exports.registerLifecycleSessionCleanup = registerLifecycleSessionCleanup;
44
46
  const node_fs_1 = __importDefault(require("node:fs"));
45
47
  const node_path_1 = __importDefault(require("node:path"));
46
48
  const log = __importStar(require("../ui/logger"));
@@ -120,17 +122,54 @@ function cleanupStaleSessions(sessionDir) {
120
122
  log.info(`cleaned up ${cleanUpCount} expired session${cleanUpCount > 1 ? 's' : ''}`);
121
123
  }
122
124
  }
123
- // Persists currently linked commands so future runs can clean stale state.
124
- function persistSession(sessionPath, record) {
125
- node_fs_1.default.writeFileSync(sessionPath, `${JSON.stringify(record, null, 2)}\n`, 'utf8');
126
- }
127
125
  // Produces unique session file names to avoid collisions across concurrent runs.
128
- function createSessionFilePath(sessionDir) {
126
+ function generateSessionFilePath(sessionDir) {
129
127
  const unique = `${Date.now()}-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
130
128
  return node_path_1.default.join(sessionDir, `${unique}.json`);
131
129
  }
132
- // Cleanup for the active process/session.
133
- function cleanupSession(sessionPath, links) {
134
- cleanupLinks(links);
135
- (0, utils_1.deleteFile)(sessionPath);
130
+ function generateSessionRecord(cwd, links) {
131
+ return {
132
+ pid: process.pid,
133
+ cwd,
134
+ createdAt: new Date().toISOString(),
135
+ links,
136
+ };
137
+ }
138
+ // Persists currently linked commands so future runs can clean stale state.
139
+ function persistSession(sessionPath, record) {
140
+ node_fs_1.default.writeFileSync(sessionPath, `${JSON.stringify(record, null, 2)}\n`, 'utf8');
141
+ }
142
+ // Registers robust process-exit handling so linked commands are removed reliably.
143
+ // Cleanup is idempotent and can be triggered by normal exit, signals, or fatal errors.
144
+ function registerLifecycleSessionCleanup(sessionPath, links) {
145
+ let cleaned = false;
146
+ const runCleanup = () => {
147
+ if (cleaned) {
148
+ return;
149
+ }
150
+ cleaned = true;
151
+ cleanupLinks(links);
152
+ (0, utils_1.deleteFile)(sessionPath);
153
+ };
154
+ // Normal termination path.
155
+ process.on('exit', runCleanup);
156
+ const onSignal = () => {
157
+ runCleanup();
158
+ process.exit(0);
159
+ };
160
+ // Common interactive stop signals.
161
+ process.on('SIGINT', onSignal);
162
+ process.on('SIGTERM', onSignal);
163
+ process.on('SIGHUP', onSignal);
164
+ // Fatal process events still attempt cleanup before exiting with failure.
165
+ process.on('uncaughtException', (error) => {
166
+ process.stderr.write(`[symlx] uncaught exception: ${String(error)}\n`);
167
+ runCleanup();
168
+ process.exit(1);
169
+ });
170
+ process.on('unhandledRejection', (reason) => {
171
+ process.stderr.write(`[symlx] unhandled rejection: ${String(reason)}\n`);
172
+ runCleanup();
173
+ process.exit(1);
174
+ });
136
175
  }
package/dist/lib/utils.js CHANGED
@@ -43,8 +43,9 @@ function loadConfigFileOptions(cwd) {
43
43
  return {};
44
44
  }
45
45
  const result = readJSONFileWithIssue(configPath, 'symlx.config.json');
46
+ // throw error if there were file reading issues
46
47
  if (result.issue) {
47
- return { issue: result.issue };
48
+ throw new Error(result.issue);
48
49
  }
49
50
  return { options: result.data };
50
51
  }
@@ -20,6 +20,8 @@ function validatePackageJSONOptions(input) {
20
20
  }
21
21
  return { ...result.data, issues: [] };
22
22
  }
23
+ // it's better ux/dx to throw if there's an error in the config file
24
+ // provided it's available than falling back to defaults and leaving the user guessing
23
25
  function validateConfigFileOptions(input, label = 'input') {
24
26
  const result = schema_1.configFileOptionsSchema.safeParse(input || {});
25
27
  if (!result.success) {