@cepharum/mcp-gitlab 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/LICENSE +21 -0
  3. package/README.md +170 -2
  4. package/package.json +50 -5
  5. package/src/audit.js +185 -0
  6. package/src/cli.js +411 -0
  7. package/src/connect.js +335 -0
  8. package/src/consent.js +115 -0
  9. package/src/downloads.js +94 -0
  10. package/src/errors.js +13 -0
  11. package/src/git.js +94 -0
  12. package/src/gitlab/client.js +406 -0
  13. package/src/gitlab/diff.js +79 -0
  14. package/src/hosts.js +228 -0
  15. package/src/paths.js +71 -0
  16. package/src/permissions/catalog.js +75 -0
  17. package/src/permissions/policy.js +230 -0
  18. package/src/permissions/profiles.js +66 -0
  19. package/src/pins.js +36 -0
  20. package/src/platform/index.js +76 -0
  21. package/src/platform/macos.js +129 -0
  22. package/src/platform/service.js +2 -0
  23. package/src/process.js +56 -0
  24. package/src/refs.js +146 -0
  25. package/src/secrets.js +51 -0
  26. package/src/server.js +146 -0
  27. package/src/session.js +140 -0
  28. package/src/text.js +68 -0
  29. package/src/tools/artifacts.js +288 -0
  30. package/src/tools/audit.js +53 -0
  31. package/src/tools/environments.js +147 -0
  32. package/src/tools/files.js +101 -0
  33. package/src/tools/index.js +33 -0
  34. package/src/tools/issues.js +465 -0
  35. package/src/tools/merge-requests.js +698 -0
  36. package/src/tools/packages.js +322 -0
  37. package/src/tools/pipelines.js +415 -0
  38. package/src/tools/registry.js +107 -0
  39. package/src/tools/repositories.js +174 -0
  40. package/src/tools/schedules.js +521 -0
  41. package/src/tools/shared.js +93 -0
  42. package/src/tools/variables.js +294 -0
  43. package/src/tools/wikis.js +168 -0
  44. package/src/zip.js +178 -0
