pivotkit-node 0.0.1-stage → 0.2.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/CHANGELOG.md +37 -0
- package/LICENSE +21 -0
- package/README.md +15 -1
- package/package.json +52 -2
- package/src/errors.js +86 -0
- package/src/files.js +39 -0
- package/src/net.js +164 -0
- package/src/rest.js +64 -0
- package/src/safe-files.js +327 -0
- package/types/errors.d.ts +25 -0
- package/types/files.d.ts +32 -0
- package/types/net.d.ts +73 -0
- package/types/rest.d.ts +39 -0
- package/types/safe-files.d.ts +106 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to `pivotkit-node` are documented in this file. The format is based on
|
|
4
|
+
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this package adheres to
|
|
5
|
+
[Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
6
|
+
|
|
7
|
+
## [Unreleased]
|
|
8
|
+
|
|
9
|
+
## [0.2.0] - 2026-11-26
|
|
10
|
+
|
|
11
|
+
### Changed
|
|
12
|
+
|
|
13
|
+
- Depends on `pivotkit-core` `^0.11.0`, `pivotkit-report` `^0.7.0` and `pivotkit-xlsx` `^0.8.0`.
|
|
14
|
+
|
|
15
|
+
### Fixed
|
|
16
|
+
|
|
17
|
+
- `EISDIR` from `link()` counts as "no hard links", so `writeNew` and `writeSafe` with `exclusive`
|
|
18
|
+
write in place. libuv reports Windows' `ERROR_INVALID_FUNCTION` as `EISDIR`, the error reported for
|
|
19
|
+
hard links on FAT and exFAT. This was not tested on Windows.
|
|
20
|
+
|
|
21
|
+
## [0.1.0] - 2026-11-24
|
|
22
|
+
|
|
23
|
+
### Added
|
|
24
|
+
|
|
25
|
+
- The first release: the file handling of `pivotkit-cli/files` and the REST contract of
|
|
26
|
+
`pivotkit-cli/rest`, which pivotkit-cli and pivotkit-server now share from here. `writeNew` and
|
|
27
|
+
`writeSafe` with `exclusive` also work on file systems without hard links, such as FAT, exFAT and
|
|
28
|
+
some SMB mounts.
|
|
29
|
+
- `pivotkit-node/net`: `ipBytes`, `isLoopback`, `retryAfterSeconds` and `networkCodeOf`, the one copy
|
|
30
|
+
of how both front ends read addresses, Retry-After headers and failed connections.
|
|
31
|
+
`NETWORK_FAILURES` is the one table of a failed connection's codes: the command line's words and
|
|
32
|
+
which codes may work again.
|
|
33
|
+
- `CliError` extends `CodedError` of `pivotkit-core/internal`.
|
|
34
|
+
|
|
35
|
+
[Unreleased]: https://github.com/eizedev/pivotkit/compare/pivotkit-node@0.2.0...HEAD
|
|
36
|
+
[0.2.0]: https://github.com/eizedev/pivotkit/compare/pivotkit-node@0.1.0...pivotkit-node@0.2.0
|
|
37
|
+
[0.1.0]: https://github.com/eizedev/pivotkit/releases/tag/pivotkit-node@0.1.0
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 eizedev
|
|
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,17 @@
|
|
|
1
1
|
# pivotkit-node
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Internal to [pivotkit](https://github.com/eizedev/pivotkit).
|
|
4
|
+
|
|
5
|
+
It holds what the command line [pivotkit-cli](https://www.npmjs.com/package/pivotkit-cli) and
|
|
6
|
+
[pivotkit-server](https://www.npmjs.com/package/pivotkit-server) share in Node:
|
|
7
|
+
|
|
8
|
+
- `pivotkit-node/files` reads and writes files for a caller.
|
|
9
|
+
- `pivotkit-node/rest` holds what the REST service and its client agree on.
|
|
10
|
+
- `pivotkit-node/net` reads addresses, Retry-After headers and failed connections.
|
|
11
|
+
|
|
12
|
+
Its exports may change in any release. Use `pivotkit-cli/files` and `pivotkit-cli/rest` instead.
|
|
13
|
+
They re-export the same names and follow [versioning](https://pivotkit.eize.dev/versioning/).
|
|
14
|
+
|
|
15
|
+
## License
|
|
16
|
+
|
|
17
|
+
[MIT](https://github.com/eizedev/pivotkit/blob/main/LICENSE)
|
package/package.json
CHANGED
|
@@ -1,11 +1,61 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pivotkit-node",
|
|
3
|
-
"version": "0.0
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Internal to pivotkit: the Node.js file handling, REST contract and network readings that the pivotkit command line and pivotkit-server share. Use pivotkit-cli/files and pivotkit-cli/rest instead.",
|
|
5
5
|
"license": "MIT",
|
|
6
|
+
"author": "eizedev <oss@eize.dev>",
|
|
7
|
+
"homepage": "https://pivotkit.eize.dev",
|
|
6
8
|
"repository": {
|
|
7
9
|
"type": "git",
|
|
8
10
|
"url": "git+https://github.com/eizedev/pivotkit.git",
|
|
9
11
|
"directory": "packages/pivotkit-node"
|
|
12
|
+
},
|
|
13
|
+
"bugs": "https://github.com/eizedev/pivotkit/issues",
|
|
14
|
+
"keywords": [
|
|
15
|
+
"pivotkit"
|
|
16
|
+
],
|
|
17
|
+
"type": "module",
|
|
18
|
+
"exports": {
|
|
19
|
+
"./files": {
|
|
20
|
+
"types": "./types/files.d.ts",
|
|
21
|
+
"default": "./src/files.js"
|
|
22
|
+
},
|
|
23
|
+
"./net": {
|
|
24
|
+
"types": "./types/net.d.ts",
|
|
25
|
+
"default": "./src/net.js"
|
|
26
|
+
},
|
|
27
|
+
"./rest": {
|
|
28
|
+
"types": "./types/rest.d.ts",
|
|
29
|
+
"default": "./src/rest.js"
|
|
30
|
+
},
|
|
31
|
+
"./package.json": "./package.json"
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"src",
|
|
35
|
+
"types",
|
|
36
|
+
"README.md",
|
|
37
|
+
"CHANGELOG.md",
|
|
38
|
+
"LICENSE"
|
|
39
|
+
],
|
|
40
|
+
"engines": {
|
|
41
|
+
"node": ">=24"
|
|
42
|
+
},
|
|
43
|
+
"scripts": {
|
|
44
|
+
"test": "node ../../scripts/test-run.js node --test \"test/*.test.js\"",
|
|
45
|
+
"coverage": "node ../../scripts/test-run.js node --test --experimental-test-coverage --test-coverage-include=\"src/**\" \"test/*.test.js\"",
|
|
46
|
+
"types": "tsc -p .",
|
|
47
|
+
"test:types": "tsc -p test/types",
|
|
48
|
+
"prepack": "npm run types && node -e \"require('node:fs').copyFileSync('../../LICENSE', 'LICENSE')\""
|
|
49
|
+
},
|
|
50
|
+
"dependencies": {
|
|
51
|
+
"pivotkit-core": "^0.11.0",
|
|
52
|
+
"pivotkit-report": "^0.7.0",
|
|
53
|
+
"pivotkit-xlsx": "^0.8.0"
|
|
54
|
+
},
|
|
55
|
+
"devDependencies": {
|
|
56
|
+
"@types/node": "24.19.2"
|
|
57
|
+
},
|
|
58
|
+
"publishConfig": {
|
|
59
|
+
"access": "public"
|
|
10
60
|
}
|
|
11
61
|
}
|
package/src/errors.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The errors of reading and writing files for a caller, and how a message names what it is about.
|
|
3
|
+
* A CliError has a kind (what went wrong, for scripts) and a code; the command line ends with exit
|
|
4
|
+
* code 2 for it. No message holds the content of a file: a path is named by its base name (a
|
|
5
|
+
* directory below the working directory as typed), text from a file or a view is cleaned before it
|
|
6
|
+
* is printed; what a message may quote from data is the header's field names (each cut) and at most
|
|
7
|
+
* one cell value where it says what to fix, cut at 20 characters.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { basename } from "node:path";
|
|
11
|
+
import { PivotkitError } from "pivotkit-core";
|
|
12
|
+
import { CodedError } from "pivotkit-core/internal";
|
|
13
|
+
import { cleanText } from "pivotkit-core/import";
|
|
14
|
+
import { OperationError } from "pivotkit-report/operations";
|
|
15
|
+
|
|
16
|
+
/** @typedef {"usage" | "io" | "limit" | "template" | "remote" | "internal"} ErrorKind */
|
|
17
|
+
|
|
18
|
+
/** @extends {CodedError<string, undefined>} */
|
|
19
|
+
export class CliError extends CodedError {
|
|
20
|
+
/**
|
|
21
|
+
* @param {ErrorKind} kind
|
|
22
|
+
* @param {string} code a stable name, e.g. NOT_FOUND, OUTSIDE_ALLOWED_DIR, UNKNOWN_OPTION
|
|
23
|
+
* @param {string} message
|
|
24
|
+
*/
|
|
25
|
+
constructor(kind, code, message) {
|
|
26
|
+
super(code, message);
|
|
27
|
+
this.name = "CliError";
|
|
28
|
+
this.kind = kind;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The most characters of a name or message from outside that a message prints. */
|
|
33
|
+
const PRINT_LENGTH = 200;
|
|
34
|
+
|
|
35
|
+
/** Text from a file, a view or the data, safe to print: no control or direction characters, capped. */
|
|
36
|
+
export function printable(text) {
|
|
37
|
+
const clean = cleanText(String(text ?? ""));
|
|
38
|
+
return clean.length > PRINT_LENGTH ? `${clean.slice(0, PRINT_LENGTH - 1)}…` : clean;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** A path as messages name it: its base name only. */
|
|
42
|
+
export const shortName = (path) => printable(path === "-" ? "stdin" : basename(String(path)));
|
|
43
|
+
|
|
44
|
+
/** What Node's file errors mean, by their code. */
|
|
45
|
+
const FILE_ERRORS = Object.freeze({ ENOENT: "not found", EACCES: "not allowed to read or write", EPERM: "not allowed to read or write", EISDIR: "is a directory", ENOTDIR: "a part of the path is not a directory", ELOOP: "is a symbolic link", EEXIST: "exists", ENOSPC: "no space left on the disk", EROFS: "the file system is read-only" });
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The kind of a pivotkit-core error, by its code.
|
|
49
|
+
* @param {PivotkitError} error
|
|
50
|
+
* @returns {ErrorKind}
|
|
51
|
+
*/
|
|
52
|
+
function kindOfPivotkitError(error) {
|
|
53
|
+
const code = /** @type {string} */ (error.code);
|
|
54
|
+
// a reader over a limit throws LIMIT_EXCEEDED; pivotkit-xlsx 0.1.0 threw INVALID_FILE with reason
|
|
55
|
+
// LIMIT and details.limit, and a host may still have it installed next to this package
|
|
56
|
+
const overLimit = code === "LIMIT_EXCEEDED" || (code === "INVALID_FILE" && (error.details?.reason === "LIMIT" || typeof error.details?.limit === "string"));
|
|
57
|
+
return overLimit ? "limit" : code === "INVALID_TEMPLATE" ? "template" : code === "INVALID_FILE" ? "io" : code === "INVALID_OPTION" ? "usage" : "internal";
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Any error as a CliError: pivotkit-core's by their code, Node's file errors by theirs (with the
|
|
62
|
+
* file's base name, never its content), anything else as internal.
|
|
63
|
+
* @param {unknown} error
|
|
64
|
+
* @param {string} [path] the file it is about
|
|
65
|
+
* @returns {CliError}
|
|
66
|
+
*/
|
|
67
|
+
export function asCliError(error, path) {
|
|
68
|
+
if (error instanceof CliError) {
|
|
69
|
+
return error;
|
|
70
|
+
}
|
|
71
|
+
const name = path ? shortName(path) : "";
|
|
72
|
+
if (error instanceof PivotkitError) {
|
|
73
|
+
const reason = typeof error.details?.reason === "string" ? error.details.reason : /** @type {string} */ (error.code);
|
|
74
|
+
return new CliError(kindOfPivotkitError(error), reason, printable(name && !error.message.includes(name) ? `${name}: ${error.message}` : error.message));
|
|
75
|
+
}
|
|
76
|
+
if (error instanceof OperationError) {
|
|
77
|
+
// an operation of pivotkit-report's table: its code, the CLI's kind for it
|
|
78
|
+
const kind = error.code === "LIMIT_EXCEEDED" ? "limit" : error.code === "INVALID_INPUT" ? "usage" : error.code === "INTERNAL" ? "internal" : "io";
|
|
79
|
+
return new CliError(kind, error.code, printable(error.message));
|
|
80
|
+
}
|
|
81
|
+
const e = /** @type {NodeJS.ErrnoException} */ (error);
|
|
82
|
+
if (e && typeof e.code === "string" && Object.hasOwn(FILE_ERRORS, e.code)) {
|
|
83
|
+
return new CliError("io", e.code, `${name || "file"}: ${FILE_ERRORS[e.code]}`);
|
|
84
|
+
}
|
|
85
|
+
return new CliError("internal", "INTERNAL", printable(e && e.message ? e.message : String(error)));
|
|
86
|
+
}
|
package/src/files.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* pivotkit-node/files: reading and writing files on behalf of a caller, for the command line and
|
|
3
|
+
* pivotkit-server (pivotkit-cli/files re-exports it): a regular file read once with its size checked
|
|
4
|
+
* first, allowed directories by real path, new files that never replace one, and a data file read
|
|
5
|
+
* into an import table with pivotkit-xlsx. Node only. Not a sandbox: see safe-files.js for what the
|
|
6
|
+
* checks cannot do (another process of the same user changing the directories while they run).
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { readFile } from "pivotkit-core/import";
|
|
10
|
+
import xlsxReader from "pivotkit-xlsx";
|
|
11
|
+
import { printable, shortName } from "./errors.js";
|
|
12
|
+
|
|
13
|
+
export { NO_HARD_LINKS, TEMP_FILE_NAME, allowedDirs, cleanFileName, isInside, readSafe, readStdin, writeNew, writeSafe } from "./safe-files.js";
|
|
14
|
+
export { CliError, asCliError, printable, shortName } from "./errors.js";
|
|
15
|
+
|
|
16
|
+
/** The data formats the front ends read, by extension. */
|
|
17
|
+
export const DATA_FORMATS = Object.freeze(["csv", "tsv", "txt", "json", "xlsx"]);
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Reader notes that only say how a file was read (its encoding, separator, sheet): "info". The others
|
|
21
|
+
* say the data differs from the file (a column renamed or dropped, text cut, values not converted):
|
|
22
|
+
* warnings.
|
|
23
|
+
*/
|
|
24
|
+
// LINES_SKIPPED is a warning: the lines above the header a reader took for a title may be data
|
|
25
|
+
export const INFO_NOTES = Object.freeze(new Set(["ENCODING", "SEPARATOR", "SHEET", "USED_RANGE", "JSON_FLATTENED", "ROWS_EMPTY"]));
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The bytes of a data file as an import table (pivotkit-core/import with pivotkit-xlsx), with the
|
|
29
|
+
* reader's notes as findings named by the file's base name.
|
|
30
|
+
* @param {Uint8Array} bytes
|
|
31
|
+
* @param {string} name the file's name; its extension (or `format`) says how to read it
|
|
32
|
+
* @param {{ format?: string, sheet?: string, timeZone?: string, limits?: Partial<import("pivotkit-core").Limits> }} [options]
|
|
33
|
+
* @returns {Promise<{ table: any, notes: Array<{ severity: "info" | "warning", code: string, path: string, message: string }> }>}
|
|
34
|
+
*/
|
|
35
|
+
export async function readTable(bytes, name, { format, sheet, timeZone, limits } = {}) {
|
|
36
|
+
const fileName = format && !name.toLowerCase().endsWith(`.${format}`) ? `${name}.${format}` : name;
|
|
37
|
+
const table = await readFile(new File([/** @type {BlobPart} */ (bytes)], fileName), { plugins: [xlsxReader], ...(limits ? { limits } : {}), ...(sheet ? { sheet } : {}), ...(timeZone ? { timeZone } : {}) });
|
|
38
|
+
return { table, notes: table.notes.map((n) => ({ severity: INFO_NOTES.has(n.code) ? "info" : "warning", code: n.code, path: "", message: printable(`${shortName(name)}: ${n.message}`) })) };
|
|
39
|
+
}
|
package/src/net.js
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* pivotkit-node/net: how pivotkit-cli and pivotkit-server read what the network hands them: an IP
|
|
3
|
+
* address as its bytes, whether a host or an address is loopback, a Retry-After header, and a failed
|
|
4
|
+
* connection: where its system code is and what that code means (NETWORK_FAILURES). Each front end
|
|
5
|
+
* keeps its own error class; the readings and the words are here, once.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { isIPv4, isIPv6 } from "node:net";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* An IP address as its bytes, or null. Brackets and a zone ("%eth0") are dropped first.
|
|
12
|
+
* @param {string} text
|
|
13
|
+
* @returns {{ v: 4 | 6, bytes: number[] } | null}
|
|
14
|
+
*/
|
|
15
|
+
export function ipBytes(text) {
|
|
16
|
+
const address = String(text).replace(/^\[|\]$/g, "").replace(/%.*$/, "");
|
|
17
|
+
if (isIPv4(address)) {
|
|
18
|
+
return { v: 4, bytes: address.split(".").map(Number) };
|
|
19
|
+
}
|
|
20
|
+
if (!isIPv6(address)) {
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
let tail = [];
|
|
24
|
+
let head = address;
|
|
25
|
+
// a dotted IPv4 address at the end ("::ffff:169.254.169.254") is the last two groups
|
|
26
|
+
const dotted = /(\d+\.\d+\.\d+\.\d+)$/.exec(address);
|
|
27
|
+
if (dotted) {
|
|
28
|
+
const v4 = dotted[1].split(".").map(Number);
|
|
29
|
+
tail = [(v4[0] << 8) | v4[1], (v4[2] << 8) | v4[3]];
|
|
30
|
+
head = address.slice(0, -dotted[1].length);
|
|
31
|
+
head = head.endsWith("::") ? head : head.slice(0, -1);
|
|
32
|
+
}
|
|
33
|
+
const [left, right] = head.includes("::") ? head.split("::") : [head, null];
|
|
34
|
+
const groups = (part) => (part ? part.split(":").filter((g) => g !== "").map((g) => parseInt(g, 16)) : []);
|
|
35
|
+
const l = groups(left);
|
|
36
|
+
const r = right === null ? [] : groups(right);
|
|
37
|
+
const missing = 8 - l.length - r.length - tail.length;
|
|
38
|
+
const words = right === null ? [...l, ...tail] : [...l, ...new Array(Math.max(missing, 0)).fill(0), ...r, ...tail];
|
|
39
|
+
if (words.length !== 8) {
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
return { v: 6, bytes: words.flatMap((w) => [w >> 8, w & 255]) };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Whether an address's bytes are loopback: 127.0.0.0/8 or ::1, and with `mapped` also the IPv4-mapped
|
|
47
|
+
* ::ffff:127.0.0.0/104.
|
|
48
|
+
* @param {{ v: 4 | 6, bytes: number[] } | null} ip
|
|
49
|
+
* @param {boolean} mapped
|
|
50
|
+
*/
|
|
51
|
+
function loopbackBytes(ip, mapped) {
|
|
52
|
+
if (!ip) {
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
const b = ip.bytes;
|
|
56
|
+
const zeros = (to) => b.slice(0, to).every((x) => x === 0);
|
|
57
|
+
return ip.v === 4 ? b[0] === 127 : (zeros(15) && b[15] === 1) || (mapped && zeros(10) && b[10] === 255 && b[11] === 255 && b[12] === 127);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Whether a host is loopback.
|
|
62
|
+
*
|
|
63
|
+
* By default it reads a host as a URL or the configuration writes it: "localhost", an IPv4 address
|
|
64
|
+
* of 127.0.0.0/8 or "::1", brackets allowed ("[::1]"), any case. Only these spellings: a name such as
|
|
65
|
+
* "127.example.com" is no loopback, and neither is an IPv4-mapped "[::ffff:7f00:1]".
|
|
66
|
+
*
|
|
67
|
+
* `address: true` reads an IP address a lookup gave or a socket reached: every spelling counts, a
|
|
68
|
+
* zone is dropped, and the IPv4-mapped ::ffff:127.0.0.0/104 is loopback too. A name never is.
|
|
69
|
+
* @param {string} host
|
|
70
|
+
* @param {{ address?: boolean }} [how]
|
|
71
|
+
*/
|
|
72
|
+
export function isLoopback(host, how) {
|
|
73
|
+
if (how?.address === true) {
|
|
74
|
+
return loopbackBytes(ipBytes(String(host ?? "")), true);
|
|
75
|
+
}
|
|
76
|
+
const plain = String(host ?? "").toLowerCase().replace(/^\[(.*)\]$/, "$1");
|
|
77
|
+
return plain === "localhost" || ((plain === "::1" || isIPv4(plain)) && loopbackBytes(ipBytes(plain), false));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* A Retry-After header in seconds: a number of seconds, or an HTTP date (one that has passed is 0).
|
|
82
|
+
* Null without one and for one that is neither. Each caller caps the result by its own rule.
|
|
83
|
+
*
|
|
84
|
+
* `maxDigits` is the longest text read as a number of seconds; a longer one is read as a date.
|
|
85
|
+
* @param {unknown} value
|
|
86
|
+
* @param {{ maxDigits?: number }} [how]
|
|
87
|
+
* @returns {number | null}
|
|
88
|
+
*/
|
|
89
|
+
export function retryAfterSeconds(value, { maxDigits = Infinity } = {}) {
|
|
90
|
+
if (typeof value !== "string" || !value.trim()) {
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
const text = value.trim();
|
|
94
|
+
const seconds = /^\d+$/.test(text) && text.length <= maxDigits ? Number(text) : Math.ceil((Date.parse(value) - Date.now()) / 1000);
|
|
95
|
+
return Number.isFinite(seconds) ? Math.max(seconds, 0) : null;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Where each kind of client puts the code of a failed connection, in the order it is looked for.
|
|
100
|
+
* node:http and node:https put it on the error, or on each error of an AggregateError when they tried
|
|
101
|
+
* IPv6 and IPv4. Node's fetch puts it on the error's cause, sometimes one level deeper; a client that
|
|
102
|
+
* uses fetch and node:http (the command line's remote mode) looks there first, then on the error.
|
|
103
|
+
*/
|
|
104
|
+
const CODE_PLACES = Object.freeze({
|
|
105
|
+
node: [(e) => e?.code, (e) => e?.errors?.[0]?.code],
|
|
106
|
+
fetch: [(e) => e?.cause?.code, (e) => e?.code, (e) => e?.cause?.cause?.code]
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* The system code of a connection that failed (ECONNREFUSED, UND_ERR_SOCKET, a TLS code), or null.
|
|
111
|
+
* `client` says where to look (CODE_PLACES); the first code `accept` takes wins.
|
|
112
|
+
* @param {unknown} error
|
|
113
|
+
* @param {{ client: "node" | "fetch", accept?: (code: unknown) => boolean }} how by default any code that is there
|
|
114
|
+
* @returns {unknown}
|
|
115
|
+
*/
|
|
116
|
+
export function networkCodeOf(error, { client, accept = (code) => code !== undefined && code !== null }) {
|
|
117
|
+
const e = /** @type {any} */ (error);
|
|
118
|
+
return CODE_PLACES[client].map((place) => place(e)).find(accept) ?? null;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** An object of objects, frozen at both levels. */
|
|
122
|
+
const deepFreeze = (table) => Object.freeze(Object.fromEntries(Object.entries(table).map(([key, entry]) => [key, Object.freeze(entry)])));
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* The system codes of a failed connection that pivotkit knows, each once, with what it means:
|
|
126
|
+
*
|
|
127
|
+
* - `text`: the command line's words for it (remote mode's "the server cannot be reached: ...")
|
|
128
|
+
* - `retry`: pivotkit-server's guardedFetch marks a request that failed so as transient
|
|
129
|
+
* - `passes`: a source's load that failed so may pass by itself, so last good data may stand in
|
|
130
|
+
* (sources/run.js; Node's and undici's codes, also on a cause or an AggregateError's errors)
|
|
131
|
+
*
|
|
132
|
+
* The two readings of "may work again" differ by code; each stays as its caller had it.
|
|
133
|
+
* @type {Readonly<Record<string, Readonly<{ text?: string, retry?: true, passes?: true }>>>}
|
|
134
|
+
*/
|
|
135
|
+
export const NETWORK_FAILURES = deepFreeze({
|
|
136
|
+
ECONNREFUSED: { text: "the connection was refused (is the server running on that port?)", retry: true, passes: true },
|
|
137
|
+
ENOTFOUND: { text: "the host name is not known", retry: true, passes: true },
|
|
138
|
+
EAI_AGAIN: { text: "the host name cannot be looked up now", retry: true, passes: true },
|
|
139
|
+
ECONNRESET: { text: "the connection was reset", retry: true, passes: true },
|
|
140
|
+
EPIPE: { text: "the connection was closed", retry: true },
|
|
141
|
+
ETIMEDOUT: { text: "the connection timed out", retry: true, passes: true },
|
|
142
|
+
EHOSTUNREACH: { text: "the host cannot be reached", retry: true },
|
|
143
|
+
ENETUNREACH: { text: "the network cannot be reached", retry: true },
|
|
144
|
+
ECONNABORTED: { retry: true },
|
|
145
|
+
UND_ERR_SOCKET: { text: "the connection was closed", retry: true, passes: true },
|
|
146
|
+
UND_ERR_CONNECT_TIMEOUT: { text: "the connection timed out", passes: true },
|
|
147
|
+
UND_ERR_HEADERS_TIMEOUT: { passes: true },
|
|
148
|
+
UND_ERR_BODY_TIMEOUT: { passes: true },
|
|
149
|
+
CERT_HAS_EXPIRED: { text: "the server's certificate has expired" },
|
|
150
|
+
DEPTH_ZERO_SELF_SIGNED_CERT: { text: "the server's certificate is self-signed and not trusted" },
|
|
151
|
+
SELF_SIGNED_CERT_IN_CHAIN: { text: "the server's certificate is not trusted (a self-signed certificate in its chain)" },
|
|
152
|
+
UNABLE_TO_VERIFY_LEAF_SIGNATURE: { text: "the server's certificate cannot be verified" },
|
|
153
|
+
UNABLE_TO_GET_ISSUER_CERT_LOCALLY: { text: "the server's certificate cannot be verified (its issuer is not known here; NODE_EXTRA_CA_CERTS adds one)" },
|
|
154
|
+
ERR_TLS_CERT_ALTNAME_INVALID: { text: "the server's certificate is for another host name" },
|
|
155
|
+
ERR_SSL_WRONG_VERSION_NUMBER: { text: "the server does not speak TLS on that port (http instead of https?)" },
|
|
156
|
+
EPROTO: { text: "the TLS handshake failed (http instead of https on that port?)" }
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* What pivotkit knows of a failed connection's code (NETWORK_FAILURES), or an empty entry.
|
|
161
|
+
* @param {unknown} code
|
|
162
|
+
* @returns {Readonly<{ text?: string, retry?: true, passes?: true }>}
|
|
163
|
+
*/
|
|
164
|
+
export const networkFailureOf = (code) => (typeof code === "string" && Object.hasOwn(NETWORK_FAILURES, code) ? NETWORK_FAILURES[code] : {});
|
package/src/rest.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* pivotkit-node/rest: what the REST service of pivotkit-server and its client, the command line in
|
|
3
|
+
* remote mode, must agree on: the base path, the source ids, the token syntax, the problem codes and
|
|
4
|
+
* which addresses are loopback. Both depend on this package, so this is the one copy;
|
|
5
|
+
* pivotkit-server and pivotkit-cli/rest re-export it under the same names.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { OPERATION_ERRORS } from "pivotkit-report/operations";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The extra field of the REST service's protected-resource metadata (RFC 9728 lets a resource add
|
|
12
|
+
* its own) that names the public client `pivotkit login` signs in with (rest.signIn.clientId).
|
|
13
|
+
*/
|
|
14
|
+
export const SIGN_IN_CLIENT_FIELD = "pivotkit_client_id";
|
|
15
|
+
|
|
16
|
+
/** A sign-in client's ID: printable, no spaces, at most 200 characters. */
|
|
17
|
+
export const CLIENT_ID_SYNTAX = /^[\x21-\x7e]{1,200}$/;
|
|
18
|
+
|
|
19
|
+
/** The REST service's path under its origin. */
|
|
20
|
+
export const REST_BASE = "/api/v1";
|
|
21
|
+
|
|
22
|
+
/** A source id: letters, digits, "_", "-" and ".", at most 64, starting with a letter or digit. */
|
|
23
|
+
export const SOURCE_ID = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
|
|
24
|
+
|
|
25
|
+
/** What a bearer token may hold (RFC 6750's b64token): a token with other characters never matches a request. */
|
|
26
|
+
export const TOKEN_SYNTAX = /^[A-Za-z0-9\-._~+/]+=*$/;
|
|
27
|
+
|
|
28
|
+
/** Why a token outside TOKEN_SYNTAX does not work. */
|
|
29
|
+
export const TOKEN_SYNTAX_TEXT = "has characters a bearer token cannot carry (letters, digits and - . _ ~ + / only, = at the end), so no request could send it";
|
|
30
|
+
|
|
31
|
+
/** The codes the REST layer adds to the operations', with their status. */
|
|
32
|
+
export const REST_ERRORS = Object.freeze({
|
|
33
|
+
INVALID_TOKEN: 401,
|
|
34
|
+
INSUFFICIENT_SCOPE: 403,
|
|
35
|
+
FORBIDDEN_HOST: 403,
|
|
36
|
+
FORBIDDEN_ORIGIN: 403,
|
|
37
|
+
NOT_FOUND: 404,
|
|
38
|
+
METHOD_NOT_ALLOWED: 405,
|
|
39
|
+
BODY_TOO_LARGE: 413,
|
|
40
|
+
UNSUPPORTED_MEDIA_TYPE: 415,
|
|
41
|
+
VIEW_HAS_ERRORS: 422,
|
|
42
|
+
RATE_LIMITED: 429,
|
|
43
|
+
AUTH_NOT_READY: 503
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
/** Every code a problem can carry. */
|
|
47
|
+
export const PROBLEM_CODES = Object.freeze([...Object.keys(OPERATION_ERRORS), ...Object.keys(REST_ERRORS)]);
|
|
48
|
+
|
|
49
|
+
/** Whether a host is loopback: pivotkit-node/net says which spellings count. */
|
|
50
|
+
export { isLoopback } from "./net.js";
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The RFC 9728 metadata address of a resource: /.well-known/oauth-protected-resource before its path
|
|
54
|
+
* (https://host/api/v1 has it at https://host/.well-known/oauth-protected-resource/api/v1).
|
|
55
|
+
* @param {string | URL} resource
|
|
56
|
+
*/
|
|
57
|
+
export function resourceMetadataUrlOf(resource) {
|
|
58
|
+
const url = new URL(resource);
|
|
59
|
+
const path = url.pathname.length > 1 && url.pathname.endsWith("/") ? url.pathname.slice(0, -1) : url.pathname;
|
|
60
|
+
url.pathname = `/.well-known/oauth-protected-resource${path === "/" ? "" : path}`;
|
|
61
|
+
url.hash = "";
|
|
62
|
+
url.search = "";
|
|
63
|
+
return url.href;
|
|
64
|
+
}
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Reading and writing files the same safe way, with or without allowed directories:
|
|
3
|
+
*
|
|
4
|
+
* - `--allow-dir` is a hard limit: every file read or written must lie inside one of the directories
|
|
5
|
+
* after its real path is resolved (symbolic links and ".." followed), checked on the path and again
|
|
6
|
+
* on the opened file (its device and inode against the real path's). Without it the CLI reads and
|
|
7
|
+
* writes with the user's own rights, as any command-line tool does.
|
|
8
|
+
* - A file is opened once, without following a symbolic link at its end where the system can
|
|
9
|
+
* (O_NOFOLLOW) and without waiting for a writer (O_NONBLOCK, so a FIFO cannot hang the CLI), then
|
|
10
|
+
* checked on the handle: a regular file only, and its size against the limit before a byte is read.
|
|
11
|
+
* - A file is written to a new temporary file next to it (exclusive create), then renamed over the
|
|
12
|
+
* target: no half-written output, and a symbolic link, a directory or another non-regular file at
|
|
13
|
+
* the target is refused, never replaced.
|
|
14
|
+
*
|
|
15
|
+
* Not a sandbox against another process of the same user that changes the directories while the CLI
|
|
16
|
+
* runs: the checks narrow that window, they do not close it. A hard link inside an allowed directory
|
|
17
|
+
* to a file outside it is that file's name inside: no path check can tell it apart. A temporary file
|
|
18
|
+
* of a run that is killed between its creation and the rename stays behind (".<name>.<pid>-<random>.tmp",
|
|
19
|
+
* `TEMP_FILE_NAME`): this module installs no signal handler, which would change the host's signal
|
|
20
|
+
* handling; a caller that owns a directory removes them (pivotkit-server's output.maxAgeDays).
|
|
21
|
+
* `hardLinks: false` refuses a file with more than one name (a hard link), for callers that read on
|
|
22
|
+
* behalf of someone else (pivotkit-mcp). `writeNew` never replaces a file: the final name is created
|
|
23
|
+
* by writeSafe's exclusive write (link(), which fails when the name exists; where the file system has
|
|
24
|
+
* no hard links, the name is created with O_EXCL and written in place). The module is exported
|
|
25
|
+
* as `pivotkit-node/files` (and `pivotkit-cli/files`).
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
import { constants } from "node:fs";
|
|
29
|
+
import { link, lstat, open, realpath, rename, stat, unlink } from "node:fs/promises";
|
|
30
|
+
import { basename, dirname, join, relative, resolve, isAbsolute, sep } from "node:path";
|
|
31
|
+
import { limitText } from "pivotkit-core/internal";
|
|
32
|
+
import { CliError, printable, shortName } from "./errors.js";
|
|
33
|
+
|
|
34
|
+
/** The calls tests replace: a file system without hard links, a temporary file that cannot be removed. */
|
|
35
|
+
export const fileMeans = { link, unlink };
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The codes of link() where a file system has no hard links (FAT, exFAT, some SMB and FUSE mounts).
|
|
39
|
+
* On Windows, libuv reports ERROR_INVALID_FUNCTION as EISDIR (src/win/error.c), the error
|
|
40
|
+
* CreateHardLinkW is reported to give on FAT and exFAT (not measured here).
|
|
41
|
+
* @type {ReadonlySet<string>}
|
|
42
|
+
*/
|
|
43
|
+
export const NO_HARD_LINKS = new Set(["EPERM", "ENOTSUP", "EOPNOTSUPP", "ENOSYS", "EXDEV", "EMLINK", "EISDIR"]);
|
|
44
|
+
|
|
45
|
+
const READ_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);
|
|
46
|
+
|
|
47
|
+
/** True when `real` is `dir` or lies inside it (both real paths). */
|
|
48
|
+
export function isInside(real, dir) {
|
|
49
|
+
const rel = relative(dir, real);
|
|
50
|
+
// "..foo" is a name inside the directory; only ".." as the first part leaves it
|
|
51
|
+
return rel === "" || (!isAbsolute(rel) && rel.split(sep)[0] !== "..");
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* The allowed directories as real paths; each must exist and be a directory.
|
|
56
|
+
* @param {string[]} dirs
|
|
57
|
+
* @param {string} cwd
|
|
58
|
+
* @returns {Promise<string[]>}
|
|
59
|
+
*/
|
|
60
|
+
export async function allowedDirs(dirs, cwd) {
|
|
61
|
+
const out = [];
|
|
62
|
+
for (const dir of dirs) {
|
|
63
|
+
let real;
|
|
64
|
+
try {
|
|
65
|
+
real = await realpath(resolve(cwd, dir));
|
|
66
|
+
} catch {
|
|
67
|
+
throw new CliError("usage", "ALLOW_DIR_NOT_FOUND", `--allow-dir ${shortName(dir)}: not found`);
|
|
68
|
+
}
|
|
69
|
+
if (!(await stat(real)).isDirectory()) {
|
|
70
|
+
throw new CliError("usage", "ALLOW_DIR_NOT_DIRECTORY", `--allow-dir ${shortName(dir)}: not a directory`);
|
|
71
|
+
}
|
|
72
|
+
out.push(real);
|
|
73
|
+
}
|
|
74
|
+
return out;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Refuses a real path outside the allowed directories (none given: every path is allowed). */
|
|
78
|
+
function checkAllowed(real, allow, path) {
|
|
79
|
+
if (allow.length > 0 && !allow.some((dir) => isInside(real, dir))) {
|
|
80
|
+
// the directories by their base names, as every path in a message
|
|
81
|
+
throw new CliError("io", "OUTSIDE_ALLOWED_DIR", `${shortName(path)}: outside the allowed directories (--allow-dir ${allow.map(shortName).join(", ")})`);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Reads a regular file of at most `maxBytes` bytes.
|
|
87
|
+
* @param {string} path
|
|
88
|
+
* @param {{ cwd: string, allow: string[], maxBytes: number, limit?: string, hardLinks?: boolean }} options `limit`: the limit's name for
|
|
89
|
+
* the message; `hardLinks: false` refuses a file with more than one name (default true)
|
|
90
|
+
* @returns {Promise<Uint8Array>}
|
|
91
|
+
*/
|
|
92
|
+
export async function readSafe(path, { cwd, allow, maxBytes, limit = "fileBytes", hardLinks = true }) {
|
|
93
|
+
const full = resolve(cwd, path);
|
|
94
|
+
let real;
|
|
95
|
+
try {
|
|
96
|
+
real = await realpath(full);
|
|
97
|
+
} catch (e) {
|
|
98
|
+
throw e?.code === "ENOENT" ? new CliError("io", "NOT_FOUND", `${shortName(path)}: not found`) : e;
|
|
99
|
+
}
|
|
100
|
+
checkAllowed(real, allow, path);
|
|
101
|
+
const handle = await open(real, READ_FLAGS);
|
|
102
|
+
try {
|
|
103
|
+
const info = await handle.stat();
|
|
104
|
+
if (!info.isFile()) {
|
|
105
|
+
throw new CliError("io", "NOT_REGULAR_FILE", `${shortName(path)}: not a regular file`);
|
|
106
|
+
}
|
|
107
|
+
const now = await stat(real);
|
|
108
|
+
// the path again after the open: a directory on the way replaced by a link in between
|
|
109
|
+
// gives another real path, the file replaced another device or inode
|
|
110
|
+
const again = await realpath(full).catch(() => null);
|
|
111
|
+
if (now.dev !== info.dev || now.ino !== info.ino || again !== real) {
|
|
112
|
+
throw new CliError("io", "CHANGED", `${shortName(path)}: changed while it was opened`);
|
|
113
|
+
}
|
|
114
|
+
if (!hardLinks && info.nlink > 1) {
|
|
115
|
+
throw new CliError("io", "HARD_LINK", `${shortName(path)}: has more than one name (a hard link); not read`);
|
|
116
|
+
}
|
|
117
|
+
if (info.size > maxBytes) {
|
|
118
|
+
throw tooLarge(path, info.size, maxBytes, limit);
|
|
119
|
+
}
|
|
120
|
+
// the size the file had at the check, plus one byte: a file that has more by then grew (or, as
|
|
121
|
+
// a file of /proc, says it has none): over the limit it is refused as too large, else as changed,
|
|
122
|
+
// never cut
|
|
123
|
+
const buffer = new Uint8Array(Math.min(maxBytes + 1, info.size + 1));
|
|
124
|
+
let length = 0;
|
|
125
|
+
for (;;) {
|
|
126
|
+
const { bytesRead } = await handle.read(buffer, length, buffer.length - length, null);
|
|
127
|
+
if (bytesRead === 0) {
|
|
128
|
+
break;
|
|
129
|
+
}
|
|
130
|
+
length += bytesRead;
|
|
131
|
+
if (length > maxBytes) {
|
|
132
|
+
throw tooLarge(path, length, maxBytes, limit);
|
|
133
|
+
}
|
|
134
|
+
if (length > info.size) {
|
|
135
|
+
throw new CliError("io", "CHANGED", `${shortName(path)}: changed while it was read (it has more than the ${info.size.toLocaleString("en-US")} bytes it had)`);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return buffer.subarray(0, length);
|
|
139
|
+
} finally {
|
|
140
|
+
await handle.close();
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** A file over its limit, named by its base name. */
|
|
145
|
+
const tooLarge = (path, size, max, limit) => new CliError("limit", "LIMIT_EXCEEDED", `${shortName(path)}: ${limitText(size, max, "bytes", `limits.${limit}`)}`);
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Reads stdin up to `maxBytes` bytes.
|
|
149
|
+
* @param {AsyncIterable<Uint8Array>} stdin
|
|
150
|
+
* @param {number} maxBytes
|
|
151
|
+
* @param {string} [limit]
|
|
152
|
+
*/
|
|
153
|
+
export async function readStdin(stdin, maxBytes, limit = "fileBytes") {
|
|
154
|
+
const chunks = [];
|
|
155
|
+
let length = 0;
|
|
156
|
+
for await (const chunk of stdin) {
|
|
157
|
+
length += chunk.length;
|
|
158
|
+
if (length > maxBytes) {
|
|
159
|
+
throw tooLarge("-", length, maxBytes, limit);
|
|
160
|
+
}
|
|
161
|
+
chunks.push(chunk);
|
|
162
|
+
}
|
|
163
|
+
const out = new Uint8Array(length);
|
|
164
|
+
let at = 0;
|
|
165
|
+
for (const chunk of chunks) {
|
|
166
|
+
out.set(chunk, at);
|
|
167
|
+
at += chunk.length;
|
|
168
|
+
}
|
|
169
|
+
return out;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* The name of writeSafe's temporary files: ".<up to 50 characters of the target's name>.<pid>-<random>.tmp".
|
|
174
|
+
* A write takes seconds; one older than an hour was left by a process that was killed during it.
|
|
175
|
+
*/
|
|
176
|
+
export const TEMP_FILE_NAME = /^\..+\.\d+-[0-9a-z]{1,8}\.tmp$/;
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* A temporary file's name for the target `name` (TEMP_FILE_NAME). It stays within a file name's 255
|
|
180
|
+
* bytes, however long the target's name is: 50 characters of at most 4 bytes each, then about 25 for
|
|
181
|
+
* the process, a random part and ".tmp". A longer name keeps its first and its last 25 characters,
|
|
182
|
+
* so the temporary file still shows where it belongs and what it is (pivotkit-server's random
|
|
183
|
+
* prefix, its ".pivotkit-out.<format>" mark).
|
|
184
|
+
* @param {string} name the target's base name
|
|
185
|
+
*/
|
|
186
|
+
export function tempFileName(name) {
|
|
187
|
+
const chars = Array.from(name);
|
|
188
|
+
const stem = chars.length <= 50 ? name : [...chars.slice(0, 25), ...chars.slice(-25)].join("");
|
|
189
|
+
return `.${stem}.${process.pid}-${Math.random().toString(36).slice(2, 10) || "0"}.tmp`;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Whether a file name is one of Windows' reserved device names (CON, PRN, AUX, NUL, COM1 to COM9,
|
|
194
|
+
* COM¹ to COM³, LPT1 to LPT9, LPT¹ to LPT³, in any case), also followed by an extension (NUL.txt and
|
|
195
|
+
* NUL.tar.gz are NUL): in every directory it names the device, not a file there (Microsoft's
|
|
196
|
+
* "Naming Files, Paths, and Namespaces"). Trailing dots and spaces are removed first, as Windows
|
|
197
|
+
* does with a name's end.
|
|
198
|
+
* @param {string} name a base name
|
|
199
|
+
*/
|
|
200
|
+
export function isWindowsDevice(name) {
|
|
201
|
+
return /^(con|prn|aux|nul|com[1-9\u00b9\u00b2\u00b3]|lpt[1-9\u00b9\u00b2\u00b3])(\..*)?$/i.test(name.replace(/[. ]+$/, ""));
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Writes `bytes` to `path`: into a new temporary file in the target's directory, then renamed over it;
|
|
206
|
+
* with `exclusive`, linked into place instead (linkNew), which fails when a file is there (also one
|
|
207
|
+
* made between the check and the write), so nothing is replaced: `EXISTS`.
|
|
208
|
+
* @param {string} path
|
|
209
|
+
* @param {Uint8Array} bytes
|
|
210
|
+
* @param {{ cwd: string, allow: string[], exclusive?: boolean, mode?: number }} options `mode`: the new file's
|
|
211
|
+
* permissions (0o600: only its owner reads it), also when it replaces one; default the replaced file's, else 0o644
|
|
212
|
+
* @returns {Promise<string>} the real path written
|
|
213
|
+
*/
|
|
214
|
+
export async function writeSafe(path, bytes, { cwd, allow, exclusive = false, mode }) {
|
|
215
|
+
const full = resolve(cwd, path);
|
|
216
|
+
let dir;
|
|
217
|
+
try {
|
|
218
|
+
dir = await realpath(dirname(full));
|
|
219
|
+
} catch {
|
|
220
|
+
// below the working directory: name it as typed and how to make it; elsewhere no path at all
|
|
221
|
+
const parent = relative(cwd, dirname(full));
|
|
222
|
+
const inside = parent !== "" && !parent.startsWith("..") && !isAbsolute(parent);
|
|
223
|
+
throw new CliError("io", "NOT_FOUND", inside ? `${shortName(path)}: the directory ${JSON.stringify(printable(parent))} does not exist: create it first (mkdir -p ${printable(parent)})` : `${shortName(path)}: its directory does not exist`);
|
|
224
|
+
}
|
|
225
|
+
const target = join(dir, basename(full));
|
|
226
|
+
checkAllowed(target, allow, path);
|
|
227
|
+
if (process.platform === "win32" && isWindowsDevice(basename(full))) {
|
|
228
|
+
throw new CliError("io", "SPECIAL_FILE", `${shortName(path)}: exists and is a device or another special file; not replaced`);
|
|
229
|
+
}
|
|
230
|
+
const existing = await lstat(target).catch((e) => (e.code === "ENOENT" ? null : Promise.reject(e)));
|
|
231
|
+
if (existing && exclusive) {
|
|
232
|
+
throw new CliError("io", "EXISTS", `${shortName(path)}: is already there; not replaced`);
|
|
233
|
+
}
|
|
234
|
+
if (existing && !existing.isFile()) {
|
|
235
|
+
const what = existing.isSymbolicLink() ? "a symbolic link" : existing.isDirectory() ? "a directory" : "a device or another special file";
|
|
236
|
+
throw new CliError("io", existing.isSymbolicLink() || existing.isDirectory() ? "NOT_REGULAR_FILE" : "SPECIAL_FILE", `${shortName(path)}: exists and is ${what}; not replaced`);
|
|
237
|
+
}
|
|
238
|
+
const temp = join(dir, tempFileName(basename(full)));
|
|
239
|
+
const fileMode = mode ?? (existing ? existing.mode & 0o777 : 0o644);
|
|
240
|
+
await createFile(temp, bytes, fileMode);
|
|
241
|
+
try {
|
|
242
|
+
if (exclusive) {
|
|
243
|
+
await linkNew(temp, target, bytes, fileMode);
|
|
244
|
+
} else {
|
|
245
|
+
await rename(temp, target);
|
|
246
|
+
}
|
|
247
|
+
} catch (e) {
|
|
248
|
+
await unlink(temp).catch(() => undefined);
|
|
249
|
+
throw e.code === "EEXIST" ? new CliError("io", "EXISTS", `${shortName(path)}: is already there; not replaced`) : e;
|
|
250
|
+
}
|
|
251
|
+
return target;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** Creates `path` with `bytes` (O_EXCL, never through a symbolic link), synced; removed again when the write fails. */
|
|
255
|
+
async function createFile(path, bytes, mode) {
|
|
256
|
+
const handle = await open(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), mode);
|
|
257
|
+
try {
|
|
258
|
+
await handle.writeFile(bytes);
|
|
259
|
+
await handle.sync();
|
|
260
|
+
} catch (e) {
|
|
261
|
+
await handle.close();
|
|
262
|
+
await unlink(path).catch(() => undefined);
|
|
263
|
+
throw e;
|
|
264
|
+
}
|
|
265
|
+
await handle.close();
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Gives the temporary file its name with link(), which never replaces: a file that appeared since
|
|
270
|
+
* the check stays as it is. Where the file system has no hard links, the name itself is created
|
|
271
|
+
* exclusively and written; a reader at that moment may see it before its bytes are written.
|
|
272
|
+
*/
|
|
273
|
+
async function linkNew(temp, target, bytes, mode) {
|
|
274
|
+
try {
|
|
275
|
+
await fileMeans.link(temp, target);
|
|
276
|
+
} catch (e) {
|
|
277
|
+
if (!NO_HARD_LINKS.has(/** @type {any} */ (e)?.code)) {
|
|
278
|
+
throw e;
|
|
279
|
+
}
|
|
280
|
+
await createFile(target, bytes, mode);
|
|
281
|
+
}
|
|
282
|
+
// the file has its name: a temporary file that cannot be removed stays behind (TEMP_FILE_NAME)
|
|
283
|
+
await fileMeans.unlink(temp).catch(() => undefined);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** The characters a name of writeNew keeps (parentheses too: "Orders (fake backend)"); the others become "-". */
|
|
287
|
+
const NAME_CHARS = /[^A-Za-z0-9 ._()-]/g;
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* A file name from a name given from outside: letters, digits, space, ".", "_", "-" and parentheses only, no
|
|
291
|
+
* leading dot, at most `max` characters; "report" when nothing is left.
|
|
292
|
+
* @param {unknown} name
|
|
293
|
+
* @param {number} [max]
|
|
294
|
+
*/
|
|
295
|
+
export function cleanFileName(name, max = 80) {
|
|
296
|
+
const clean = String(name ?? "").normalize("NFKD").replace(/[\u0300-\u036f]/g, "").replace(NAME_CHARS, "-").replace(/-{2,}/g, "-").replace(/^[.\s-]+|[.\s-]+$/g, "").slice(0, max).trim();
|
|
297
|
+
return clean || "report";
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* Writes `bytes` as a new file in `dir` (a real path), never replacing one: `<name>.<extension>`, or
|
|
302
|
+
* with "-2", "-3" ... when the name is taken (at most `tries`); each try is writeSafe's exclusive
|
|
303
|
+
* write, so a file that appears in between is never replaced.
|
|
304
|
+
* @param {string} dir a directory's real path
|
|
305
|
+
* @param {string} name the file's name without extension (cleaned with cleanFileName)
|
|
306
|
+
* @param {string} extension without the dot
|
|
307
|
+
* @param {Uint8Array} bytes
|
|
308
|
+
* @param {{ prefix?: string, tries?: number, mode?: number }} [options] `prefix`: put before the name (a random part);
|
|
309
|
+
* `mode`: the new file's permissions (writeSafe's, default 0o644)
|
|
310
|
+
* @returns {Promise<string>} the file's base name
|
|
311
|
+
*/
|
|
312
|
+
export async function writeNew(dir, name, extension, bytes, { prefix = "", tries = 100, mode } = {}) {
|
|
313
|
+
const stem = `${prefix}${cleanFileName(name)}`;
|
|
314
|
+
for (let n = 1; n <= tries; n++) {
|
|
315
|
+
const base = `${stem}${n === 1 ? "" : `-${n}`}.${extension}`;
|
|
316
|
+
try {
|
|
317
|
+
await writeSafe(base, bytes, { cwd: dir, allow: [dir], exclusive: true, mode });
|
|
318
|
+
return base;
|
|
319
|
+
} catch (e) {
|
|
320
|
+
// a device's name (Windows' NUL, CON ...) is taken as well: the next name
|
|
321
|
+
if (e?.code !== "EXISTS" && e?.code !== "SPECIAL_FILE") {
|
|
322
|
+
throw e;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
throw new CliError("io", "EXISTS", `${shortName(stem)}: ${tries} files of this name exist already`);
|
|
327
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { CodedError } from "pivotkit-core/internal";
|
|
2
|
+
export type ErrorKind = "usage" | "io" | "limit" | "template" | "remote" | "internal";
|
|
3
|
+
/** @typedef {"usage" | "io" | "limit" | "template" | "remote" | "internal"} ErrorKind */
|
|
4
|
+
/** @extends {CodedError<string, undefined>} */
|
|
5
|
+
export declare class CliError extends CodedError<string, undefined> {
|
|
6
|
+
kind: ErrorKind;
|
|
7
|
+
/**
|
|
8
|
+
* @param {ErrorKind} kind
|
|
9
|
+
* @param {string} code a stable name, e.g. NOT_FOUND, OUTSIDE_ALLOWED_DIR, UNKNOWN_OPTION
|
|
10
|
+
* @param {string} message
|
|
11
|
+
*/
|
|
12
|
+
constructor(kind: ErrorKind, code: string, message: string);
|
|
13
|
+
}
|
|
14
|
+
/** Text from a file, a view or the data, safe to print: no control or direction characters, capped. */
|
|
15
|
+
export declare function printable(text: any): string;
|
|
16
|
+
/** A path as messages name it: its base name only. */
|
|
17
|
+
export declare const shortName: (path: any) => string;
|
|
18
|
+
/**
|
|
19
|
+
* Any error as a CliError: pivotkit-core's by their code, Node's file errors by theirs (with the
|
|
20
|
+
* file's base name, never its content), anything else as internal.
|
|
21
|
+
* @param {unknown} error
|
|
22
|
+
* @param {string} [path] the file it is about
|
|
23
|
+
* @returns {CliError}
|
|
24
|
+
*/
|
|
25
|
+
export declare function asCliError(error: unknown, path?: string): CliError;
|
package/types/files.d.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export { NO_HARD_LINKS, TEMP_FILE_NAME, allowedDirs, cleanFileName, isInside, readSafe, readStdin, writeNew, writeSafe } from "./safe-files.js";
|
|
2
|
+
export { CliError, asCliError, printable, shortName } from "./errors.js";
|
|
3
|
+
/** The data formats the front ends read, by extension. */
|
|
4
|
+
export declare const DATA_FORMATS: readonly string[];
|
|
5
|
+
/**
|
|
6
|
+
* Reader notes that only say how a file was read (its encoding, separator, sheet): "info". The others
|
|
7
|
+
* say the data differs from the file (a column renamed or dropped, text cut, values not converted):
|
|
8
|
+
* warnings.
|
|
9
|
+
*/
|
|
10
|
+
export declare const INFO_NOTES: Readonly<Set<string>>;
|
|
11
|
+
/**
|
|
12
|
+
* The bytes of a data file as an import table (pivotkit-core/import with pivotkit-xlsx), with the
|
|
13
|
+
* reader's notes as findings named by the file's base name.
|
|
14
|
+
* @param {Uint8Array} bytes
|
|
15
|
+
* @param {string} name the file's name; its extension (or `format`) says how to read it
|
|
16
|
+
* @param {{ format?: string, sheet?: string, timeZone?: string, limits?: Partial<import("pivotkit-core").Limits> }} [options]
|
|
17
|
+
* @returns {Promise<{ table: any, notes: Array<{ severity: "info" | "warning", code: string, path: string, message: string }> }>}
|
|
18
|
+
*/
|
|
19
|
+
export declare function readTable(bytes: Uint8Array, name: string, { format, sheet, timeZone, limits }?: {
|
|
20
|
+
format?: string;
|
|
21
|
+
sheet?: string;
|
|
22
|
+
timeZone?: string;
|
|
23
|
+
limits?: Partial<import("pivotkit-core").Limits>;
|
|
24
|
+
}): Promise<{
|
|
25
|
+
table: any;
|
|
26
|
+
notes: Array<{
|
|
27
|
+
severity: "info" | "warning";
|
|
28
|
+
code: string;
|
|
29
|
+
path: string;
|
|
30
|
+
message: string;
|
|
31
|
+
}>;
|
|
32
|
+
}>;
|
package/types/net.d.ts
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An IP address as its bytes, or null. Brackets and a zone ("%eth0") are dropped first.
|
|
3
|
+
* @param {string} text
|
|
4
|
+
* @returns {{ v: 4 | 6, bytes: number[] } | null}
|
|
5
|
+
*/
|
|
6
|
+
export declare function ipBytes(text: string): {
|
|
7
|
+
v: 4 | 6;
|
|
8
|
+
bytes: number[];
|
|
9
|
+
} | null;
|
|
10
|
+
/**
|
|
11
|
+
* Whether a host is loopback.
|
|
12
|
+
*
|
|
13
|
+
* By default it reads a host as a URL or the configuration writes it: "localhost", an IPv4 address
|
|
14
|
+
* of 127.0.0.0/8 or "::1", brackets allowed ("[::1]"), any case. Only these spellings: a name such as
|
|
15
|
+
* "127.example.com" is no loopback, and neither is an IPv4-mapped "[::ffff:7f00:1]".
|
|
16
|
+
*
|
|
17
|
+
* `address: true` reads an IP address a lookup gave or a socket reached: every spelling counts, a
|
|
18
|
+
* zone is dropped, and the IPv4-mapped ::ffff:127.0.0.0/104 is loopback too. A name never is.
|
|
19
|
+
* @param {string} host
|
|
20
|
+
* @param {{ address?: boolean }} [how]
|
|
21
|
+
*/
|
|
22
|
+
export declare function isLoopback(host: string, how?: {
|
|
23
|
+
address?: boolean;
|
|
24
|
+
}): boolean;
|
|
25
|
+
/**
|
|
26
|
+
* A Retry-After header in seconds: a number of seconds, or an HTTP date (one that has passed is 0).
|
|
27
|
+
* Null without one and for one that is neither. Each caller caps the result by its own rule.
|
|
28
|
+
*
|
|
29
|
+
* `maxDigits` is the longest text read as a number of seconds; a longer one is read as a date.
|
|
30
|
+
* @param {unknown} value
|
|
31
|
+
* @param {{ maxDigits?: number }} [how]
|
|
32
|
+
* @returns {number | null}
|
|
33
|
+
*/
|
|
34
|
+
export declare function retryAfterSeconds(value: unknown, { maxDigits }?: {
|
|
35
|
+
maxDigits?: number;
|
|
36
|
+
}): number | null;
|
|
37
|
+
/**
|
|
38
|
+
* The system code of a connection that failed (ECONNREFUSED, UND_ERR_SOCKET, a TLS code), or null.
|
|
39
|
+
* `client` says where to look (CODE_PLACES); the first code `accept` takes wins.
|
|
40
|
+
* @param {unknown} error
|
|
41
|
+
* @param {{ client: "node" | "fetch", accept?: (code: unknown) => boolean }} how by default any code that is there
|
|
42
|
+
* @returns {unknown}
|
|
43
|
+
*/
|
|
44
|
+
export declare function networkCodeOf(error: unknown, { client, accept }: {
|
|
45
|
+
client: "node" | "fetch";
|
|
46
|
+
accept?: (code: unknown) => boolean;
|
|
47
|
+
}): unknown;
|
|
48
|
+
/**
|
|
49
|
+
* The system codes of a failed connection that pivotkit knows, each once, with what it means:
|
|
50
|
+
*
|
|
51
|
+
* - `text`: the command line's words for it (remote mode's "the server cannot be reached: ...")
|
|
52
|
+
* - `retry`: pivotkit-server's guardedFetch marks a request that failed so as transient
|
|
53
|
+
* - `passes`: a source's load that failed so may pass by itself, so last good data may stand in
|
|
54
|
+
* (sources/run.js; Node's and undici's codes, also on a cause or an AggregateError's errors)
|
|
55
|
+
*
|
|
56
|
+
* The two readings of "may work again" differ by code; each stays as its caller had it.
|
|
57
|
+
* @type {Readonly<Record<string, Readonly<{ text?: string, retry?: true, passes?: true }>>>}
|
|
58
|
+
*/
|
|
59
|
+
export declare const NETWORK_FAILURES: Readonly<Record<string, Readonly<{
|
|
60
|
+
text?: string;
|
|
61
|
+
retry?: true;
|
|
62
|
+
passes?: true;
|
|
63
|
+
}>>>;
|
|
64
|
+
/**
|
|
65
|
+
* What pivotkit knows of a failed connection's code (NETWORK_FAILURES), or an empty entry.
|
|
66
|
+
* @param {unknown} code
|
|
67
|
+
* @returns {Readonly<{ text?: string, retry?: true, passes?: true }>}
|
|
68
|
+
*/
|
|
69
|
+
export declare const networkFailureOf: (code: unknown) => Readonly<{
|
|
70
|
+
text?: string;
|
|
71
|
+
retry?: true;
|
|
72
|
+
passes?: true;
|
|
73
|
+
}>;
|
package/types/rest.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The extra field of the REST service's protected-resource metadata (RFC 9728 lets a resource add
|
|
3
|
+
* its own) that names the public client `pivotkit login` signs in with (rest.signIn.clientId).
|
|
4
|
+
*/
|
|
5
|
+
export declare const SIGN_IN_CLIENT_FIELD = "pivotkit_client_id";
|
|
6
|
+
/** A sign-in client's ID: printable, no spaces, at most 200 characters. */
|
|
7
|
+
export declare const CLIENT_ID_SYNTAX: RegExp;
|
|
8
|
+
/** The REST service's path under its origin. */
|
|
9
|
+
export declare const REST_BASE = "/api/v1";
|
|
10
|
+
/** A source id: letters, digits, "_", "-" and ".", at most 64, starting with a letter or digit. */
|
|
11
|
+
export declare const SOURCE_ID: RegExp;
|
|
12
|
+
/** What a bearer token may hold (RFC 6750's b64token): a token with other characters never matches a request. */
|
|
13
|
+
export declare const TOKEN_SYNTAX: RegExp;
|
|
14
|
+
/** Why a token outside TOKEN_SYNTAX does not work. */
|
|
15
|
+
export declare const TOKEN_SYNTAX_TEXT = "has characters a bearer token cannot carry (letters, digits and - . _ ~ + / only, = at the end), so no request could send it";
|
|
16
|
+
/** The codes the REST layer adds to the operations', with their status. */
|
|
17
|
+
export declare const REST_ERRORS: Readonly<{
|
|
18
|
+
INVALID_TOKEN: 401;
|
|
19
|
+
INSUFFICIENT_SCOPE: 403;
|
|
20
|
+
FORBIDDEN_HOST: 403;
|
|
21
|
+
FORBIDDEN_ORIGIN: 403;
|
|
22
|
+
NOT_FOUND: 404;
|
|
23
|
+
METHOD_NOT_ALLOWED: 405;
|
|
24
|
+
BODY_TOO_LARGE: 413;
|
|
25
|
+
UNSUPPORTED_MEDIA_TYPE: 415;
|
|
26
|
+
VIEW_HAS_ERRORS: 422;
|
|
27
|
+
RATE_LIMITED: 429;
|
|
28
|
+
AUTH_NOT_READY: 503;
|
|
29
|
+
}>;
|
|
30
|
+
/** Every code a problem can carry. */
|
|
31
|
+
export declare const PROBLEM_CODES: readonly string[];
|
|
32
|
+
/** Whether a host is loopback: pivotkit-node/net says which spellings count. */
|
|
33
|
+
export { isLoopback } from "./net.js";
|
|
34
|
+
/**
|
|
35
|
+
* The RFC 9728 metadata address of a resource: /.well-known/oauth-protected-resource before its path
|
|
36
|
+
* (https://host/api/v1 has it at https://host/.well-known/oauth-protected-resource/api/v1).
|
|
37
|
+
* @param {string | URL} resource
|
|
38
|
+
*/
|
|
39
|
+
export declare function resourceMetadataUrlOf(resource: string | URL): string;
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { link, unlink } from "node:fs/promises";
|
|
2
|
+
/** The calls tests replace: a file system without hard links, a temporary file that cannot be removed. */
|
|
3
|
+
export declare const fileMeans: {
|
|
4
|
+
link: typeof link;
|
|
5
|
+
unlink: typeof unlink;
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* The codes of link() where a file system has no hard links (FAT, exFAT, some SMB and FUSE mounts).
|
|
9
|
+
* On Windows, libuv reports ERROR_INVALID_FUNCTION as EISDIR (src/win/error.c), the error
|
|
10
|
+
* CreateHardLinkW is reported to give on FAT and exFAT (not measured here).
|
|
11
|
+
* @type {ReadonlySet<string>}
|
|
12
|
+
*/
|
|
13
|
+
export declare const NO_HARD_LINKS: ReadonlySet<string>;
|
|
14
|
+
/** True when `real` is `dir` or lies inside it (both real paths). */
|
|
15
|
+
export declare function isInside(real: any, dir: any): boolean;
|
|
16
|
+
/**
|
|
17
|
+
* The allowed directories as real paths; each must exist and be a directory.
|
|
18
|
+
* @param {string[]} dirs
|
|
19
|
+
* @param {string} cwd
|
|
20
|
+
* @returns {Promise<string[]>}
|
|
21
|
+
*/
|
|
22
|
+
export declare function allowedDirs(dirs: string[], cwd: string): Promise<string[]>;
|
|
23
|
+
/**
|
|
24
|
+
* Reads a regular file of at most `maxBytes` bytes.
|
|
25
|
+
* @param {string} path
|
|
26
|
+
* @param {{ cwd: string, allow: string[], maxBytes: number, limit?: string, hardLinks?: boolean }} options `limit`: the limit's name for
|
|
27
|
+
* the message; `hardLinks: false` refuses a file with more than one name (default true)
|
|
28
|
+
* @returns {Promise<Uint8Array>}
|
|
29
|
+
*/
|
|
30
|
+
export declare function readSafe(path: string, { cwd, allow, maxBytes, limit, hardLinks }: {
|
|
31
|
+
cwd: string;
|
|
32
|
+
allow: string[];
|
|
33
|
+
maxBytes: number;
|
|
34
|
+
limit?: string;
|
|
35
|
+
hardLinks?: boolean;
|
|
36
|
+
}): Promise<Uint8Array>;
|
|
37
|
+
/**
|
|
38
|
+
* Reads stdin up to `maxBytes` bytes.
|
|
39
|
+
* @param {AsyncIterable<Uint8Array>} stdin
|
|
40
|
+
* @param {number} maxBytes
|
|
41
|
+
* @param {string} [limit]
|
|
42
|
+
*/
|
|
43
|
+
export declare function readStdin(stdin: AsyncIterable<Uint8Array>, maxBytes: number, limit?: string): Promise<Uint8Array<ArrayBuffer>>;
|
|
44
|
+
/**
|
|
45
|
+
* The name of writeSafe's temporary files: ".<up to 50 characters of the target's name>.<pid>-<random>.tmp".
|
|
46
|
+
* A write takes seconds; one older than an hour was left by a process that was killed during it.
|
|
47
|
+
*/
|
|
48
|
+
export declare const TEMP_FILE_NAME: RegExp;
|
|
49
|
+
/**
|
|
50
|
+
* A temporary file's name for the target `name` (TEMP_FILE_NAME). It stays within a file name's 255
|
|
51
|
+
* bytes, however long the target's name is: 50 characters of at most 4 bytes each, then about 25 for
|
|
52
|
+
* the process, a random part and ".tmp". A longer name keeps its first and its last 25 characters,
|
|
53
|
+
* so the temporary file still shows where it belongs and what it is (pivotkit-server's random
|
|
54
|
+
* prefix, its ".pivotkit-out.<format>" mark).
|
|
55
|
+
* @param {string} name the target's base name
|
|
56
|
+
*/
|
|
57
|
+
export declare function tempFileName(name: string): string;
|
|
58
|
+
/**
|
|
59
|
+
* Whether a file name is one of Windows' reserved device names (CON, PRN, AUX, NUL, COM1 to COM9,
|
|
60
|
+
* COM¹ to COM³, LPT1 to LPT9, LPT¹ to LPT³, in any case), also followed by an extension (NUL.txt and
|
|
61
|
+
* NUL.tar.gz are NUL): in every directory it names the device, not a file there (Microsoft's
|
|
62
|
+
* "Naming Files, Paths, and Namespaces"). Trailing dots and spaces are removed first, as Windows
|
|
63
|
+
* does with a name's end.
|
|
64
|
+
* @param {string} name a base name
|
|
65
|
+
*/
|
|
66
|
+
export declare function isWindowsDevice(name: string): boolean;
|
|
67
|
+
/**
|
|
68
|
+
* Writes `bytes` to `path`: into a new temporary file in the target's directory, then renamed over it;
|
|
69
|
+
* with `exclusive`, linked into place instead (linkNew), which fails when a file is there (also one
|
|
70
|
+
* made between the check and the write), so nothing is replaced: `EXISTS`.
|
|
71
|
+
* @param {string} path
|
|
72
|
+
* @param {Uint8Array} bytes
|
|
73
|
+
* @param {{ cwd: string, allow: string[], exclusive?: boolean, mode?: number }} options `mode`: the new file's
|
|
74
|
+
* permissions (0o600: only its owner reads it), also when it replaces one; default the replaced file's, else 0o644
|
|
75
|
+
* @returns {Promise<string>} the real path written
|
|
76
|
+
*/
|
|
77
|
+
export declare function writeSafe(path: string, bytes: Uint8Array, { cwd, allow, exclusive, mode }: {
|
|
78
|
+
cwd: string;
|
|
79
|
+
allow: string[];
|
|
80
|
+
exclusive?: boolean;
|
|
81
|
+
mode?: number;
|
|
82
|
+
}): Promise<string>;
|
|
83
|
+
/**
|
|
84
|
+
* A file name from a name given from outside: letters, digits, space, ".", "_", "-" and parentheses only, no
|
|
85
|
+
* leading dot, at most `max` characters; "report" when nothing is left.
|
|
86
|
+
* @param {unknown} name
|
|
87
|
+
* @param {number} [max]
|
|
88
|
+
*/
|
|
89
|
+
export declare function cleanFileName(name: unknown, max?: number): string;
|
|
90
|
+
/**
|
|
91
|
+
* Writes `bytes` as a new file in `dir` (a real path), never replacing one: `<name>.<extension>`, or
|
|
92
|
+
* with "-2", "-3" ... when the name is taken (at most `tries`); each try is writeSafe's exclusive
|
|
93
|
+
* write, so a file that appears in between is never replaced.
|
|
94
|
+
* @param {string} dir a directory's real path
|
|
95
|
+
* @param {string} name the file's name without extension (cleaned with cleanFileName)
|
|
96
|
+
* @param {string} extension without the dot
|
|
97
|
+
* @param {Uint8Array} bytes
|
|
98
|
+
* @param {{ prefix?: string, tries?: number, mode?: number }} [options] `prefix`: put before the name (a random part);
|
|
99
|
+
* `mode`: the new file's permissions (writeSafe's, default 0o644)
|
|
100
|
+
* @returns {Promise<string>} the file's base name
|
|
101
|
+
*/
|
|
102
|
+
export declare function writeNew(dir: string, name: string, extension: string, bytes: Uint8Array, { prefix, tries, mode }?: {
|
|
103
|
+
prefix?: string;
|
|
104
|
+
tries?: number;
|
|
105
|
+
mode?: number;
|
|
106
|
+
}): Promise<string>;
|