@b12k/porto 0.1.0 → 0.3.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/README.md +95 -10
- package/dist/cli.js +10 -9
- package/dist/config.d.ts +10 -5
- package/dist/config.js +3 -1
- package/dist/reserve.d.ts +17 -13
- package/dist/reserve.js +13 -11
- package/dist/vars.d.ts +12 -7
- package/dist/vars.js +52 -37
- package/package.json +24 -27
package/README.md
CHANGED
|
@@ -46,6 +46,7 @@ Run each command with `pnpm exec porto`. `reserve` is the default command.
|
|
|
46
46
|
| `--env-file <file>` | Set the env file path and turn on env output. |
|
|
47
47
|
| `--json-file <file>` / `--no-json-file` | Set or clear the JSON output file. |
|
|
48
48
|
| `--json` | Print JSON to stdout. Also works with `current` and `stats`. |
|
|
49
|
+
| `--silent` / `--no-silent` | Hide or show the reservation result on stdout. |
|
|
49
50
|
|
|
50
51
|
Use `-h` or `--help` for help. Use `-V` or `--version` for the version.
|
|
51
52
|
|
|
@@ -55,39 +56,123 @@ With no variables, `--env` writes `PORTO_BLOCK`.
|
|
|
55
56
|
|
|
56
57
|
## ⚙️ Config
|
|
57
58
|
|
|
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
|
+
The CLI loads config for `reserve` and `release`. 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
|
|
|
60
61
|
CLI options override config values. Config values override defaults.
|
|
61
62
|
|
|
62
|
-
Set `host` in config or use `--host` to check a specific address. Porto saves it for `release` and `cleanup`.
|
|
63
|
-
|
|
64
63
|
```ts
|
|
65
64
|
import { defineConfig } from '@b12k/porto';
|
|
66
65
|
|
|
67
66
|
export default defineConfig({
|
|
67
|
+
start: 10_000,
|
|
68
|
+
size: 10,
|
|
69
|
+
host: '127.0.0.1',
|
|
70
|
+
idleTtlMinutes: 60,
|
|
71
|
+
keep: false,
|
|
72
|
+
env: true,
|
|
68
73
|
envFile: '.env.local',
|
|
69
|
-
|
|
74
|
+
jsonFile: 'ports.json',
|
|
75
|
+
silent: false,
|
|
76
|
+
vars: ['PORT', (_block, port) => ({ PORT_2: port, HOST_NAME: `https://localhost:${port}` }), 'DB_PORT'],
|
|
70
77
|
onReserved(block, ports) {
|
|
71
|
-
console.error(`
|
|
78
|
+
console.error(`Reserved block ${block.index} with ports ${ports.join(', ')}`);
|
|
79
|
+
},
|
|
80
|
+
onReleased(block, ports) {
|
|
81
|
+
console.error(`Released block ${block.index} with ports ${ports.join(', ')}`);
|
|
72
82
|
},
|
|
73
83
|
});
|
|
74
84
|
```
|
|
75
85
|
|
|
86
|
+
All properties are optional.
|
|
87
|
+
|
|
88
|
+
| Property | Default | Effect |
|
|
89
|
+
| ---------------- | ---------------------- | -------------------------------------------------------------------------------------------- |
|
|
90
|
+
| `start` | `10000` | Set the first port of the candidate range. |
|
|
91
|
+
| `size` | `10` | Set the number of ports per block. |
|
|
92
|
+
| `host` | Local addresses | Check a specific host for busy ports. Porto saves the host for `release` and `cleanup`. |
|
|
93
|
+
| `idleTtlMinutes` | `60` | Set the idle time limit in minutes. A new `reserve` call refreshes the timer. |
|
|
94
|
+
| `keep` | `false` for new blocks | Keep a block during idle cleanup. Omit to keep its current setting. Set `false` to clear it. |
|
|
95
|
+
| `env` | `false` | Write variables to an env file. With no variables, write `PORTO_BLOCK`. |
|
|
96
|
+
| `envFile` | `.env` | Set the env file path. An explicit path enables `env` unless you set `env: false`. |
|
|
97
|
+
| `jsonFile` | `false` | Save variables or block details to a JSON file. Use a path to enable it. |
|
|
98
|
+
| `silent` | `false` | Hide the `reserve` result on stdout. Porto still writes requested files and reports errors. |
|
|
99
|
+
| `vars` | Unset | Assign one port per entry. Use a name for a port number or a function for several values. |
|
|
100
|
+
| `onReserved` | Unset | Run after Porto saves the block and writes the requested files. |
|
|
101
|
+
| `onReleased` | Unset | Run once per block freed by `release`. |
|
|
102
|
+
|
|
76
103
|
Relative paths in config start at the config directory. Relative paths in flags start at the current directory.
|
|
77
104
|
|
|
78
|
-
|
|
105
|
+
A `vars` function receives `(blockIndex, port, entryIndex)`, where `entryIndex` starts at zero. Return an object with string or number values. In the example, `PORT_2` and `HOST_NAME` use the same port.
|
|
79
106
|
|
|
80
|
-
|
|
107
|
+
Both hooks receive `(block, ports)`, where `ports` lists the ports assigned to that block. Hooks can return a promise. Porto runs release hooks in parallel.
|
|
81
108
|
|
|
82
109
|
## 📦 API
|
|
83
110
|
|
|
111
|
+
Run the API inside a Git checkout. It uses the options you pass in code and the built-in defaults.
|
|
112
|
+
|
|
113
|
+
### Get ports by offset
|
|
114
|
+
|
|
115
|
+
```js
|
|
116
|
+
import { reserve } from '@b12k/porto';
|
|
117
|
+
|
|
118
|
+
const block = await reserve();
|
|
119
|
+
const firstPort = block.getPort();
|
|
120
|
+
const secondPort = block.getPort(1);
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
`reserve()` returns `index`, `start`, `end`, `getPort(offset = 0)`, `ports`, and `vars`. The bounds are inclusive. Offsets start at zero and must fit inside the block.
|
|
124
|
+
|
|
125
|
+
### Get ports by name
|
|
126
|
+
|
|
84
127
|
```js
|
|
85
128
|
import { reserve } from '@b12k/porto';
|
|
86
129
|
|
|
87
|
-
const block = await reserve({ vars: ['API_PORT'] });
|
|
88
|
-
const
|
|
130
|
+
const block = await reserve({ start: 10_000, size: 5, vars: ['PORT', 'API_PORT'] });
|
|
131
|
+
const { PORT, API_PORT } = block.vars;
|
|
132
|
+
const DB_PORT = block.getPort(2); // 10002 if the first block is free
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
TypeScript infers `PORT` and `API_PORT` as `number`. `block.vars` contains this call's named values and defaults to `{}`. `block.ports` lists the ports assigned through `vars` across calls. `getPort()` reads a port by offset.
|
|
136
|
+
|
|
137
|
+
### Share a port between variables
|
|
138
|
+
|
|
139
|
+
```js
|
|
140
|
+
import { reserve } from '@b12k/porto';
|
|
141
|
+
|
|
142
|
+
const block = await reserve({
|
|
143
|
+
start: 10_000,
|
|
144
|
+
size: 2,
|
|
145
|
+
host: '127.0.0.1',
|
|
146
|
+
idleTtlMinutes: 30,
|
|
147
|
+
keep: true,
|
|
148
|
+
vars: [
|
|
149
|
+
'PORT',
|
|
150
|
+
(_block, port) => ({
|
|
151
|
+
API_PORT: port,
|
|
152
|
+
API_URL: `http://localhost:${port}`,
|
|
153
|
+
HEALTH_PORT: port,
|
|
154
|
+
HEALTH_URL: `http://localhost:${port}/health`,
|
|
155
|
+
}),
|
|
156
|
+
],
|
|
157
|
+
});
|
|
158
|
+
const { API_PORT, API_URL } = block.vars;
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
`reserve()` accepts `start`, `size`, `host`, `idleTtlMinutes`, `keep`, and `vars`. All six options are optional and use the defaults in the config table.
|
|
162
|
+
|
|
163
|
+
Each entry in `vars` uses one port. The example returns five named values from two entries. Five separate entries with `size: 2` throw `PortoError` with code `mappingInvalid` before Porto saves a reservation.
|
|
164
|
+
|
|
165
|
+
### Read and release reservations
|
|
166
|
+
|
|
167
|
+
```js
|
|
168
|
+
import { cleanup, current, release, stats } from '@b12k/porto';
|
|
169
|
+
|
|
170
|
+
const blocks = await current(); // Blocks for this checkout
|
|
171
|
+
const reservations = await stats(); // All reservations for this repository
|
|
172
|
+
const released = await release(); // Release this checkout's blocks if their ports are free
|
|
173
|
+
const expired = await cleanup(); // Release expired blocks if their ports are free
|
|
89
174
|
```
|
|
90
175
|
|
|
91
|
-
|
|
176
|
+
`release()` throws `BusyPortsError` if a port is in use. Its `ports` property lists the blocked ports.
|
|
92
177
|
|
|
93
178
|
Porto stores reservations in `<git-common-dir>/porto-registry.json`.
|
package/dist/cli.js
CHANGED
|
@@ -7,8 +7,8 @@ import { fetchGitContext } from "./git.js";
|
|
|
7
7
|
import { BusyPortsError, PortoError, cleanup, current, release, stats } from "./index.js";
|
|
8
8
|
import { logError } from "./log.js";
|
|
9
9
|
import { fetchExportPaths, formatReserveOutput, formatStatsTable, formatTable, updateEnvironmentFile, writeReserveJsonFile } from "./output.js";
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
10
|
+
import { commitReservation } from "./reserve.js";
|
|
11
|
+
import { parseVars } from "./vars.js";
|
|
12
12
|
async function fetchSettings(flags, command, worktree) {
|
|
13
13
|
const configured = await fetchConfig(worktree);
|
|
14
14
|
const { idle, json, vars, ...overrides } = pickBy(flags, (_flag, key)=>'cli' === command.getOptionValueSource(key));
|
|
@@ -45,16 +45,17 @@ async function handleReserve(flags, command) {
|
|
|
45
45
|
const git = await fetchGitContext();
|
|
46
46
|
const { vars: entries, ...settings } = await fetchSettings(flags, command, git.worktree);
|
|
47
47
|
const { environmentPath, jsonPath } = await fetchExportPaths(settings, git.commonDirectory);
|
|
48
|
-
const prepared = await
|
|
48
|
+
const prepared = await commitReservation({
|
|
49
49
|
...settings,
|
|
50
50
|
git,
|
|
51
|
-
|
|
52
|
-
}, ({ ports, ...block })=>{
|
|
53
|
-
const environment = void 0 === entries ? void 0 :
|
|
51
|
+
vars: entries
|
|
52
|
+
}, ({ ports, vars, ...block })=>{
|
|
53
|
+
const environment = void 0 === entries ? void 0 : vars;
|
|
54
|
+
const output = settings.silent ? void 0 : formatReserveOutput(block, environment, settings.json);
|
|
54
55
|
return {
|
|
55
56
|
block,
|
|
56
57
|
environment,
|
|
57
|
-
output
|
|
58
|
+
output,
|
|
58
59
|
ports
|
|
59
60
|
};
|
|
60
61
|
});
|
|
@@ -64,7 +65,7 @@ async function handleReserve(flags, command) {
|
|
|
64
65
|
PORTO_BLOCK: block.index
|
|
65
66
|
}, git.commonDirectory);
|
|
66
67
|
await runHook('onReserved', ()=>settings.onReserved?.(block, ports));
|
|
67
|
-
writeOutput(output);
|
|
68
|
+
if (void 0 !== output) writeOutput(output);
|
|
68
69
|
}
|
|
69
70
|
const cli = new Command('porto');
|
|
70
71
|
update_notifier({
|
|
@@ -79,7 +80,7 @@ update_notifier({
|
|
|
79
80
|
});
|
|
80
81
|
cli.command('reserve', {
|
|
81
82
|
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
|
+
}).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('--silent', 'Skip the reservation output on stdout').option('--no-silent', 'Print the reservation output on stdout').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
84
|
cli.command('current').description('Read the reservations of the current checkout').option('--json', 'Print JSON to stdout').action(async (flags)=>{
|
|
84
85
|
const blocks = await current();
|
|
85
86
|
if (0 === blocks.length) throw new PortoError('reservationNotFound');
|
package/dist/config.d.ts
CHANGED
|
@@ -11,7 +11,8 @@ declare const CONFIG_SCHEMA: z.ZodObject<{
|
|
|
11
11
|
env: z.ZodOptional<z.ZodBoolean>;
|
|
12
12
|
envFile: z.ZodOptional<z.ZodString>;
|
|
13
13
|
jsonFile: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<false>, z.ZodString]>>;
|
|
14
|
-
|
|
14
|
+
silent: z.ZodOptional<z.ZodBoolean>;
|
|
15
|
+
vars: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodCustom<import("./vars.js").VarFactory, import("./vars.js").VarFactory>]>>>;
|
|
15
16
|
}, z.core.$strict>;
|
|
16
17
|
type PortoConfig = z.input<typeof CONFIG_SCHEMA>;
|
|
17
18
|
declare const libraryName = "porto";
|
|
@@ -27,7 +28,8 @@ declare function defineConfig(config: PortoConfig): {
|
|
|
27
28
|
env?: boolean | undefined;
|
|
28
29
|
envFile?: string | undefined;
|
|
29
30
|
jsonFile?: string | false | undefined;
|
|
30
|
-
|
|
31
|
+
silent?: boolean | undefined;
|
|
32
|
+
vars?: (string | import("./vars.js").VarFactory)[] | undefined;
|
|
31
33
|
};
|
|
32
34
|
declare function parseConfig(config: unknown): {
|
|
33
35
|
onReleased?: ((block: import("./index.js").PortBlock, ports: Array<number>) => Promise<void> | void) | undefined;
|
|
@@ -40,7 +42,8 @@ declare function parseConfig(config: unknown): {
|
|
|
40
42
|
env?: boolean | undefined;
|
|
41
43
|
envFile?: string | undefined;
|
|
42
44
|
jsonFile?: string | false | undefined;
|
|
43
|
-
|
|
45
|
+
silent?: boolean | undefined;
|
|
46
|
+
vars?: (string | import("./vars.js").VarFactory)[] | undefined;
|
|
44
47
|
};
|
|
45
48
|
declare function applyReserveDefaults(settings: ReturnType<typeof parseConfig>): {
|
|
46
49
|
onReleased?: ((block: import("./index.js").PortBlock, ports: Array<number>) => Promise<void> | void) | undefined;
|
|
@@ -50,10 +53,11 @@ declare function applyReserveDefaults(settings: ReturnType<typeof parseConfig>):
|
|
|
50
53
|
keep?: boolean | undefined;
|
|
51
54
|
size: number;
|
|
52
55
|
start: number;
|
|
53
|
-
vars?: import("./vars.js").
|
|
56
|
+
vars?: (string | import("./vars.js").VarFactory)[] | undefined;
|
|
54
57
|
env: boolean;
|
|
55
58
|
envFile: string;
|
|
56
59
|
jsonFile: string | false;
|
|
60
|
+
silent: boolean;
|
|
57
61
|
};
|
|
58
62
|
declare function fetchConfig(worktree: string): Promise<{
|
|
59
63
|
onReleased?: ((block: import("./index.js").PortBlock, ports: Array<number>) => Promise<void> | void) | undefined;
|
|
@@ -66,7 +70,8 @@ declare function fetchConfig(worktree: string): Promise<{
|
|
|
66
70
|
env?: boolean | undefined;
|
|
67
71
|
envFile?: string | undefined;
|
|
68
72
|
jsonFile?: string | false | undefined;
|
|
69
|
-
|
|
73
|
+
silent?: boolean | undefined;
|
|
74
|
+
vars?: (string | import("./vars.js").VarFactory)[] | undefined;
|
|
70
75
|
}>;
|
|
71
76
|
export { applyReserveDefaults, DEFAULT_ENV_FILE, defineConfig, fetchConfig, libraryName, name, parseConfig, version };
|
|
72
77
|
export type { PortoConfig };
|
package/dist/config.js
CHANGED
|
@@ -23,6 +23,7 @@ const CONFIG_SCHEMA = z.strictObject({
|
|
|
23
23
|
z.literal(false),
|
|
24
24
|
z.string().min(1)
|
|
25
25
|
]),
|
|
26
|
+
silent: z.boolean(),
|
|
26
27
|
vars: VARS_SCHEMA
|
|
27
28
|
}).partial();
|
|
28
29
|
const libraryName = 'porto';
|
|
@@ -71,7 +72,8 @@ function applyReserveDefaults(settings) {
|
|
|
71
72
|
...parseOptions(settings),
|
|
72
73
|
env: settings.env ?? false,
|
|
73
74
|
envFile: settings.envFile ?? DEFAULT_ENV_FILE,
|
|
74
|
-
jsonFile: settings.jsonFile ?? false
|
|
75
|
+
jsonFile: settings.jsonFile ?? false,
|
|
76
|
+
silent: settings.silent ?? false
|
|
75
77
|
};
|
|
76
78
|
}
|
|
77
79
|
function resolveConfigPaths(config, filePath) {
|
package/dist/reserve.d.ts
CHANGED
|
@@ -1,18 +1,26 @@
|
|
|
1
1
|
import type { ReservationRecord } from './registry.js';
|
|
2
|
-
import type { Vars } from './vars.js';
|
|
2
|
+
import type { Vars, VarsResult } from './vars.js';
|
|
3
3
|
import { fetchGitContext } from './git.js';
|
|
4
|
+
import { buildBlock } from './ports.js';
|
|
4
5
|
import { parseOptions } from './schemas.js';
|
|
6
|
+
type ReservedBlock<Entries extends Vars = Vars> = ReturnType<typeof buildBlock> & {
|
|
7
|
+
ports: Array<number>;
|
|
8
|
+
vars: VarsResult<Entries>;
|
|
9
|
+
};
|
|
5
10
|
type ReserveOptions = Partial<ReturnType<typeof parseOptions>> & {
|
|
6
11
|
vars?: undefined | Vars;
|
|
7
12
|
};
|
|
8
13
|
declare function checkIsExpired(record: Pick<ReservationRecord, 'idleTtlMinutes' | 'keep' | 'lastUsedAt'>, now: number): boolean;
|
|
9
|
-
declare function issuePorts(record: ReservationRecord,
|
|
14
|
+
declare function issuePorts(record: ReservationRecord, entries: Vars): {
|
|
10
15
|
end: number;
|
|
11
16
|
getPort(offset?: number): number;
|
|
12
17
|
index: number;
|
|
13
18
|
start: number;
|
|
14
19
|
} & {
|
|
15
20
|
ports: number[];
|
|
21
|
+
vars: {
|
|
22
|
+
[k: string]: string | number;
|
|
23
|
+
};
|
|
16
24
|
};
|
|
17
25
|
declare function removeExpiredRecords(records: Array<ReservationRecord>, now: number): Promise<{
|
|
18
26
|
end: number;
|
|
@@ -20,17 +28,13 @@ declare function removeExpiredRecords(records: Array<ReservationRecord>, now: nu
|
|
|
20
28
|
index: number;
|
|
21
29
|
start: number;
|
|
22
30
|
}[]>;
|
|
23
|
-
declare function
|
|
31
|
+
declare function commitReservation<Result>({ git, host, idleTtlMinutes, keep, size, start, vars, }: ReturnType<typeof parseOptions> & {
|
|
24
32
|
git?: Awaited<ReturnType<typeof fetchGitContext>>;
|
|
25
|
-
|
|
33
|
+
vars?: undefined | Vars;
|
|
26
34
|
}, prepare: (block: ReturnType<typeof issuePorts>) => Result): Promise<Result>;
|
|
27
|
-
declare function reserve(options
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
} & {
|
|
33
|
-
ports: number[];
|
|
34
|
-
}>;
|
|
35
|
-
export { checkIsExpired, removeExpiredRecords, reserve, reserveBlock };
|
|
35
|
+
declare function reserve<const Entries extends Vars>(options: ReserveOptions & {
|
|
36
|
+
vars: Entries;
|
|
37
|
+
}): Promise<ReservedBlock<Entries>>;
|
|
38
|
+
declare function reserve(options?: ReserveOptions): Promise<ReservedBlock>;
|
|
39
|
+
export { checkIsExpired, commitReservation, removeExpiredRecords, reserve };
|
|
36
40
|
export type { ReserveOptions };
|
package/dist/reserve.js
CHANGED
|
@@ -4,7 +4,7 @@ import { fetchGitContext } from "./git.js";
|
|
|
4
4
|
import { buildBlock, checkHasBusyPort } from "./ports.js";
|
|
5
5
|
import { updateRegistry } from "./registry.js";
|
|
6
6
|
import { parseOptions } from "./schemas.js";
|
|
7
|
-
import { assertVarsFit, parseVarEntries } from "./vars.js";
|
|
7
|
+
import { assertVarsFit, mapBlockToVars, parseVarEntries } from "./vars.js";
|
|
8
8
|
async function allocateRecord(records, options) {
|
|
9
9
|
for(let index = 0; options.start + (index + 1) * options.size - 1 <= 65535; index += 1){
|
|
10
10
|
const record = {
|
|
@@ -23,11 +23,13 @@ async function allocateRecord(records, options) {
|
|
|
23
23
|
function checkIsExpired(record, now) {
|
|
24
24
|
return !record.keep && now - Date.parse(record.lastUsedAt) > 60000 * record.idleTtlMinutes;
|
|
25
25
|
}
|
|
26
|
-
function issuePorts(record,
|
|
26
|
+
function issuePorts(record, entries) {
|
|
27
27
|
const block = buildBlock(record);
|
|
28
|
-
|
|
28
|
+
const vars = mapBlockToVars(block, entries);
|
|
29
|
+
record.ports = union(record.ports, range(block.start, block.start + entries.length));
|
|
29
30
|
return Object.assign(block, {
|
|
30
|
-
ports: record.ports
|
|
31
|
+
ports: record.ports,
|
|
32
|
+
vars
|
|
31
33
|
});
|
|
32
34
|
}
|
|
33
35
|
async function removeExpiredRecords(records, now) {
|
|
@@ -42,8 +44,8 @@ async function removeExpiredRecords(records, now) {
|
|
|
42
44
|
remove(records, (record)=>expiredRecords.includes(record));
|
|
43
45
|
return expiredRecords.map((record)=>buildBlock(record));
|
|
44
46
|
}
|
|
45
|
-
async function
|
|
46
|
-
assertVarsFit(
|
|
47
|
+
async function commitReservation({ git, host, idleTtlMinutes, keep, size, start, vars = [] }, prepare) {
|
|
48
|
+
assertVarsFit(vars.length, size);
|
|
47
49
|
const { commonDirectory, worktree, worktreeId } = git ?? await fetchGitContext();
|
|
48
50
|
return updateRegistry(commonDirectory, async (records)=>{
|
|
49
51
|
const now = Date.now();
|
|
@@ -69,16 +71,16 @@ async function reserveBlock({ git, host, idleTtlMinutes, keep, portsCount, size,
|
|
|
69
71
|
worktreeId
|
|
70
72
|
});
|
|
71
73
|
if (!existingRecord) records.push(record);
|
|
72
|
-
return prepare(issuePorts(record,
|
|
74
|
+
return prepare(issuePorts(record, vars));
|
|
73
75
|
});
|
|
74
76
|
}
|
|
75
77
|
async function reserve(options = {}) {
|
|
76
78
|
const settings = parseOptions(options);
|
|
77
|
-
const
|
|
78
|
-
const block = await
|
|
79
|
+
const vars = void 0 === options.vars ? void 0 : parseVarEntries(options.vars);
|
|
80
|
+
const block = await commitReservation({
|
|
79
81
|
...settings,
|
|
80
|
-
|
|
82
|
+
vars
|
|
81
83
|
}, (reservedBlock)=>reservedBlock);
|
|
82
84
|
return block;
|
|
83
85
|
}
|
|
84
|
-
export { checkIsExpired, removeExpiredRecords, reserve
|
|
86
|
+
export { checkIsExpired, commitReservation, removeExpiredRecords, reserve };
|
package/dist/vars.d.ts
CHANGED
|
@@ -1,14 +1,19 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import type { PortBlock } from './index.js';
|
|
3
|
-
type VarEntry =
|
|
4
|
-
type
|
|
5
|
-
type
|
|
6
|
-
|
|
3
|
+
type VarEntry = string | VarFactory;
|
|
4
|
+
type VarEntryResult<Entry extends VarEntry> = Entry extends string ? string extends Entry ? Partial<Record<string, number>> : Record<Entry, number> : Entry extends VarFactory ? ReturnType<Entry> : never;
|
|
5
|
+
type VarFactory = (block: number, port: number, index: number) => Record<string, number | string>;
|
|
6
|
+
type Vars = ReadonlyArray<VarEntry>;
|
|
7
|
+
type VarsResult<Entries extends Vars> = Entries extends readonly [
|
|
8
|
+
infer Entry extends VarEntry,
|
|
9
|
+
...infer Rest extends Vars
|
|
10
|
+
] ? VarEntryResult<Entry> & VarsResult<Rest> : number extends Entries['length'] ? Partial<Record<string, number | string>> : object;
|
|
11
|
+
declare const VARS_SCHEMA: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodCustom<VarFactory, VarFactory>]>>;
|
|
7
12
|
declare function assertVarsFit(varsCount: number, size: number): void;
|
|
8
|
-
declare function mapBlockToVars(block: PortBlock, entries:
|
|
13
|
+
declare function mapBlockToVars(block: PortBlock, entries: Vars): {
|
|
9
14
|
[k: string]: string | number;
|
|
10
15
|
};
|
|
11
|
-
declare function parseVarEntries(vars: unknown):
|
|
16
|
+
declare function parseVarEntries(vars: unknown): (string | VarFactory)[];
|
|
12
17
|
declare function parseVars(source: string): VarEntry[];
|
|
13
18
|
export { assertVarsFit, mapBlockToVars, parseVarEntries, parseVars, VARS_SCHEMA };
|
|
14
|
-
export type { VarEntry, VarFactory, Vars };
|
|
19
|
+
export type { VarEntry, VarFactory, Vars, VarsResult };
|
package/dist/vars.js
CHANGED
|
@@ -1,62 +1,70 @@
|
|
|
1
|
+
import { isPlainObject } from "es-toolkit";
|
|
1
2
|
import { types } from "node:util";
|
|
2
3
|
import { z } from "zod";
|
|
3
4
|
import { PortoError } from "./error.js";
|
|
4
5
|
const VAR_NAME_SCHEMA = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u);
|
|
5
6
|
const VAR_TEXT_SCHEMA = z.string().regex(/^[^\r\n\0]*$/u);
|
|
6
|
-
const
|
|
7
|
-
|
|
8
|
-
return Object.entries(record).every(([name, factory])=>VAR_NAME_SCHEMA.safeParse(name).success && 'function' == typeof factory);
|
|
9
|
-
});
|
|
10
|
-
const VAR_ENTRY_SCHEMA = z.union([
|
|
7
|
+
const VAR_FACTORY_SCHEMA = z.custom((entry)=>'function' == typeof entry);
|
|
8
|
+
const VAR_RESULT_ENTRY_SCHEMA = z.tuple([
|
|
11
9
|
VAR_NAME_SCHEMA,
|
|
12
|
-
|
|
10
|
+
z.union([
|
|
11
|
+
VAR_TEXT_SCHEMA,
|
|
12
|
+
z.number()
|
|
13
|
+
])
|
|
13
14
|
]);
|
|
14
|
-
const
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
15
|
+
const VAR_RESULT_SCHEMA = z.custom(isPlainObject).transform((variables)=>Object.entries(variables)).pipe(z.array(VAR_RESULT_ENTRY_SCHEMA));
|
|
16
|
+
const VARS_SCHEMA = z.array(z.union([
|
|
17
|
+
VAR_NAME_SCHEMA,
|
|
18
|
+
VAR_FACTORY_SCHEMA
|
|
19
|
+
])).refine((entries)=>{
|
|
20
|
+
const names = entries.filter((entry)=>'string' == typeof entry);
|
|
21
|
+
return new Set(names).size === names.length;
|
|
22
|
+
}, {
|
|
20
23
|
message: 'Variable names must be unique.'
|
|
21
24
|
});
|
|
22
25
|
function assertVarsFit(varsCount, size) {
|
|
23
26
|
if (varsCount > size) throw new PortoError('mappingInvalid', 'Vars contain more entries than the block contains.');
|
|
24
27
|
}
|
|
25
|
-
function
|
|
26
|
-
const
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
28
|
+
function mapVarEntry(entry, block, index) {
|
|
29
|
+
const port = block.getPort(index);
|
|
30
|
+
if ('string' == typeof entry) return [
|
|
31
|
+
[
|
|
32
|
+
entry,
|
|
30
33
|
port
|
|
31
|
-
]
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
34
|
+
]
|
|
35
|
+
];
|
|
36
|
+
try {
|
|
37
|
+
const variables = entry(block.index, port, index);
|
|
38
|
+
if (types.isPromise(variables)) variables.catch(()=>{});
|
|
39
|
+
return VAR_RESULT_SCHEMA.parse(variables);
|
|
40
|
+
} catch (error) {
|
|
41
|
+
throw new PortoError('mappingInvalid', `Cannot create variables for entry ${index + 1}; expected an object with valid names and single-line strings or finite numbers.`, {
|
|
42
|
+
cause: error
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
function mapBlockToVars(block, entries) {
|
|
47
|
+
const environment = new Map();
|
|
48
|
+
for (const [index, entry] of entries.entries())for (const [name, value] of mapVarEntry(entry, block, index)){
|
|
49
|
+
if (environment.has(name)) throw new PortoError('mappingInvalid', `Variable names must be unique. Duplicate: ${name}.`);
|
|
50
|
+
environment.set(name, value);
|
|
51
|
+
}
|
|
52
|
+
return Object.fromEntries(environment);
|
|
46
53
|
}
|
|
47
54
|
function parseVar(entry) {
|
|
48
55
|
const separator = entry.indexOf(':');
|
|
49
56
|
const name = (-1 === separator ? entry : entry.slice(0, separator)).trim();
|
|
50
|
-
if (-1 === separator) return
|
|
57
|
+
if (-1 === separator) return {
|
|
58
|
+
name
|
|
59
|
+
};
|
|
51
60
|
const template = entry.slice(separator + 1);
|
|
52
61
|
const result = VAR_TEXT_SCHEMA.safeParse(template);
|
|
53
62
|
if (!result.success) throw new PortoError('mappingInvalid', 'Vars templates must fit on one line.', {
|
|
54
63
|
cause: result.error
|
|
55
64
|
});
|
|
56
65
|
return {
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
}
|
|
66
|
+
name,
|
|
67
|
+
template
|
|
60
68
|
};
|
|
61
69
|
}
|
|
62
70
|
function parseVarEntries(vars) {
|
|
@@ -67,6 +75,13 @@ function parseVarEntries(vars) {
|
|
|
67
75
|
return result.data;
|
|
68
76
|
}
|
|
69
77
|
function parseVars(source) {
|
|
70
|
-
|
|
78
|
+
const entries = source.split(';').map((entry)=>parseVar(entry));
|
|
79
|
+
parseVarEntries(entries.map(({ name })=>name));
|
|
80
|
+
return entries.map(({ name, template })=>{
|
|
81
|
+
if (void 0 === template) return name;
|
|
82
|
+
return (block, port)=>({
|
|
83
|
+
[name]: template.replaceAll('{{block}}', String(block)).replaceAll('{{port}}', String(port))
|
|
84
|
+
});
|
|
85
|
+
});
|
|
71
86
|
}
|
|
72
87
|
export { VARS_SCHEMA, assertVarsFit, mapBlockToVars, parseVarEntries, parseVars };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@b12k/porto",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Port range allocator for git worktrees",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cli",
|
|
@@ -31,30 +31,6 @@
|
|
|
31
31
|
"publishConfig": {
|
|
32
32
|
"access": "public"
|
|
33
33
|
},
|
|
34
|
-
"scripts": {
|
|
35
|
-
"build": "rslib",
|
|
36
|
-
"check": "run-p -l check:*",
|
|
37
|
-
"check:format": "oxfmt . --check",
|
|
38
|
-
"check:scripts": "oxlint",
|
|
39
|
-
"check:types": "tsc --noEmit",
|
|
40
|
-
"check:tests": "rstest run",
|
|
41
|
-
"deps:check": "ncu -e 2 -c 1",
|
|
42
|
-
"deps:update": "ncu -du --doctorInstall \"pnpm deps:update:install\" --doctorTest \"pnpm deps:update:doctor\" -c 1",
|
|
43
|
-
"deps:update:doctor": "run-p -l check:types check:scripts check:tests build",
|
|
44
|
-
"deps:update:install": "pnpm i --no-frozen-lockfile",
|
|
45
|
-
"dev": "rslib --watch",
|
|
46
|
-
"fix": "run-s -l fix:*",
|
|
47
|
-
"fix:format": "oxfmt . --write",
|
|
48
|
-
"fix:scripts": "oxlint --fix",
|
|
49
|
-
"ga:notify": "tsx .github/notify.ts",
|
|
50
|
-
"husky:commit-msg": "commitlint",
|
|
51
|
-
"husky:pre-commit": "lint-staged",
|
|
52
|
-
"husky:pre-push": "branch-name-lint",
|
|
53
|
-
"prepack": "run-p check build",
|
|
54
|
-
"prepare": "husky",
|
|
55
|
-
"release": "release-it",
|
|
56
|
-
"test": "rstest run"
|
|
57
|
-
},
|
|
58
34
|
"dependencies": {
|
|
59
35
|
"boxen": "9.0.0",
|
|
60
36
|
"commander": "15.1.0",
|
|
@@ -92,5 +68,26 @@
|
|
|
92
68
|
"engines": {
|
|
93
69
|
"node": ">=24"
|
|
94
70
|
},
|
|
95
|
-
"
|
|
96
|
-
|
|
71
|
+
"scripts": {
|
|
72
|
+
"build": "rslib",
|
|
73
|
+
"check": "run-p -l check:*",
|
|
74
|
+
"check:format": "oxfmt . --check",
|
|
75
|
+
"check:scripts": "oxlint",
|
|
76
|
+
"check:types": "tsc --noEmit",
|
|
77
|
+
"check:tests": "rstest run",
|
|
78
|
+
"deps:check": "ncu -e 2 -c 1",
|
|
79
|
+
"deps:update": "ncu -du --doctorInstall \"pnpm deps:update:install\" --doctorTest \"pnpm deps:update:doctor\" -c 1",
|
|
80
|
+
"deps:update:doctor": "run-p -l check:types check:scripts check:tests build",
|
|
81
|
+
"deps:update:install": "pnpm i --no-frozen-lockfile",
|
|
82
|
+
"dev": "rslib --watch",
|
|
83
|
+
"fix": "run-s -l fix:*",
|
|
84
|
+
"fix:format": "oxfmt . --write",
|
|
85
|
+
"fix:scripts": "oxlint --fix",
|
|
86
|
+
"ga:notify": "tsx .github/notify.ts",
|
|
87
|
+
"husky:commit-msg": "commitlint",
|
|
88
|
+
"husky:pre-commit": "lint-staged",
|
|
89
|
+
"husky:pre-push": "branch-name-lint",
|
|
90
|
+
"release": "release-it",
|
|
91
|
+
"test": "rstest run"
|
|
92
|
+
}
|
|
93
|
+
}
|