package/src/process.js ADDED
@@ -0,0 +1,56 @@
1
+ import { spawn } from "node:child_process";
2
+
3
+ /**
4
+ * Runs a program without a shell, so no argument is ever interpreted as
5
+ * shell syntax.
6
+ *
7
+ * @param {string} command
8
+ * @param {string[]} args
9
+ * @param {{ cwd?: string, input?: string, timeoutMs?: number }} [options]
10
+ * @returns {Promise<string>} what the program wrote to stdout
11
+ * @throws {Error & { exitCode?: number|null }} if the program fails, with its stderr as message
12
+ */
13
+ export function run( command, args, { cwd, input, timeoutMs = 30_000 } = {} ) {
14
+ return new Promise( ( resolve, reject ) => {
15
+ const child = spawn( command, args, { cwd, stdio: [ input === undefined ? "ignore" : "pipe", "pipe", "pipe" ], timeout: timeoutMs } );
16
+ const stdout = [];
17
+ const stderr = [];
18
+
19
+ child.stdout.on( "data", chunk => stdout.push( chunk ) );
20
+ child.stderr.on( "data", chunk => stderr.push( chunk ) );
21
+ child.on( "error", reject );
22
+ child.on( "close", ( code, signal ) => {
23
+ if ( code === 0 ) {
24
+ resolve( Buffer.concat( stdout ).toString( "utf8" ) );
25
+ return;
26
+ }
27
+
28
+ const message = Buffer.concat( stderr ).toString( "utf8" ).trim() || ( signal ? `${command} was stopped by ${signal}` : `${command} exited with code ${code}` );
29
+ const error = /** @type {Error & { exitCode?: number|null }} */ new Error( message );
30
+
31
+ error.exitCode = code;
32
+ reject( error );
33
+ } );
34
+
35
+ if ( input !== undefined ) {
36
+ child.stdin.end( input );
37
+ }
38
+ } );
39
+ }
40
+
41
+ /**
42
+ * Runs a program attached to the terminal of the user, e.g. to have it prompt
43
+ * for a secret that this process never sees.
44
+ *
45
+ * @param {string} command
46
+ * @param {string[]} args
47
+ * @returns {Promise<number|null>} exit code
48
+ */
49
+ export function runInteractive( command, args ) {
50
+ return new Promise( ( resolve, reject ) => {
51
+ const child = spawn( command, args, { stdio: "inherit" } );
52
+
53
+ child.on( "error", reject );
54
+ child.on( "close", code => resolve( code ) );
55
+ } );
56
+ }
package/src/refs.js ADDED
@@ -0,0 +1,146 @@
1
+ import { defaultHost } from "./hosts.js";
2
+
3
+ /**
4
+ * A project at a registered GitLab instance.
5
+ *
6
+ * @typedef {object} RepoRef
7
+ * @property {import("./hosts.js").Host} host
8
+ * @property {string} path full path of the project, e.g. "group/subgroup/project"
9
+ */
10
+
11
+ /**
12
+ * The reference of a repository as tools hand it out and accept it.
13
+ *
14
+ * @param {RepoRef} repo
15
+ * @returns {string} e.g. "git.example.com:group/project"
16
+ */
17
+ export function formatRef( repo ) {
18
+ return `${repo.host.name}:${repo.path}`;
19
+ }
20
+
21
+ /**
22
+ * Checks and normalizes the path of a project.
23
+ *
24
+ * @param {string} raw
25
+ * @param {string} source text to name in errors
26
+ * @returns {string}
27
+ */
28
+ function projectPath( raw, source ) {
29
+ const path = raw.replace( /\/-\/.*$/, "" ).replace( /\/+$/, "" ).replace( /\.git$/, "" );
30
+ const segments = path.split( "/" );
31
+
32
+ if ( segments.length < 2 || segments.some( segment => !segment || segment === "." || segment === ".." || /[\u0000-\u001f\s\\?#%:@]/.test( segment ) ) ) {
33
+ throw new Error( `"${source}" doesn't name a project, expected <group>/<project>` );
34
+ }
35
+
36
+ return path;
37
+ }
38
+
39
+ /**
40
+ * Derives the repository from a clone or web URL, which has to belong to a
41
+ * registered host.
42
+ *
43
+ * @param {string} text https, ssh:// or scp-like URL, e.g. "git@git.example.com:group/project.git"
44
+ * @param {import("./hosts.js").Host[]} hosts
45
+ * @returns {RepoRef}
46
+ */
47
+ export function parseRemote( text, hosts ) {
48
+ const value = text.trim();
49
+
50
+ if ( /^https?:\/\//i.test( value ) ) {
51
+ const url = new URL( value );
52
+ const candidates = hosts
53
+ .map( host => ( { host, base: new URL( host.url ) } ) )
54
+ .filter( ( { base } ) => base.origin === url.origin && ( base.pathname === "/" || url.pathname.startsWith( `${base.pathname}/` ) ) )
55
+ .sort( ( a, b ) => b.base.pathname.length - a.base.pathname.length );
56
+
57
+ if ( candidates.length > 0 ) {
58
+ const { host, base } = candidates[0];
59
+ const rest = decodeURIComponent( url.pathname.slice( base.pathname === "/" ? 1 : base.pathname.length + 1 ) );
60
+
61
+ return { host, path: projectPath( rest, value ) };
62
+ }
63
+ } else {
64
+ let hostname;
65
+ let rest;
66
+
67
+ if ( /^ssh:\/\//i.test( value ) ) {
68
+ const url = new URL( value );
69
+
70
+ hostname = url.hostname;
71
+ rest = decodeURIComponent( url.pathname.replace( /^\/+/, "" ) );
72
+ } else {
73
+ const match = value.match( /^[^@\s/]+@([^:/\s]+):\/?(.+)$/ );
74
+
75
+ if ( match ) {
76
+ [ , hostname, rest ] = match;
77
+ }
78
+ }
79
+
80
+ if ( hostname ) {
81
+ const matching = hostsForSsh( hosts, hostname );
82
+
83
+ if ( matching.length > 1 ) {
84
+ throw new Error( `"${value}" matches several registered hosts (${matching.map( host => host.name ).join( ", " )}), use <host>:<group>/<project>` );
85
+ }
86
+
87
+ if ( matching.length === 1 ) {
88
+ return { host: matching[0], path: projectPath( rest, value ) };
89
+ }
90
+ }
91
+ }
92
+
93
+ throw new Error( `"${value}" isn't a repository of a registered GitLab host (${hosts.map( host => host.name ).join( ", " ) || "none registered"})` );
94
+ }
95
+
96
+ /**
97
+ * @param {import("./hosts.js").Host[]} hosts
98
+ * @param {string} hostname
99
+ * @returns {import("./hosts.js").Host[]}
100
+ */
101
+ function hostsForSsh( hosts, hostname ) {
102
+ const name = hostname.toLowerCase();
103
+
104
+ return hosts.filter( host => new URL( host.url ).hostname === name || host.sshHosts.includes( name ) );
105
+ }
106
+
107
+ /**
108
+ * Parses a repository reference: `<host>:<group>/<project>`, `<group>/<project>`
109
+ * for the default host, or a clone or web URL of a registered host.
110
+ *
111
+ * @param {string} text
112
+ * @param {import("./hosts.js").Host[]} hosts
113
+ * @returns {RepoRef}
114
+ */
115
+ export function parseRef( text, hosts ) {
116
+ const value = text.trim();
117
+
118
+ if ( /^[a-z][a-z0-9+.-]*:\/\//i.test( value ) || /^[^@\s/:]+@/.test( value ) ) {
119
+ return parseRemote( value, hosts );
120
+ }
121
+
122
+ const lower = value.toLowerCase();
123
+ const named = hosts
124
+ .filter( host => lower.startsWith( `${host.name}:` ) )
125
+ .sort( ( a, b ) => b.name.length - a.name.length )[0];
126
+
127
+ if ( named ) {
128
+ return { host: named, path: projectPath( value.slice( named.name.length + 1 ), value ) };
129
+ }
130
+
131
+ const colon = value.indexOf( ":" );
132
+
133
+ if ( colon > 0 && !value.slice( 0, colon ).includes( "/" ) ) {
134
+ throw new Error( `"${value.slice( 0, colon )}" isn't a registered GitLab host (${hosts.map( entry => entry.name ).join( ", " ) || "none registered"})` );
135
+ }
136
+
137
+ const host = defaultHost( hosts );
138
+
139
+ if ( !host ) {
140
+ throw new Error( hosts.length === 0 ?
141
+ "no GitLab host is registered, the user has to run \"mcp-gitlab host add <url>\"" :
142
+ `"${value}" doesn't name its host and there is no default host, use <host>:<group>/<project> with one of ${hosts.map( entry => entry.name ).join( ", " )}` );
143
+ }
144
+
145
+ return { host, path: projectPath( value, value ) };
146
+ }
package/src/secrets.js ADDED
@@ -0,0 +1,51 @@
1
+ /** Characters of GitLab access tokens. This also keeps a damaged entry from ending up in a header. */
2
+ const TOKEN_PATTERN = /^[\w.~+/=-]{20,300}$/;
3
+
4
+ /**
5
+ * Provides the access token of a host, read once per session from the
6
+ * credential store of the platform.
7
+ *
8
+ * @param {import("./platform/index.js").Platform} platform
9
+ */
10
+ export function createSecrets( platform ) {
11
+ /** @type {Map<string, string>} */
12
+ const cache = new Map();
13
+
14
+ return {
15
+ /**
16
+ * @param {import("./hosts.js").Host} host
17
+ * @returns {Promise<string>}
18
+ */
19
+ async tokenFor( host ) {
20
+ const cached = cache.get( host.name );
21
+
22
+ if ( cached ) {
23
+ return cached;
24
+ }
25
+
26
+ const token = await platform.readSecret( host.name );
27
+
28
+ if ( !token ) {
29
+ throw new Error( `no access token is stored for "${host.name}", the user has to run "mcp-gitlab token set ${host.name}"` );
30
+ }
31
+
32
+ if ( !TOKEN_PATTERN.test( token ) ) {
33
+ throw new Error( `the access token stored for "${host.name}" isn't valid, the user has to run "mcp-gitlab token set ${host.name}" again` );
34
+ }
35
+
36
+ cache.set( host.name, token );
37
+
38
+ return token;
39
+ },
40
+
41
+ /**
42
+ * Drops a cached token, e.g. after GitLab rejected it.
43
+ *
44
+ * @param {import("./hosts.js").Host} host
45
+ * @returns {void}
46
+ */
47
+ forget( host ) {
48
+ cache.delete( host.name );
49
+ },
50
+ };
51
+ }
package/src/server.js ADDED
@@ -0,0 +1,146 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { isAbsolute } from "node:path";
3
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
+ import { createAudit } from "./audit.js";
6
+ import { createConsent } from "./consent.js";
7
+ import { DeniedError } from "./errors.js";
8
+ import { pruneDownloads } from "./downloads.js";
9
+ import { detectRepo } from "./git.js";
10
+ import { createGitLabClient } from "./gitlab/client.js";
11
+ import { loadHosts } from "./hosts.js";
12
+ import { PERMISSIONS } from "./permissions/catalog.js";
13
+ import { allowsRepo, loadSettings, resolveProfile, selectedProfileName } from "./permissions/policy.js";
14
+ import { selectPlatform } from "./platform/index.js";
15
+ import { formatRef, parseRef } from "./refs.js";
16
+ import { createSecrets } from "./secrets.js";
17
+ import { allTools } from "./tools/index.js";
18
+ import { IMAGE, REPO_INPUT } from "./tools/shared.js";
19
+
20
+ export const VERSION = JSON.parse( readFileSync( new URL( "../package.json", import.meta.url ), "utf8" ) ).version;
21
+
22
+ const INSTRUCTIONS = `Tools for GitLab: repositories, files, merge requests, issues, wikis, pipelines and their schedules, artifacts, packages, container registries, environments, runners and CI/CD variables of gitlab.com and self-managed GitLab instances the user registered.
23
+ Repositories are referenced as "<host>:<group>/<project>", as repo_list returns them; "<group>/<project>" means the default host. Without "repo", tools use the local clone in "directory" or the working directory of the server.
24
+ Access tokens are never shown to you. Some actions need the user's confirmation in a dialog, and the user enters values of sensitive variables in a dialog, never you. If the user denies an action, don't retry it unless the user asks for it.`;
25
+
26
+ /**
27
+ * Selects the repository a tool works on: "repo", else the clone in
28
+ * "directory", else the working directory of the server.
29
+ *
30
+ * @param {{ repo?: string, directory?: string }} args
31
+ * @param {import("./hosts.js").Host[]} hosts
32
+ * @param {string} cwd
33
+ * @returns {Promise<import("./refs.js").RepoRef>}
34
+ */
35
+ async function selectRepo( { repo, directory }, hosts, cwd ) {
36
+ if ( repo ) {
37
+ return parseRef( repo, hosts );
38
+ }
39
+
40
+ if ( directory && !isAbsolute( directory ) ) {
41
+ throw new Error( "\"directory\" has to be an absolute path" );
42
+ }
43
+
44
+ return detectRepo( directory ?? cwd, hosts );
45
+ }
46
+
47
+ /**
48
+ * Creates the MCP server with the tools the active profile permits.
49
+ *
50
+ * @param {object} [options] dependencies to replace, e.g. in tests
51
+ * @param {import("./platform/index.js").Platform} [options.platform]
52
+ * @param {typeof fetch} [options.fetch]
53
+ * @param {string} [options.cwd]
54
+ * @param {NodeJS.ProcessEnv} [options.env]
55
+ * @param {ReturnType<typeof createAudit>} [options.audit]
56
+ * @returns {Promise<{ server: McpServer, profile: import("./permissions/policy.js").Profile, tools: string[] }>}
57
+ */
58
+ export async function createServer( { platform = selectPlatform(), fetch, cwd = process.cwd(), env = process.env, audit = createAudit() } = {} ) {
59
+ const settings = await loadSettings();
60
+ const profile = resolveProfile( selectedProfileName( settings, env ), settings );
61
+ const consent = createConsent( platform );
62
+ const gitlab = createGitLabClient( { secrets: createSecrets( platform ), consent, fetch } );
63
+ const server = new McpServer( { name: "mcp-gitlab", version: VERSION }, { instructions: INSTRUCTIONS } );
64
+ const tools = allTools.filter( tool => profile.permissions.has( tool.permission ) );
65
+
66
+ for ( const tool of tools ) {
67
+ server.registerTool( tool.name, {
68
+ title: tool.title,
69
+ description: tool.description,
70
+ inputSchema: tool.usesRepo ? { ...REPO_INPUT, ...tool.input } : tool.input,
71
+ annotations: {
72
+ title: tool.title,
73
+ readOnlyHint: !tool.mutates,
74
+ destructiveHint: Boolean( tool.destructive ),
75
+ openWorldHint: true,
76
+ },
77
+ }, async args => {
78
+ const started = new Date();
79
+ let repo;
80
+
81
+ try {
82
+ // read on every call, so hosts registered while the server runs are known
83
+ const hosts = await loadHosts();
84
+
85
+ if ( tool.usesRepo ) {
86
+ repo = await selectRepo( args, hosts, cwd );
87
+
88
+ if ( !allowsRepo( profile, formatRef( repo ) ) ) {
89
+ throw new DeniedError( `profile "${profile.name}" doesn't allow access to ${formatRef( repo )}` );
90
+ }
91
+ }
92
+
93
+ const context = { repo, hosts, gitlab, profile, audit, cwd, consent };
94
+ // refuse what would fail anyway before the user is asked to confirm it
95
+ await tool.precheck?.( args, context );
96
+
97
+ const mode = profile.confirm.get( tool.permission );
98
+
99
+ if ( mode && !await tool.asksUser?.( args, context ) ) {
100
+ const message = await tool.confirmMessage?.( args, context ) ??
101
+ `An agent wants to ${PERMISSIONS[tool.permission]} (${tool.name})${repo ? ` in ${formatRef( repo )}` : ""}.`;
102
+
103
+ await consent.confirm( tool.permission, message, mode );
104
+ }
105
+
106
+ const result = await tool.handler( args, context );
107
+
108
+ await audit.record( { started, tool: tool.name, repo: repo && formatRef( repo ), outcome: "ok", ms: Date.now() - started.getTime(), args } );
109
+
110
+ const content = [{ type: "text", text: JSON.stringify( result, null, "\t" ) }];
111
+
112
+ if ( result?.[IMAGE] ) {
113
+ content.push( { type: "image", ...result[IMAGE] } );
114
+ }
115
+
116
+ return { content };
117
+ } catch ( error ) {
118
+ const outcome = error instanceof DeniedError ? "denied" : "error";
119
+
120
+ await audit.record( { started, tool: tool.name, repo: repo && formatRef( repo ), outcome, ms: Date.now() - started.getTime(), error: error.message, args } );
121
+
122
+ return { isError: true, content: [{ type: "text", text: error.message }] };
123
+ }
124
+ } );
125
+ }
126
+
127
+ return { server, profile, tools: tools.map( tool => tool.name ) };
128
+ }
129
+
130
+ /**
131
+ * Runs the server on stdin/stdout, as agents start it.
132
+ *
133
+ * @returns {Promise<void>}
134
+ */
135
+ export async function serve() {
136
+ const audit = createAudit();
137
+
138
+ await audit.prune().catch( error => process.stderr.write( `mcp-gitlab: pruning the audit log failed: ${error.message}\n` ) );
139
+ await pruneDownloads().catch( error => process.stderr.write( `mcp-gitlab: pruning saved files failed: ${error.message}\n` ) );
140
+
141
+ const { server, profile, tools } = await createServer( { audit } );
142
+
143
+ process.stderr.write( `mcp-gitlab ${VERSION}: profile "${profile.name}" with ${tools.length} tools\n` );
144
+
145
+ await server.connect( new StdioServerTransport() );
146
+ }
package/src/session.js ADDED
@@ -0,0 +1,140 @@
1
+ import { rm } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { configDirectory, readJsonFile, writeJsonFile } from "./paths.js";
4
+
5
+ /**
6
+ * A session the user started with "mcp-gitlab session <duration>": approvals
7
+ * granted "for this session" while it lasts are kept in the configuration
8
+ * folder, so they survive restarts of the server and apply to every agent
9
+ * using it, until the session ends. Without such a session, approvals last as
10
+ * long as the server runs.
11
+ *
12
+ * @typedef {object} Session
13
+ * @property {string} started ISO time, identifies the session
14
+ * @property {string} expires ISO time
15
+ * @property {string[]} grants keys of the approvals granted, e.g. "host:gitlab.com"
16
+ */
17
+
18
+ const FILE = "session.json";
19
+
20
+ /** Longest session the user can start. */
21
+ export const MAX_SESSION_MS = 24 * 3_600_000;
22
+
23
+ /**
24
+ * Parses the duration of a session such as "8h", "90m" or "1h30m".
25
+ *
26
+ * @param {string|undefined} value
27
+ * @returns {number} milliseconds
28
+ */
29
+ export function parseDuration( value ) {
30
+ const match = String( value ?? "" ).trim().match( /^(?:(\d{1,3})h)?(?:(\d{1,4})m)?$/ );
31
+ const ms = match ? ( Number( match[1] ?? 0 ) * 3_600_000 ) + ( Number( match[2] ?? 0 ) * 60_000 ) : 0;
32
+
33
+ if ( !match || ms <= 0 ) {
34
+ throw new Error( `"${value}" isn't a duration such as "8h", "90m" or "1h30m"` );
35
+ }
36
+
37
+ if ( ms > MAX_SESSION_MS ) {
38
+ throw new Error( `a session lasts ${MAX_SESSION_MS / 3_600_000}h at most` );
39
+ }
40
+
41
+ return ms;
42
+ }
43
+
44
+ /**
45
+ * Accesses the session kept in the configuration folder.
46
+ *
47
+ * @param {object} [options]
48
+ * @param {() => Date} [options.now]
49
+ */
50
+ export function createSessionStore( { now = () => new Date() } = {} ) {
51
+ /**
52
+ * @returns {Promise<Session|null>} the session, if one is running
53
+ */
54
+ async function current() {
55
+ const session = await readJsonFile( FILE, null );
56
+
57
+ if ( !session || typeof session !== "object" || typeof session.started !== "string" || typeof session.expires !== "string" || !Array.isArray( session.grants ) ) {
58
+ return null;
59
+ }
60
+
61
+ const expires = new Date( session.expires ).getTime();
62
+
63
+ if ( Number.isNaN( expires ) || expires <= now().getTime() || expires - new Date( session.started ).getTime() > MAX_SESSION_MS ) {
64
+ return null;
65
+ }
66
+
67
+ return { started: session.started, expires: session.expires, grants: session.grants.filter( grant => typeof grant === "string" ) };
68
+ }
69
+
70
+ return {
71
+ current,
72
+
73
+ /**
74
+ * Starts a session, replacing a running one and its approvals.
75
+ *
76
+ * @param {number} ms duration
77
+ * @returns {Promise<Session>}
78
+ */
79
+ async start( ms ) {
80
+ if ( !( ms > 0 && ms <= MAX_SESSION_MS ) ) {
81
+ throw new Error( `a session lasts ${MAX_SESSION_MS / 3_600_000}h at most` );
82
+ }
83
+
84
+ const started = now();
85
+ const session = { started: started.toISOString(), expires: new Date( started.getTime() + ms ).toISOString(), grants: [] };
86
+
87
+ await writeJsonFile( FILE, session );
88
+
89
+ return session;
90
+ },
91
+
92
+ /**
93
+ * Ends the session, revoking the approvals granted for it.
94
+ *
95
+ * @returns {Promise<boolean>} false if no session was running
96
+ */
97
+ async end() {
98
+ const running = await current();
99
+
100
+ await rm( join( configDirectory(), FILE ), { force: true } );
101
+
102
+ return Boolean( running );
103
+ },
104
+
105
+ /**
106
+ * Keeps an approval for the rest of a session.
107
+ *
108
+ * @param {Session} session the session the user granted the approval for
109
+ * @param {string} key
110
+ * @returns {Promise<boolean>} false if that session isn't running anymore
111
+ */
112
+ async grant( session, key ) {
113
+ const running = await current();
114
+
115
+ if ( !running || running.started !== session.started ) {
116
+ return false;
117
+ }
118
+
119
+ if ( !running.grants.includes( key ) ) {
120
+ await writeJsonFile( FILE, { ...running, grants: [ ...running.grants, key ] } );
121
+ }
122
+
123
+ return true;
124
+ },
125
+ };
126
+ }
127
+
128
+ /**
129
+ * Describes when a session ends, for buttons and messages.
130
+ *
131
+ * @param {string} expires ISO time
132
+ * @param {Date} [now]
133
+ * @returns {string} e.g. "14:30" or "Fri 02:30"
134
+ */
135
+ export function formatUntil( expires, now = new Date() ) {
136
+ const time = new Date( expires );
137
+ const clock = time.toLocaleTimeString( "en-GB", { hour: "2-digit", minute: "2-digit" } );
138
+
139
+ return time.toDateString() === now.toDateString() ? clock : `${time.toLocaleDateString( "en-GB", { weekday: "short" } )} ${clock}`;
140
+ }
package/src/text.js ADDED
@@ -0,0 +1,68 @@
1
+ /** Bytes inspected to tell binary from text. */
2
+ const SNIFF_BYTES = 8000;
3
+
4
+ /**
5
+ * Decodes the content of a file: UTF-8 (with or without BOM), UTF-16 with BOM,
6
+ * else Windows-1252. Returns null for binary content.
7
+ *
8
+ * @param {Buffer} bytes
9
+ * @returns {{ text: string, encoding: string }|null}
10
+ */
11
+ export function decodeText( bytes ) {
12
+ if ( bytes[0] === 0xff && bytes[1] === 0xfe ) {
13
+ return { text: new TextDecoder( "utf-16le" ).decode( bytes.subarray( 2 ) ), encoding: "utf-16le" };
14
+ }
15
+
16
+ if ( bytes[0] === 0xfe && bytes[1] === 0xff ) {
17
+ return { text: new TextDecoder( "utf-16be" ).decode( bytes.subarray( 2 ) ), encoding: "utf-16be" };
18
+ }
19
+
20
+ if ( bytes.subarray( 0, SNIFF_BYTES ).includes( 0 ) ) {
21
+ return null;
22
+ }
23
+
24
+ try {
25
+ return { text: new TextDecoder( "utf-8", { fatal: true, ignoreBOM: false } ).decode( bytes ), encoding: "utf-8" };
26
+ } catch {
27
+ return { text: new TextDecoder( "windows-1252" ).decode( bytes ), encoding: "windows-1252" };
28
+ }
29
+ }
30
+
31
+ /**
32
+ * Returns a range of lines with line numbers, limited in lines and characters.
33
+ *
34
+ * @param {string} text
35
+ * @param {{ from?: number, lines?: number, maxChars?: number }} [options] `from` counts from 1
36
+ * @returns {{ content: string, from: number, to: number, totalLines: number, nextFrom: number|null }}
37
+ */
38
+ export function numberedLines( text, { from = 1, lines = 500, maxChars = 50_000 } = {} ) {
39
+ const all = text.split( /\r?\n/ );
40
+
41
+ if ( all.length > 1 && all[all.length - 1] === "" ) {
42
+ all.pop();
43
+ }
44
+
45
+ const width = String( all.length ).length;
46
+ const output = [];
47
+ let chars = 0;
48
+ let index = Math.max( from, 1 ) - 1;
49
+
50
+ for ( ; index < all.length && output.length < lines; index++ ) {
51
+ const line = `${String( index + 1 ).padStart( width )}\t${all[index]}`;
52
+
53
+ if ( chars + line.length > maxChars && output.length > 0 ) {
54
+ break;
55
+ }
56
+
57
+ output.push( line.length > maxChars ? `${line.slice( 0, maxChars )}… (line cut)` : line );
58
+ chars += line.length + 1;
59
+ }
60
+
61
+ return {
62
+ content: output.join( "\n" ),
63
+ from: Math.max( from, 1 ),
64
+ to: index,
65
+ totalLines: all.length,
66
+ nextFrom: index < all.length ? index + 1 : null,
67
+ };
68
+ }