@quantile-co/factory-github 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Quantile LLC
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.
@@ -0,0 +1,31 @@
1
+ export interface Execution {
2
+ logFile?: string;
3
+ append?: boolean;
4
+ signal?: AbortSignal;
5
+ }
6
+ export type Execute = (program: string, args: readonly string[], execution?: Execution) => Promise<string>;
7
+ export interface ActionInput {
8
+ planFile: string;
9
+ logFile: string;
10
+ signal?: AbortSignal;
11
+ }
12
+ export type Action = (input: ActionInput) => Promise<void>;
13
+ export interface TransportOptions {
14
+ bucket: string;
15
+ repositoryId: string;
16
+ runId: string;
17
+ attempt: string;
18
+ scratchDirectory: string;
19
+ signal?: AbortSignal;
20
+ }
21
+ export declare class CommandFailure extends Error {
22
+ readonly exitCode: number;
23
+ constructor(exitCode: number, message: string);
24
+ }
25
+ export declare function processRunner(environment: NodeJS.ProcessEnv): Execute;
26
+ export declare function plan(options: TransportOptions & {
27
+ summaryFile: string;
28
+ }, action: Action, execute: Execute): Promise<string>;
29
+ export declare function apply(options: TransportOptions & {
30
+ planReference: string;
31
+ }, action: Action, execute: Execute): Promise<void>;
package/dist/index.js ADDED
@@ -0,0 +1,194 @@
1
+ import { spawn } from "node:child_process";
2
+ import { appendFileSync, chmodSync, closeSync, lstatSync, mkdirSync, openSync, rmSync } from "node:fs";
3
+ import { constants } from "node:os";
4
+ import { isAbsolute, join } from "node:path";
5
+ // src/index.ts
6
+ var CommandFailure = class extends Error {
7
+ exitCode;
8
+ constructor(exitCode, message) {
9
+ super(message);
10
+ this.exitCode = exitCode;
11
+ }
12
+ };
13
+ function processRunner(environment) {
14
+ return (program, args, options = {}) => new Promise((resolve, reject) => {
15
+ if (options.signal?.aborted) {
16
+ reject(new CommandFailure(130, "Command cancelled"));
17
+ return;
18
+ }
19
+ const fd = options.logFile ? openSync(options.logFile, options.append ? "a" : "w", 384) : void 0;
20
+ const grouped = process.platform !== "win32";
21
+ const child = spawn(program, [...args], {
22
+ env: environment,
23
+ detached: grouped,
24
+ stdio: [
25
+ "ignore",
26
+ fd ?? "pipe",
27
+ fd ?? "pipe"
28
+ ]
29
+ });
30
+ let cancelled = false;
31
+ let failedToSpawn = false;
32
+ let killTimer;
33
+ const terminate = (signal) => {
34
+ if (!child.pid) return;
35
+ try {
36
+ if (grouped) process.kill(-child.pid, signal);
37
+ else child.kill(signal);
38
+ } catch (error) {
39
+ if (error.code !== "ESRCH") throw error;
40
+ }
41
+ };
42
+ const cancel = () => {
43
+ cancelled = true;
44
+ terminate("SIGTERM");
45
+ killTimer = setTimeout(() => terminate("SIGKILL"), 5e3);
46
+ killTimer.unref();
47
+ };
48
+ options.signal?.addEventListener("abort", cancel, { once: true });
49
+ const output = [];
50
+ child.stdout?.on("data", (data) => output.push(data));
51
+ child.stderr?.resume();
52
+ child.on("error", () => {
53
+ failedToSpawn = true;
54
+ });
55
+ child.on("close", (code, signal) => {
56
+ options.signal?.removeEventListener("abort", cancel);
57
+ if (killTimer) clearTimeout(killTimer);
58
+ if (cancelled) terminate("SIGKILL");
59
+ if (fd !== void 0) closeSync(fd);
60
+ const status = code && code > 0 ? code : signal ? 128 + constants.signals[signal] : cancelled ? 130 : failedToSpawn ? 1 : 0;
61
+ if (status === 0) resolve(Buffer.concat(output).toString("utf8").trim());
62
+ else reject(new CommandFailure(status, cancelled ? "Command cancelled" : `${program} failed`));
63
+ });
64
+ });
65
+ }
66
+ function validate(options) {
67
+ if (!/^[a-z0-9][a-z0-9._-]*$/.test(options.bucket)) throw new Error("Invalid state bucket");
68
+ for (const value of [
69
+ options.repositoryId,
70
+ options.runId,
71
+ options.attempt
72
+ ]) if (!/^[1-9][0-9]*$/.test(value)) throw new Error("Invalid repository/run/attempt ID");
73
+ if (!isAbsolute(options.scratchDirectory)) throw new Error("Runner scratch directory must be absolute");
74
+ }
75
+ function privatePaths(options, phase) {
76
+ const directory = join(options.scratchDirectory, "saved-plan");
77
+ try {
78
+ mkdirSync(directory, { mode: 448 });
79
+ } catch (error) {
80
+ if (error.code === "EEXIST") throw new Error("Private scratch path already exists");
81
+ throw error;
82
+ }
83
+ const planFile = join(directory, "plan.tfplan");
84
+ const logFile = join(directory, `${phase}.log`);
85
+ try {
86
+ closeSync(openSync(logFile, "wx", 384));
87
+ } catch (error) {
88
+ rmSync(directory, {
89
+ recursive: true,
90
+ force: true
91
+ });
92
+ throw error;
93
+ }
94
+ return {
95
+ directory,
96
+ planFile,
97
+ logFile
98
+ };
99
+ }
100
+ function requirePlan(path) {
101
+ const info = lstatSync(path, { throwIfNoEntry: false });
102
+ if (!info?.isFile() || info.size === 0) throw new Error("No regular saved plan produced");
103
+ chmodSync(path, 384);
104
+ }
105
+ function base(options) {
106
+ return `gs://${options.bucket}/plans/${options.repositoryId}`;
107
+ }
108
+ async function failureLog(execute, logFile, destination) {
109
+ try {
110
+ await execute("gcloud", [
111
+ "storage",
112
+ "cp",
113
+ logFile,
114
+ destination,
115
+ "--if-generation-match=0",
116
+ "--quiet"
117
+ ], { signal: AbortSignal.timeout(1e4) });
118
+ } catch {}
119
+ }
120
+ async function plan(options, action, execute) {
121
+ validate(options);
122
+ if (!isAbsolute(options.summaryFile)) throw new Error("Step summary path must be absolute");
123
+ const paths = privatePaths(options, "plan");
124
+ const destination = `${base(options)}/${options.runId}/${options.attempt}`;
125
+ try {
126
+ await action({
127
+ ...paths,
128
+ signal: options.signal
129
+ });
130
+ requirePlan(paths.planFile);
131
+ await execute("gcloud", [
132
+ "storage",
133
+ "cp",
134
+ "--recursive",
135
+ paths.directory,
136
+ `${destination}/`,
137
+ "--if-generation-match=0",
138
+ "--quiet"
139
+ ], { signal: options.signal });
140
+ const generation = await execute("gcloud", [
141
+ "storage",
142
+ "objects",
143
+ "describe",
144
+ `${destination}/saved-plan/plan.tfplan`,
145
+ "--raw",
146
+ "--format=value(generation)"
147
+ ], { signal: options.signal });
148
+ if (!/^[1-9][0-9]*$/.test(generation)) throw new Error("Invalid saved-plan generation");
149
+ const reference = `${options.runId}/${options.attempt}/${generation}`;
150
+ appendFileSync(options.summaryFile, `Plan reference: ${reference}\n`, { mode: 384 });
151
+ return reference;
152
+ } catch (error) {
153
+ await failureLog(execute, paths.logFile, `${destination}/plan.log`);
154
+ throw error;
155
+ } finally {
156
+ rmSync(paths.directory, {
157
+ recursive: true,
158
+ force: true
159
+ });
160
+ }
161
+ }
162
+ async function apply(options, action, execute) {
163
+ validate(options);
164
+ const reference = /^([1-9][0-9]*)\/([1-9][0-9]*)\/([1-9][0-9]*)$/.exec(options.planReference);
165
+ if (!reference) throw new Error("Expected reviewed run/attempt/generation");
166
+ const source = `${base(options)}/${reference[1]}/${reference[2]}/saved-plan/plan.tfplan#${reference[3]}`;
167
+ const paths = privatePaths(options, "apply");
168
+ try {
169
+ await execute("gcloud", [
170
+ "storage",
171
+ "cp",
172
+ source,
173
+ paths.planFile,
174
+ "--quiet"
175
+ ], {
176
+ logFile: paths.logFile,
177
+ signal: options.signal
178
+ });
179
+ requirePlan(paths.planFile);
180
+ await action({
181
+ ...paths,
182
+ signal: options.signal
183
+ });
184
+ } catch (error) {
185
+ await failureLog(execute, paths.logFile, `${base(options)}/apply/${options.runId}/${options.attempt}/apply.log`);
186
+ throw error;
187
+ } finally {
188
+ rmSync(paths.directory, {
189
+ recursive: true,
190
+ force: true
191
+ });
192
+ }
193
+ }
194
+ export { CommandFailure, apply, plan, processRunner };
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
2
  "name": "@quantile-co/factory-github",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "license": "MIT",
5
+ "description": "Private saved-plan transport for repository-owned deployment commands.",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=24"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/quantile-co/factory.git",
13
+ "directory": "packages/github"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public",
17
+ "registry": "https://registry.npmjs.org/"
18
+ },
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "default": "./dist/index.js"
23
+ }
24
+ },
25
+ "files": [
26
+ "dist"
27
+ ],
28
+ "scripts": {
29
+ "build": "vite build",
30
+ "check": "tsc -p tsconfig.json --noEmit",
31
+ "test": "vitest run --maxWorkers=4"
32
+ }
6
33
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.