@b12k/porto 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bogdan Kolesnyk
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,93 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <img src="./porto.png" alt="Porto banner with a tree formed from Ethernet cables" />
3
+ </p>
2
4
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
5
+ # 🌳 :porto
6
+
7
+ Porto reserves TCP port blocks for Git checkouts and worktrees.
8
+
9
+ ## 🚀 Start
10
+
11
+ Install Node.js 24 or later and Git 2.36 or later.
12
+
13
+ ```sh
14
+ pnpm add -D @b12k/porto
15
+ pnpm exec porto --vars API_PORT --env
16
+ ```
17
+
18
+ Porto writes `API_PORT` to `.env`. Run the same command again to reuse the block.
19
+
20
+ | Worktree | Block | Ports |
21
+ | -------- | ----: | ----------- |
22
+ | Main | 0 | 10000–10009 |
23
+ | Feature | 1 | 10010–10019 |
24
+
25
+ ## 🖥️ Commands
26
+
27
+ Run each command with `pnpm exec porto`. `reserve` is the default command.
28
+
29
+ | Command | Action |
30
+ | --------- | --------------------------------------------------------- |
31
+ | `reserve` | Reserve a block and print its index or variables. |
32
+ | `current` | Show the blocks for this checkout. |
33
+ | `stats` | Show all reservations for this repository. |
34
+ | `release` | Release this checkout's blocks when their ports are free. |
35
+ | `cleanup` | Remove expired reservations when their ports are free. |
36
+
37
+ | `reserve` option | Action |
38
+ | --------------------------------------- | ------------------------------------------------------------ |
39
+ | `--start <port>` | Set the first port of the range. Default `10000`. |
40
+ | `--host <host>` | Check this host for busy ports. Default local addresses. |
41
+ | `--size <count>` | Set the ports per block. Default `10`. |
42
+ | `--idle <minutes>` | Set the idle time limit. Default `60`. |
43
+ | `--keep` / `--no-keep` | Turn idle cleanup off or on for the block. |
44
+ | `--vars <entries>` / `--no-vars` | Set or clear the variable list. |
45
+ | `--env` / `--no-env` | Turn env file output on or off. Default off. File `.env`. |
46
+ | `--env-file <file>` | Set the env file path and turn on env output. |
47
+ | `--json-file <file>` / `--no-json-file` | Set or clear the JSON output file. |
48
+ | `--json` | Print JSON to stdout. Also works with `current` and `stats`. |
49
+
50
+ Use `-h` or `--help` for help. Use `-V` or `--version` for the version.
51
+
52
+ Separate `--vars` entries with `;`. Use `NAME` for a port or `NAME:template` for text. Templates accept `{{block}}` and `{{port}}`.
53
+
54
+ With no variables, `--env` writes `PORTO_BLOCK`.
55
+
56
+ ## ⚙️ Config
57
+
58
+ Create `porto.config.ts` or `porto.config.js` in your checkout. Porto searches from the current directory to the checkout root. If both files are in one directory, Porto uses the TypeScript file.
59
+
60
+ CLI options override config values. Config values override defaults.
61
+
62
+ Set `host` in config or use `--host` to check a specific address. Porto saves it for `release` and `cleanup`.
63
+
64
+ ```ts
65
+ import { defineConfig } from '@b12k/porto';
66
+
67
+ export default defineConfig({
68
+ envFile: '.env.local',
69
+ vars: ['API_PORT', { WEB_URL: (_block, port) => `http://localhost:${port}` }],
70
+ onReserved(block, ports) {
71
+ console.error(`Block ${block.index} has ports ${ports.join(', ')}`);
72
+ },
73
+ });
74
+ ```
75
+
76
+ Relative paths in config start at the config directory. Relative paths in flags start at the current directory.
77
+
78
+ Each variable selects a port by position. A function receives the block index, port, and zero-based variable index.
79
+
80
+ A hook receives the block and its assigned ports. `onReserved` runs after file output. `onReleased` runs once per freed block. Porto runs release hooks in parallel.
81
+
82
+ ## 📦 API
83
+
84
+ ```js
85
+ import { reserve } from '@b12k/porto';
86
+
87
+ const block = await reserve({ vars: ['API_PORT'] });
88
+ const apiPort = block.getPort();
89
+ ```
90
+
91
+ The API also provides `current`, `stats`, `release`, and `cleanup`.
92
+
93
+ Porto stores reservations in `<git-common-dir>/porto-registry.json`.
@@ -0,0 +1,11 @@
1
+ import { PortoError } from './error.js';
2
+ export declare class BusyPortsError extends PortoError {
3
+ readonly ports: Array<{
4
+ block: number;
5
+ port: number;
6
+ }>;
7
+ constructor(ports: Array<{
8
+ block: number;
9
+ port: number;
10
+ }>);
11
+ }
@@ -0,0 +1,10 @@
1
+ import { PortoError } from "./error.js";
2
+ class BusyPortsError extends PortoError {
3
+ ports;
4
+ constructor(ports){
5
+ super('portsBusy');
6
+ this.name = 'BusyPortsError';
7
+ this.ports = ports;
8
+ }
9
+ }
10
+ export { BusyPortsError };
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,116 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from "commander";
3
+ import { pickBy } from "es-toolkit";
4
+ import update_notifier from "update-notifier";
5
+ import { applyReserveDefaults, fetchConfig, name as external_config_js_name, parseConfig, version } from "./config.js";
6
+ import { fetchGitContext } from "./git.js";
7
+ import { BusyPortsError, PortoError, cleanup, current, release, stats } from "./index.js";
8
+ import { logError } from "./log.js";
9
+ import { fetchExportPaths, formatReserveOutput, formatStatsTable, formatTable, updateEnvironmentFile, writeReserveJsonFile } from "./output.js";
10
+ import { reserveBlock } from "./reserve.js";
11
+ import { mapBlockToVars, parseVars } from "./vars.js";
12
+ async function fetchSettings(flags, command, worktree) {
13
+ const configured = await fetchConfig(worktree);
14
+ const { idle, json, vars, ...overrides } = pickBy(flags, (_flag, key)=>'cli' === command.getOptionValueSource(key));
15
+ const explicit = parseConfig({
16
+ ...overrides,
17
+ ...void 0 === idle ? {} : {
18
+ idleTtlMinutes: idle
19
+ }
20
+ });
21
+ let entries = configured.vars;
22
+ if (void 0 !== vars) entries = false === vars ? void 0 : parseVars(vars);
23
+ return {
24
+ ...applyReserveDefaults({
25
+ ...configured,
26
+ ...explicit,
27
+ vars: entries
28
+ }),
29
+ json: json ?? false
30
+ };
31
+ }
32
+ async function runHook(hookName, hook) {
33
+ try {
34
+ await hook();
35
+ } catch (error) {
36
+ throw new PortoError('hookFailed', `${hookName}: ${error instanceof Error ? error.message : String(error)}`, {
37
+ cause: error
38
+ });
39
+ }
40
+ }
41
+ function writeOutput(contents) {
42
+ process.stdout.write(`${contents}\n`);
43
+ }
44
+ async function handleReserve(flags, command) {
45
+ const git = await fetchGitContext();
46
+ const { vars: entries, ...settings } = await fetchSettings(flags, command, git.worktree);
47
+ const { environmentPath, jsonPath } = await fetchExportPaths(settings, git.commonDirectory);
48
+ const prepared = await reserveBlock({
49
+ ...settings,
50
+ git,
51
+ portsCount: entries?.length ?? 0
52
+ }, ({ ports, ...block })=>{
53
+ const environment = void 0 === entries ? void 0 : mapBlockToVars(block, entries);
54
+ return {
55
+ block,
56
+ environment,
57
+ output: formatReserveOutput(block, environment, settings.json),
58
+ ports
59
+ };
60
+ });
61
+ const { block, environment, output, ports } = prepared;
62
+ if (jsonPath) await writeReserveJsonFile(jsonPath, block, environment);
63
+ if (environmentPath) await updateEnvironmentFile(environmentPath, environment ?? {
64
+ PORTO_BLOCK: block.index
65
+ }, git.commonDirectory);
66
+ await runHook('onReserved', ()=>settings.onReserved?.(block, ports));
67
+ writeOutput(output);
68
+ }
69
+ const cli = new Command('porto');
70
+ update_notifier({
71
+ pkg: {
72
+ name: external_config_js_name,
73
+ version: version
74
+ },
75
+ shouldNotifyInNpmScript: true,
76
+ updateCheckInterval: 86400000
77
+ }).notify({
78
+ defer: false
79
+ });
80
+ cli.command('reserve', {
81
+ isDefault: true
82
+ }).description('Reserve a stable TCP port block for the current checkout').option('--start <port>', 'First port of the range (default: 10000)', Number).option('--host <host>', 'Host to check for busy ports (default: detect local addresses)').option('--size <count>', 'Number of ports in each block (default: 10)', Number).option('--idle <minutes>', 'Idle TTL in minutes (default: 60)', Number).option('--vars <entries>', 'Semicolon-separated NAME or NAME:template variables').option('--no-vars', 'Ignore configured variables').option('--json', 'Print JSON to stdout').option('--json-file <file>', 'Save JSON to a file independently of stdout').option('--no-json-file', 'Skip the configured JSON file').option('--env', 'Update the env file (default: disabled)').option('--no-env', 'Skip the env file').option('--env-file <file>', 'Set the env filename and enable env output (default: .env)').option('--keep', 'Keep this reservation until explicitly released').option('--no-keep', 'Restore idle cleanup for this reservation').action(handleReserve);
83
+ cli.command('current').description('Read the reservations of the current checkout').option('--json', 'Print JSON to stdout').action(async (flags)=>{
84
+ const blocks = await current();
85
+ if (0 === blocks.length) throw new PortoError('reservationNotFound');
86
+ writeOutput(flags.json ? JSON.stringify(1 === blocks.length ? blocks[0] : blocks) : blocks.map((block)=>block.index).join('\n'));
87
+ });
88
+ cli.command('stats').description('List all reservations in this repository').option('--json', 'Print JSON to stdout').action(async (flags)=>{
89
+ const reservations = await stats();
90
+ writeOutput(flags.json ? JSON.stringify(reservations) : formatStatsTable(reservations));
91
+ });
92
+ cli.command('release').description('Release current checkout reservations if every port is free').action(async ()=>{
93
+ const { worktree } = await fetchGitContext();
94
+ const { onReleased } = await fetchConfig(worktree);
95
+ const blocks = await release();
96
+ const results = await Promise.allSettled(blocks.map(({ ports, ...block })=>runHook('onReleased', ()=>onReleased?.(block, ports))));
97
+ const failure = results.find((result)=>'rejected' === result.status);
98
+ if (failure) throw failure.reason;
99
+ });
100
+ cli.command('cleanup').description('Remove idle reservations whose ports are all free').action(async ()=>{
101
+ await cleanup();
102
+ });
103
+ cli.version(version);
104
+ try {
105
+ await cli.parseAsync();
106
+ } catch (error) {
107
+ if (error instanceof BusyPortsError) process.stderr.write(`${formatTable([
108
+ 'BLOCK',
109
+ 'PORT'
110
+ ], error.ports.map(({ block, port })=>[
111
+ String(block),
112
+ String(port)
113
+ ]))}\n`);
114
+ logError(error);
115
+ process.exitCode = 1;
116
+ }
@@ -0,0 +1,72 @@
1
+ import { z } from 'zod';
2
+ declare const DEFAULT_ENV_FILE = ".env";
3
+ declare const CONFIG_SCHEMA: z.ZodObject<{
4
+ onReleased: z.ZodOptional<z.ZodCustom<(block: import("./index.js").PortBlock, ports: Array<number>) => Promise<void> | void, (block: import("./index.js").PortBlock, ports: Array<number>) => Promise<void> | void>>;
5
+ onReserved: z.ZodOptional<z.ZodCustom<(block: import("./index.js").PortBlock, ports: Array<number>) => Promise<void> | void, (block: import("./index.js").PortBlock, ports: Array<number>) => Promise<void> | void>>;
6
+ host: z.ZodOptional<z.ZodOptional<z.ZodString>>;
7
+ idleTtlMinutes: z.ZodOptional<z.ZodNumber>;
8
+ keep: z.ZodOptional<z.ZodOptional<z.ZodBoolean>>;
9
+ size: z.ZodOptional<z.ZodInt>;
10
+ start: z.ZodOptional<z.ZodInt>;
11
+ env: z.ZodOptional<z.ZodBoolean>;
12
+ envFile: z.ZodOptional<z.ZodString>;
13
+ jsonFile: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<false>, z.ZodString]>>;
14
+ vars: z.ZodOptional<z.ZodPipe<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodCustom<Record<string, import("./vars.js").VarFactory>, Record<string, import("./vars.js").VarFactory>>]>>, z.ZodTransform<import("./vars.js").VarEntry[], (string | Record<string, import("./vars.js").VarFactory>)[]>>>;
15
+ }, z.core.$strict>;
16
+ type PortoConfig = z.input<typeof CONFIG_SCHEMA>;
17
+ declare const libraryName = "porto";
18
+ declare const name: string, version: string;
19
+ declare function defineConfig(config: PortoConfig): {
20
+ onReleased?: ((block: import("./index.js").PortBlock, ports: Array<number>) => Promise<void> | void) | undefined;
21
+ onReserved?: ((block: import("./index.js").PortBlock, ports: Array<number>) => Promise<void> | void) | undefined;
22
+ host?: string | undefined;
23
+ idleTtlMinutes?: number | undefined;
24
+ keep?: boolean | undefined;
25
+ size?: number | undefined;
26
+ start?: number | undefined;
27
+ env?: boolean | undefined;
28
+ envFile?: string | undefined;
29
+ jsonFile?: string | false | undefined;
30
+ vars?: (string | Record<string, import("./vars.js").VarFactory>)[] | undefined;
31
+ };
32
+ declare function parseConfig(config: unknown): {
33
+ onReleased?: ((block: import("./index.js").PortBlock, ports: Array<number>) => Promise<void> | void) | undefined;
34
+ onReserved?: ((block: import("./index.js").PortBlock, ports: Array<number>) => Promise<void> | void) | undefined;
35
+ host?: string | undefined;
36
+ idleTtlMinutes?: number | undefined;
37
+ keep?: boolean | undefined;
38
+ size?: number | undefined;
39
+ start?: number | undefined;
40
+ env?: boolean | undefined;
41
+ envFile?: string | undefined;
42
+ jsonFile?: string | false | undefined;
43
+ vars?: import("./vars.js").VarEntry[] | undefined;
44
+ };
45
+ declare function applyReserveDefaults(settings: ReturnType<typeof parseConfig>): {
46
+ onReleased?: ((block: import("./index.js").PortBlock, ports: Array<number>) => Promise<void> | void) | undefined;
47
+ onReserved?: ((block: import("./index.js").PortBlock, ports: Array<number>) => Promise<void> | void) | undefined;
48
+ host?: string | undefined;
49
+ idleTtlMinutes: number;
50
+ keep?: boolean | undefined;
51
+ size: number;
52
+ start: number;
53
+ vars?: import("./vars.js").VarEntry[] | undefined;
54
+ env: boolean;
55
+ envFile: string;
56
+ jsonFile: string | false;
57
+ };
58
+ declare function fetchConfig(worktree: string): Promise<{
59
+ onReleased?: ((block: import("./index.js").PortBlock, ports: Array<number>) => Promise<void> | void) | undefined;
60
+ onReserved?: ((block: import("./index.js").PortBlock, ports: Array<number>) => Promise<void> | void) | undefined;
61
+ host?: string | undefined;
62
+ idleTtlMinutes?: number | undefined;
63
+ keep?: boolean | undefined;
64
+ size?: number | undefined;
65
+ start?: number | undefined;
66
+ env?: boolean | undefined;
67
+ envFile?: string | undefined;
68
+ jsonFile?: string | false | undefined;
69
+ vars?: import("./vars.js").VarEntry[] | undefined;
70
+ }>;
71
+ export { applyReserveDefaults, DEFAULT_ENV_FILE, defineConfig, fetchConfig, libraryName, name, parseConfig, version };
72
+ export type { PortoConfig };
package/dist/config.js ADDED
@@ -0,0 +1,101 @@
1
+ import { access, realpath } from "node:fs/promises";
2
+ import node_path from "node:path";
3
+ import { z } from "zod";
4
+ import package_0 from "../package.json" with {
5
+ type: "json"
6
+ };
7
+ import { PortoError } from "./error.js";
8
+ import { checkIsFileMissing } from "./files.js";
9
+ import { loadConfigFile } from "./load-config.js";
10
+ import { HOOKS_SCHEMA, OPTIONS_SCHEMA, parseOptions } from "./schemas.js";
11
+ import { VARS_SCHEMA } from "./vars.js";
12
+ const DEFAULT_ENV_FILE = '.env';
13
+ const CONFIG_FILES = [
14
+ 'porto.config.ts',
15
+ 'porto.config.js'
16
+ ];
17
+ const CONFIG_SCHEMA = z.strictObject({
18
+ ...OPTIONS_SCHEMA.shape,
19
+ ...HOOKS_SCHEMA.shape,
20
+ env: z.boolean(),
21
+ envFile: z.string().min(1),
22
+ jsonFile: z.union([
23
+ z.literal(false),
24
+ z.string().min(1)
25
+ ]),
26
+ vars: VARS_SCHEMA
27
+ }).partial();
28
+ const libraryName = 'porto';
29
+ const { name: config_name, version } = package_0;
30
+ function defineConfig(config) {
31
+ return config;
32
+ }
33
+ async function fetchConfigPath(candidates) {
34
+ let configPath;
35
+ for (const filePath of candidates)try {
36
+ await access(filePath);
37
+ configPath = filePath;
38
+ break;
39
+ } catch (error) {
40
+ if (!checkIsFileMissing(error)) throw error;
41
+ }
42
+ return configPath;
43
+ }
44
+ function getConfigPaths(directoryPath, worktreePath) {
45
+ const filePaths = [];
46
+ for(let currentPath = directoryPath;; currentPath = node_path.dirname(currentPath)){
47
+ filePaths.push(...CONFIG_FILES.map((fileName)=>node_path.join(currentPath, fileName)));
48
+ if (currentPath === worktreePath) return filePaths;
49
+ if (node_path.dirname(currentPath) === currentPath) throw new PortoError('configInvalid', 'Cannot find the checkout root.');
50
+ }
51
+ }
52
+ function parseConfig(config) {
53
+ const result = CONFIG_SCHEMA.safeParse(config);
54
+ if (!result.success) {
55
+ const details = result.error.issues.map((issue)=>`${issue.path.join('.')}: ${issue.message}`).join('; ');
56
+ throw new PortoError('configInvalid', details, {
57
+ cause: result.error
58
+ });
59
+ }
60
+ const settings = result.data;
61
+ return {
62
+ ...settings,
63
+ ...void 0 !== settings.envFile && void 0 === settings.env ? {
64
+ env: true
65
+ } : {}
66
+ };
67
+ }
68
+ function applyReserveDefaults(settings) {
69
+ return {
70
+ ...settings,
71
+ ...parseOptions(settings),
72
+ env: settings.env ?? false,
73
+ envFile: settings.envFile ?? DEFAULT_ENV_FILE,
74
+ jsonFile: settings.jsonFile ?? false
75
+ };
76
+ }
77
+ function resolveConfigPaths(config, filePath) {
78
+ const directoryPath = node_path.dirname(filePath);
79
+ for (const key of [
80
+ 'envFile',
81
+ 'jsonFile'
82
+ ]){
83
+ const configuredPath = config[key];
84
+ if ('string' == typeof configuredPath) config[key] = node_path.resolve(directoryPath, configuredPath);
85
+ }
86
+ return config;
87
+ }
88
+ async function fetchConfig(worktree) {
89
+ const candidates = getConfigPaths(await realpath(process.cwd()), worktree);
90
+ const filePath = await fetchConfigPath(candidates);
91
+ if (!filePath) return parseConfig({});
92
+ try {
93
+ const config = await loadConfigFile(filePath);
94
+ return resolveConfigPaths(parseConfig(config), filePath);
95
+ } catch (error) {
96
+ throw new PortoError('configInvalid', `${filePath}: ${error instanceof Error ? error.message : String(error)}`, {
97
+ cause: error
98
+ });
99
+ }
100
+ }
101
+ export { DEFAULT_ENV_FILE, applyReserveDefaults, config_name as name, defineConfig, fetchConfig, libraryName, parseConfig, version };
@@ -0,0 +1,5 @@
1
+ import { ERRORS_BY_KEY } from './errors.js';
2
+ export declare class PortoError extends Error {
3
+ readonly code: keyof typeof ERRORS_BY_KEY;
4
+ constructor(code: keyof typeof ERRORS_BY_KEY, details?: string, options?: ErrorOptions);
5
+ }
package/dist/error.js ADDED
@@ -0,0 +1,13 @@
1
+ import { ERRORS_BY_KEY } from "./errors.js";
2
+ class PortoError extends Error {
3
+ code;
4
+ constructor(code, details, options){
5
+ super([
6
+ ERRORS_BY_KEY[code].message,
7
+ details
8
+ ].filter(Boolean).join(' '), options);
9
+ this.code = code;
10
+ this.name = 'PortoError';
11
+ }
12
+ }
13
+ export { PortoError };
@@ -0,0 +1,46 @@
1
+ export declare const ERRORS_BY_KEY: {
2
+ readonly blockUnavailable: {
3
+ readonly instruction: 'Release unused blocks or choose another range.';
4
+ readonly message: 'No free port block remains in the TCP port range.';
5
+ };
6
+ readonly configInvalid: {
7
+ readonly instruction: 'Check porto.config.ts or porto.config.js.';
8
+ readonly message: 'Invalid Porto configuration.';
9
+ };
10
+ readonly exportInvalid: {
11
+ readonly instruction: 'Check --json-file and --env-file filenames.';
12
+ readonly message: 'Invalid export options.';
13
+ };
14
+ readonly hookFailed: {
15
+ readonly instruction: 'The registry change is already saved. Check the hook in your config.';
16
+ readonly message: 'Lifecycle hook failed.';
17
+ };
18
+ readonly mappingInvalid: {
19
+ readonly instruction: 'Use unique variable names, valid callbacks, and a block large enough for all entries.';
20
+ readonly message: 'Invalid variables.';
21
+ };
22
+ readonly offsetInvalid: {
23
+ readonly instruction: 'Choose an integer offset inside the block.';
24
+ readonly message: 'Invalid port offset.';
25
+ };
26
+ readonly optionsInvalid: {
27
+ readonly instruction: 'Check host, start, size, and idleTtlMinutes.';
28
+ readonly message: 'Invalid reservation options.';
29
+ };
30
+ readonly portsBusy: {
31
+ readonly instruction: 'Stop the services using these ports and try again.';
32
+ readonly message: 'Cannot release reservations while ports are in use.';
33
+ };
34
+ readonly registryInvalid: {
35
+ readonly instruction: 'Restore or repair the reservation file before continuing.';
36
+ readonly message: 'Cannot read reservation.';
37
+ };
38
+ readonly reservationNotFound: {
39
+ readonly instruction: 'Run porto reserve first.';
40
+ readonly message: 'No reservation for the current worktree.';
41
+ };
42
+ readonly worktreeNotFound: {
43
+ readonly instruction: 'Run Porto inside a regular Git checkout or linked worktree.';
44
+ readonly message: 'Porto must run inside a Git working tree.';
45
+ };
46
+ };
package/dist/errors.js ADDED
@@ -0,0 +1,47 @@
1
+ const ERRORS_BY_KEY = {
2
+ blockUnavailable: {
3
+ instruction: 'Release unused blocks or choose another range.',
4
+ message: 'No free port block remains in the TCP port range.'
5
+ },
6
+ configInvalid: {
7
+ instruction: 'Check porto.config.ts or porto.config.js.',
8
+ message: 'Invalid Porto configuration.'
9
+ },
10
+ exportInvalid: {
11
+ instruction: 'Check --json-file and --env-file filenames.',
12
+ message: 'Invalid export options.'
13
+ },
14
+ hookFailed: {
15
+ instruction: 'The registry change is already saved. Check the hook in your config.',
16
+ message: 'Lifecycle hook failed.'
17
+ },
18
+ mappingInvalid: {
19
+ instruction: 'Use unique variable names, valid callbacks, and a block large enough for all entries.',
20
+ message: 'Invalid variables.'
21
+ },
22
+ offsetInvalid: {
23
+ instruction: 'Choose an integer offset inside the block.',
24
+ message: 'Invalid port offset.'
25
+ },
26
+ optionsInvalid: {
27
+ instruction: 'Check host, start, size, and idleTtlMinutes.',
28
+ message: 'Invalid reservation options.'
29
+ },
30
+ portsBusy: {
31
+ instruction: 'Stop the services using these ports and try again.',
32
+ message: 'Cannot release reservations while ports are in use.'
33
+ },
34
+ registryInvalid: {
35
+ instruction: 'Restore or repair the reservation file before continuing.',
36
+ message: 'Cannot read reservation.'
37
+ },
38
+ reservationNotFound: {
39
+ instruction: 'Run porto reserve first.',
40
+ message: 'No reservation for the current worktree.'
41
+ },
42
+ worktreeNotFound: {
43
+ instruction: 'Run Porto inside a regular Git checkout or linked worktree.',
44
+ message: 'Porto must run inside a Git working tree.'
45
+ }
46
+ };
47
+ export { ERRORS_BY_KEY };
@@ -0,0 +1,4 @@
1
+ declare function checkIsFileMissing(error: unknown): boolean;
2
+ declare function fetchCanonicalPath(filePath: string): Promise<string>;
3
+ declare function writeFileAtomically(filePath: string, contents: string): Promise<void>;
4
+ export { checkIsFileMissing, fetchCanonicalPath, writeFileAtomically };
package/dist/files.js ADDED
@@ -0,0 +1,43 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { chmod, readlink, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
3
+ import node_path from "node:path";
4
+ function checkIsFileMissing(error) {
5
+ return error instanceof Error && 'code' in error && 'ENOENT' === error.code;
6
+ }
7
+ async function fetchCanonicalPath(filePath) {
8
+ try {
9
+ return await realpath(filePath);
10
+ } catch (error) {
11
+ if (!checkIsFileMissing(error)) throw error;
12
+ let targetPath = filePath;
13
+ try {
14
+ targetPath = node_path.resolve(node_path.dirname(filePath), await readlink(filePath));
15
+ } catch (linkError) {
16
+ if (!checkIsFileMissing(linkError) && !(linkError instanceof Error && 'code' in linkError && 'EINVAL' === linkError.code)) throw linkError;
17
+ }
18
+ if (targetPath !== filePath) return fetchCanonicalPath(targetPath);
19
+ return node_path.join(await realpath(node_path.dirname(filePath)), node_path.basename(filePath));
20
+ }
21
+ }
22
+ async function writeFileAtomically(filePath, contents) {
23
+ const temporaryPath = `${filePath}.${randomUUID()}.tmp`;
24
+ let mode;
25
+ try {
26
+ ({ mode } = await stat(filePath));
27
+ } catch (error) {
28
+ if (!checkIsFileMissing(error)) throw error;
29
+ }
30
+ try {
31
+ await writeFile(temporaryPath, contents, {
32
+ flag: 'wx',
33
+ mode
34
+ });
35
+ if (void 0 !== mode) await chmod(temporaryPath, mode);
36
+ await rename(temporaryPath, filePath);
37
+ } finally{
38
+ await rm(temporaryPath, {
39
+ force: true
40
+ });
41
+ }
42
+ }
43
+ export { checkIsFileMissing, fetchCanonicalPath, writeFileAtomically };
package/dist/git.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ declare function fetchGitContext(): Promise<{
2
+ commonDirectory: string;
3
+ worktree: string;
4
+ worktreeId: string;
5
+ }>;
6
+ declare function listWorktreePaths(commonDirectory: string): Promise<Map<string, string>>;
7
+ export { fetchGitContext, listWorktreePaths };