@ajnart/self-host-testkit 0.0.0-stage → 1.2.1
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 +202 -0
- package/README.md +286 -2
- package/binary.mjs +40 -0
- package/examples/sonarr.mjs +20 -0
- package/index.d.mts +40 -0
- package/index.mjs +441 -0
- package/package.json +53 -5
- package/setup.mjs +85 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,287 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @ajnart/self-host-testkit
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Real, isolated Docker App fixtures for TypeScript and JavaScript integration
|
|
4
|
+
tests. Start an App through self-host's existing Setup, call its API, and close
|
|
5
|
+
the fixture. ESM only: use `import`, not CommonJS `require`. No runtime npm
|
|
6
|
+
dependencies and no test-runner dependency.
|
|
7
|
+
|
|
8
|
+
## Before you start
|
|
9
|
+
|
|
10
|
+
You need **Node.js 22+**, a running local **Docker Engine** and the **Docker
|
|
11
|
+
Compose v2 plugin** (`docker compose version`). Linux and macOS x64/arm64 are
|
|
12
|
+
supported; Docker must use a local Unix socket and enforce memory, CPU and PID
|
|
13
|
+
limits. Allow up to 5 GiB RAM and five CPUs per fixture, plus image/storage space.
|
|
14
|
+
First startup pulls images and can take several minutes.
|
|
15
|
+
|
|
16
|
+
For a published release, install the SDK as a dev dependency. Version 1.2.1 must
|
|
17
|
+
exist on npm and GitHub before using these commands; for an unpublished source
|
|
18
|
+
checkout, use the source workflow linked below instead:
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
npm install --save-dev @ajnart/self-host-testkit@1.2.1
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
This guide describes version 1.2.1. The older v1.2.0 tarball does not contain the setup command,
|
|
25
|
+
`TestkitError` export or safe startup reasons. For that release, extract
|
|
26
|
+
`self-host-testkit` from its platform archive, verify `checksums.txt`, and set
|
|
27
|
+
`SELF_HOST_TESTKIT_BINARY` to the helper's absolute path. For the improved source,
|
|
28
|
+
follow the [checkout quickstart](../README.md#typescript-install).
|
|
29
|
+
|
|
30
|
+
Version 1.2.0 used the unpublished package name `@self-host/testkit`. When
|
|
31
|
+
upgrading, change imports to `@ajnart/self-host-testkit`. The exact npm package
|
|
32
|
+
is also available as `self-host-testkit-1.2.1.tgz` on the matching GitHub release.
|
|
33
|
+
|
|
34
|
+
## Install the matching helper
|
|
35
|
+
|
|
36
|
+
After installing the SDK, run:
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
npm exec -- self-host-testkit-setup
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
This explicit setup downloads only the matching Linux/macOS helper, requires one
|
|
43
|
+
SHA-256 checksum entry and verifies the archive before extraction. It caches the
|
|
44
|
+
helper privately under `$XDG_CACHE_HOME/self-host-testkit/`, or
|
|
45
|
+
`~/.cache/self-host-testkit/`. It does not run Docker, modify PATH, require Go, or
|
|
46
|
+
download anything during package installation or import. Repeating setup reuses
|
|
47
|
+
the cached helper. `createSelfHost()` discovers it automatically.
|
|
48
|
+
|
|
49
|
+
To use a source-built or offline helper instead:
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
export SELF_HOST_TESTKIT_BINARY=/absolute/path/to/self-host-testkit
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Resolution order: `binary` option, `SELF_HOST_TESTKIT_BINARY`, the versioned
|
|
56
|
+
private cache, then `self-host-testkit` on PATH. Keep SDK, helper and Action on
|
|
57
|
+
the same release or immutable source commit. Never substitute the normal
|
|
58
|
+
`self-host` CLI: the helper is a separate executable.
|
|
59
|
+
|
|
60
|
+
## A small demo
|
|
61
|
+
|
|
62
|
+
Save this as `demo.mjs` and run `node demo.mjs` after installing the SDK/helper:
|
|
63
|
+
|
|
64
|
+
```javascript
|
|
65
|
+
import { createSelfHost } from "@ajnart/self-host-testkit";
|
|
66
|
+
|
|
67
|
+
const selfHost = createSelfHost();
|
|
68
|
+
try {
|
|
69
|
+
const sonarr = await selfHost.spinup("sonarr");
|
|
70
|
+
const response = await fetch(`${sonarr.url}/api/v3/system/status`, {
|
|
71
|
+
headers: { "X-Api-Key": await sonarr.getApiKey() },
|
|
72
|
+
signal: AbortSignal.timeout(10_000),
|
|
73
|
+
});
|
|
74
|
+
if (!response.ok) throw new Error("Sonarr rejected the request");
|
|
75
|
+
const status = await response.json();
|
|
76
|
+
if (status.appName !== "Sonarr") throw new Error("Unexpected App identity");
|
|
77
|
+
console.log(`Connected to Sonarr ${status.version}`);
|
|
78
|
+
} finally {
|
|
79
|
+
await selfHost.close();
|
|
80
|
+
}
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
The package also includes `examples/sonarr.mjs`. No API key appears in its output.
|
|
84
|
+
Cleanup uses ordinary `try/finally` or test-runner hooks, without requiring
|
|
85
|
+
TypeScript disposable libraries or newer JavaScript syntax.
|
|
86
|
+
|
|
87
|
+
## Vitest
|
|
88
|
+
|
|
89
|
+
Use your project's existing Vitest dependency. Set hook timeouts explicitly;
|
|
90
|
+
the default hook timeout is too short for image pulls and Setup.
|
|
91
|
+
|
|
92
|
+
```typescript
|
|
93
|
+
import { afterAll, beforeAll, expect, test } from "vitest";
|
|
94
|
+
import { createSelfHost, type App } from "@ajnart/self-host-testkit";
|
|
95
|
+
|
|
96
|
+
const selfHost = createSelfHost();
|
|
97
|
+
let sonarr: App;
|
|
98
|
+
|
|
99
|
+
beforeAll(async () => {
|
|
100
|
+
sonarr = await selfHost.spinup("sonarr");
|
|
101
|
+
}, 780_000);
|
|
102
|
+
|
|
103
|
+
afterAll(async () => {
|
|
104
|
+
await selfHost.close();
|
|
105
|
+
}, 160_000);
|
|
106
|
+
|
|
107
|
+
test("Sonarr returns its authenticated identity", async () => {
|
|
108
|
+
const response = await fetch(`${sonarr.url}/api/v3/system/status`, {
|
|
109
|
+
headers: { "X-Api-Key": await sonarr.getApiKey() },
|
|
110
|
+
signal: AbortSignal.timeout(10_000),
|
|
111
|
+
});
|
|
112
|
+
expect(response.ok).toBe(true);
|
|
113
|
+
const status = await response.json();
|
|
114
|
+
expect(status.appName).toBe("Sonarr");
|
|
115
|
+
expect(status.version).toMatch(/^\d+\./);
|
|
116
|
+
});
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
This verifies identity, not complete integration acceptance. Your adapter tests
|
|
120
|
+
should also check meaningful data and invalid-key behavior. Do not print raw
|
|
121
|
+
response bodies, credentials or API keys in failing assertions.
|
|
122
|
+
|
|
123
|
+
## API
|
|
124
|
+
|
|
125
|
+
```typescript
|
|
126
|
+
const selfHost = createSelfHost({
|
|
127
|
+
timeoutMs: 720_000,
|
|
128
|
+
});
|
|
129
|
+
const app = await selfHost.spinup("sonarr", {
|
|
130
|
+
image: "lscr.io/linuxserver/sonarr:latest",
|
|
131
|
+
});
|
|
132
|
+
const apiKey = await app.getApiKey();
|
|
133
|
+
const credentials = await app.credentials();
|
|
134
|
+
const info = await app.info();
|
|
135
|
+
await app.close();
|
|
136
|
+
await selfHost.close();
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
- `createSelfHost({ binary?, timeoutMs?, manifest? })`: creates a fixture manager
|
|
140
|
+
without starting Docker. `timeoutMs` defaults to 720,000 and accepts 1–840,000.
|
|
141
|
+
It bounds the App lifetime, not just startup; cleanup time is reserved within
|
|
142
|
+
that budget. Do not share a fixture across a longer-running suite.
|
|
143
|
+
- `spinup(id, { image? })`: awaits Setup and returns an App with its loopback
|
|
144
|
+
`url`. Each call gets a separate helper and Project; image overrides apply to
|
|
145
|
+
the selected App, not its dependency images.
|
|
146
|
+
- `getApiKey(name?)`: explicitly reads a private key; the default name is
|
|
147
|
+
`api_key`. Use the App's declared key name when it differs.
|
|
148
|
+
- `credentials()`: `username`, `password`, `email`, `apiKey`. Fields are
|
|
149
|
+
non-enumerable and JSON/inspection redact the object, but reading a field
|
|
150
|
+
returns the actual secret. Never log it or upload it.
|
|
151
|
+
- `info()`: public `id`, `url`, `image`, `imageId`, `repoDigests`. Record image
|
|
152
|
+
digests when reproducibility matters; `latest` is deliberately mutable.
|
|
153
|
+
- `app.close()` closes one fixture; `selfHost.close()` closes all its fixtures.
|
|
154
|
+
Both are idempotent. Successful cleanup removes owned containers, networks,
|
|
155
|
+
anonymous container volumes and private storage. Named volumes are rejected.
|
|
156
|
+
- `manifest`: optional absolute recovery filename in an existing owned mode-0700
|
|
157
|
+
directory. Otherwise the SDK creates a private temporary parent. The helper
|
|
158
|
+
records ownership before startup. Keep recovery manifests and Project data
|
|
159
|
+
private; never upload them as public CI artifacts.
|
|
160
|
+
|
|
161
|
+
## Errors and recovery
|
|
162
|
+
|
|
163
|
+
```typescript
|
|
164
|
+
import { TestkitError } from "@ajnart/self-host-testkit";
|
|
165
|
+
|
|
166
|
+
try {
|
|
167
|
+
await selfHost.spinup("sonarr");
|
|
168
|
+
} catch (error: unknown) {
|
|
169
|
+
if (error instanceof TestkitError && error.code === "BINARY") {
|
|
170
|
+
throw new Error(
|
|
171
|
+
"Install the matching testkit helper before running this suite",
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
throw error;
|
|
175
|
+
}
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
Errors expose a sanitized `code`: `BINARY`, `PROTOCOL`, `STATE`, `START`,
|
|
179
|
+
`CREDENTIALS`, `INFO`, `CLEANUP`, `TIMEOUT` or `TRANSPORT`. They never include raw
|
|
180
|
+
provider output, helper stderr or executable paths. A `START` error may also
|
|
181
|
+
have an allowlisted `reason` and a corresponding safe hint: `APP`, `OPTIONS`,
|
|
182
|
+
`DOCKER`, `CAPABILITIES`, `PORT`, `OWNERSHIP`, `LIMITS`, `LOCK`, `UNSUPPORTED`,
|
|
183
|
+
`STORAGE`, `CONTAINER` or `SETUP`. These distinguish unsupported fixtures from
|
|
184
|
+
failed Setup without forwarding provider messages.
|
|
185
|
+
|
|
186
|
+
- **BINARY:** run the explicit setup command or set the helper path.
|
|
187
|
+
- **START:** check local Docker/Compose, supported App prerequisites, resource
|
|
188
|
+
limits and image availability. Apps needing a Manual step, hardware, external
|
|
189
|
+
account, host networking, socket mount or named volume fail rather than skip.
|
|
190
|
+
- **TIMEOUT:** allow cold-pull time within the bounded lifetime, lower concurrent
|
|
191
|
+
fixture count, or use a smaller supported App.
|
|
192
|
+
- **CLEANUP:** retain the private manifest and retry scoped recovery after helper
|
|
193
|
+
exit. For CI, use the always-run step below. For local recovery, pass the
|
|
194
|
+
matching helper `--cleanup-manifest /absolute/private/manifest.jsonl`.
|
|
195
|
+
|
|
196
|
+
If you supply a manifest, retain its path outside the test for recovery. SIGKILL,
|
|
197
|
+
runner loss and daemon outages can prevent cleanup; disposable runners are best.
|
|
198
|
+
Do not run Docker prune or broad container/volume removal to recover fixtures.
|
|
199
|
+
|
|
200
|
+
## GitHub Actions
|
|
201
|
+
|
|
202
|
+
```yaml
|
|
203
|
+
jobs:
|
|
204
|
+
integration:
|
|
205
|
+
runs-on: ubuntu-latest
|
|
206
|
+
timeout-minutes: 20
|
|
207
|
+
steps:
|
|
208
|
+
- uses: actions/checkout@v7
|
|
209
|
+
- uses: actions/setup-node@v6
|
|
210
|
+
with:
|
|
211
|
+
node-version: 22
|
|
212
|
+
- run: npm ci
|
|
213
|
+
- id: testkit
|
|
214
|
+
uses: ajnart/self-host/testkit@v1.2.1
|
|
215
|
+
- run: npx vitest run path/to/live-integration.test.ts
|
|
216
|
+
- name: Clean up owned fixtures
|
|
217
|
+
if: always() && steps.testkit.outcome == 'success'
|
|
218
|
+
run: '"$SELF_HOST_TESTKIT_BINARY" --cleanup-manifest "$SELF_HOST_TESTKIT_MANIFEST"'
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
Pin the Action to a full commit SHA and install the SDK from the same source or
|
|
222
|
+
release. The Action requires Bash, Python 3 and tar; it verifies and extracts a
|
|
223
|
+
patched Go toolchain privately for its own build without changing the caller's
|
|
224
|
+
PATH or `GOTOOLCHAIN`. It does not require a preinstalled Go launcher and works
|
|
225
|
+
when the caller sets `GOSUMDB=off`. Standard GitHub-hosted Ubuntu runners supply
|
|
226
|
+
these prerequisites.
|
|
227
|
+
The original v1.2.0 Action does not yet preserve the caller's Go environment.
|
|
228
|
+
|
|
229
|
+
Outputs: `binary-path`, `sdk-path`, `manifest-path`. Job environment:
|
|
230
|
+
`SELF_HOST_TESTKIT_BINARY`, `SELF_HOST_TESTKIT_SDK`, `SELF_HOST_TESTKIT_MANIFEST`.
|
|
231
|
+
The Action does not install the npm dependency or start Apps. Its committed SDK
|
|
232
|
+
exports and source-built helper match its ref. Set bounded matrix concurrency;
|
|
233
|
+
each simultaneous fixture adds its own resource budget. Always-run cleanup is
|
|
234
|
+
mandatory because composite Actions have no finally hook.
|
|
235
|
+
|
|
236
|
+
## Go
|
|
237
|
+
|
|
238
|
+
```bash
|
|
239
|
+
go get github.com/ajnart/self-host@v1.2.1
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
```go
|
|
243
|
+
peer, err := testkit.Start(ctx, testkit.Options{App: "sonarr"})
|
|
244
|
+
if err != nil {
|
|
245
|
+
return err
|
|
246
|
+
}
|
|
247
|
+
defer func() {
|
|
248
|
+
cleanup, cancel := context.WithTimeout(context.Background(), time.Minute)
|
|
249
|
+
defer cancel()
|
|
250
|
+
if err := peer.Close(cleanup); err != nil {
|
|
251
|
+
log.Print("fixture cleanup failed; retain its private recovery path")
|
|
252
|
+
}
|
|
253
|
+
}()
|
|
254
|
+
key, err := peer.GetAPIKey(ctx, "")
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
Import `github.com/ajnart/self-host/testkit`; it is part of the root module, not a
|
|
258
|
+
separate Go module. `RecoveryPath()` is private operational metadata. Go startup
|
|
259
|
+
errors preserve known safe testkit causes and context cancellation while hiding
|
|
260
|
+
raw provider errors. The current source removes storage on successful `Close`;
|
|
261
|
+
v1.2.0 retains it until a dead-process `Cleanup` pass.
|
|
262
|
+
|
|
263
|
+
## Developing this package
|
|
264
|
+
|
|
265
|
+
From the repository root:
|
|
266
|
+
|
|
267
|
+
```bash
|
|
268
|
+
bun install --frozen-lockfile
|
|
269
|
+
bun run --cwd testkit/node build
|
|
270
|
+
bun run --cwd testkit/node check
|
|
271
|
+
bun run --cwd testkit/node lint
|
|
272
|
+
bun test testkit/node/tests
|
|
273
|
+
npm pack ./testkit/node --ignore-scripts --dry-run
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
`src/*.mts` is the source of truth. TypeScript generates the committed `.mjs`
|
|
277
|
+
exports and `.d.mts` declarations; CI verifies they remain current. No hand-kept
|
|
278
|
+
parallel declarations. The tarball includes only runtime modules, public types,
|
|
279
|
+
license, README and the demo; it does not ship development dependencies or tests.
|
|
280
|
+
`SELF_HOST_RELEASE_VERSION=X.Y.Z node testkit/node/pack.mjs` validates the package
|
|
281
|
+
allowlist and adds its checksum to release artifacts. Build first. Version bumps
|
|
282
|
+
and npm trusted publishing require a separate release decision; never overwrite
|
|
283
|
+
v1.2.0 assets with a modified package.
|
|
284
|
+
|
|
285
|
+
Backup/Restore caching and live Docker acceptance are deferred, not implied by
|
|
286
|
+
passing SDK transport tests. The downstream Homarr weekly checklist is tracked
|
|
287
|
+
in [draft PR #7446](https://github.com/homarr-labs/homarr/pull/7446).
|
package/binary.mjs
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { existsSync, lstatSync, readFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { isAbsolute, join } from "node:path";
|
|
4
|
+
const metadata = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8"));
|
|
5
|
+
if (typeof metadata !== "object" ||
|
|
6
|
+
metadata === null ||
|
|
7
|
+
!("version" in metadata) ||
|
|
8
|
+
typeof metadata.version !== "string" ||
|
|
9
|
+
!/^\d+\.\d+\.\d+$/.test(metadata.version)) {
|
|
10
|
+
throw new Error("Invalid testkit package version.");
|
|
11
|
+
}
|
|
12
|
+
export const version = metadata.version;
|
|
13
|
+
export function binaryDirectory() {
|
|
14
|
+
let cache = join(homedir(), ".cache");
|
|
15
|
+
if (process.env.XDG_CACHE_HOME && isAbsolute(process.env.XDG_CACHE_HOME)) {
|
|
16
|
+
cache = process.env.XDG_CACHE_HOME;
|
|
17
|
+
}
|
|
18
|
+
return join(cache, "self-host-testkit", version, `${process.platform}-${process.arch}`);
|
|
19
|
+
}
|
|
20
|
+
export function privateDirectory(path) {
|
|
21
|
+
const info = lstatSync(path);
|
|
22
|
+
return (info.isDirectory() &&
|
|
23
|
+
info.uid === process.getuid?.() &&
|
|
24
|
+
(info.mode & 0o077) === 0);
|
|
25
|
+
}
|
|
26
|
+
export function installedBinary() {
|
|
27
|
+
const directory = binaryDirectory();
|
|
28
|
+
const binary = join(directory, "self-host-testkit");
|
|
29
|
+
if (!existsSync(binary))
|
|
30
|
+
return "self-host-testkit";
|
|
31
|
+
const info = lstatSync(binary);
|
|
32
|
+
if (!privateDirectory(directory) ||
|
|
33
|
+
!info.isFile() ||
|
|
34
|
+
info.uid !== process.getuid?.() ||
|
|
35
|
+
(info.mode & 0o077) !== 0 ||
|
|
36
|
+
(info.mode & 0o100) === 0) {
|
|
37
|
+
throw new Error("Testkit helper cache is not private; set SELF_HOST_TESTKIT_BINARY explicitly.");
|
|
38
|
+
}
|
|
39
|
+
return binary;
|
|
40
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { createSelfHost } from "@ajnart/self-host-testkit";
|
|
2
|
+
|
|
3
|
+
const selfHost = createSelfHost();
|
|
4
|
+
|
|
5
|
+
try {
|
|
6
|
+
const sonarr = await selfHost.spinup("sonarr");
|
|
7
|
+
const response = await fetch(`${sonarr.url}/api/v3/system/status`, {
|
|
8
|
+
headers: { "X-Api-Key": await sonarr.getApiKey() },
|
|
9
|
+
signal: AbortSignal.timeout(10_000),
|
|
10
|
+
});
|
|
11
|
+
if (!response.ok)
|
|
12
|
+
throw new Error("Sonarr rejected the authenticated request.");
|
|
13
|
+
const status = await response.json();
|
|
14
|
+
if (status.appName !== "Sonarr" || typeof status.version !== "string") {
|
|
15
|
+
throw new Error("Sonarr returned an unexpected identity.");
|
|
16
|
+
}
|
|
17
|
+
console.log(`Connected to Sonarr ${status.version}.`);
|
|
18
|
+
} finally {
|
|
19
|
+
await selfHost.close();
|
|
20
|
+
}
|
package/index.d.mts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export interface Credentials {
|
|
2
|
+
readonly username: string;
|
|
3
|
+
readonly password: string;
|
|
4
|
+
readonly email: string;
|
|
5
|
+
readonly apiKey: string;
|
|
6
|
+
}
|
|
7
|
+
export interface AppInfo {
|
|
8
|
+
readonly id: string;
|
|
9
|
+
readonly url: string;
|
|
10
|
+
readonly image: string;
|
|
11
|
+
readonly imageId: string;
|
|
12
|
+
readonly repoDigests: string[];
|
|
13
|
+
}
|
|
14
|
+
export interface App {
|
|
15
|
+
readonly url: string;
|
|
16
|
+
getApiKey(name?: string): Promise<string>;
|
|
17
|
+
credentials(): Promise<Credentials>;
|
|
18
|
+
info(): Promise<AppInfo>;
|
|
19
|
+
close(): Promise<void>;
|
|
20
|
+
}
|
|
21
|
+
export interface SpinupOptions {
|
|
22
|
+
image?: string;
|
|
23
|
+
}
|
|
24
|
+
export interface SelfHost {
|
|
25
|
+
spinup(app: string, options?: SpinupOptions): Promise<App>;
|
|
26
|
+
close(): Promise<void>;
|
|
27
|
+
}
|
|
28
|
+
export interface SelfHostOptions {
|
|
29
|
+
binary?: string;
|
|
30
|
+
timeoutMs?: number;
|
|
31
|
+
manifest?: string;
|
|
32
|
+
}
|
|
33
|
+
export type TestkitErrorCode = "PROTOCOL" | "STATE" | "START" | "CREDENTIALS" | "INFO" | "CLEANUP" | "TIMEOUT" | "TRANSPORT" | "BINARY";
|
|
34
|
+
export type TestkitStartupReason = "APP" | "OPTIONS" | "DOCKER" | "CAPABILITIES" | "PORT" | "OWNERSHIP" | "LIMITS" | "LOCK" | "UNSUPPORTED" | "STORAGE" | "CONTAINER" | "SETUP";
|
|
35
|
+
export declare class TestkitError extends Error {
|
|
36
|
+
readonly code: TestkitErrorCode;
|
|
37
|
+
readonly reason: TestkitStartupReason | undefined;
|
|
38
|
+
constructor(code: TestkitErrorCode, reason?: TestkitStartupReason);
|
|
39
|
+
}
|
|
40
|
+
export declare function createSelfHost(options?: SelfHostOptions): SelfHost;
|
package/index.mjs
ADDED
|
@@ -0,0 +1,441 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { mkdtempSync, rmdirSync, unlinkSync } from "node:fs";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { isAbsolute, join } from "node:path";
|
|
6
|
+
import { inspect } from "node:util";
|
|
7
|
+
import { installedBinary } from "./binary.mjs";
|
|
8
|
+
const MAX_MESSAGE = 65536;
|
|
9
|
+
const CLEANUP_TIMEOUT = 50000;
|
|
10
|
+
const messages = new Map([
|
|
11
|
+
["PROTOCOL", "Invalid testkit protocol."],
|
|
12
|
+
["STATE", "Fixture is not available."],
|
|
13
|
+
["START", "Fixture startup failed."],
|
|
14
|
+
["CREDENTIALS", "Fixture credentials are not available."],
|
|
15
|
+
["INFO", "Fixture information is not available."],
|
|
16
|
+
["CLEANUP", "Fixture cleanup failed; run manifest cleanup."],
|
|
17
|
+
["TIMEOUT", "Fixture operation timed out."],
|
|
18
|
+
["TRANSPORT", "Testkit helper transport failed."],
|
|
19
|
+
[
|
|
20
|
+
"BINARY",
|
|
21
|
+
"Testkit helper not found. Run self-host-testkit-setup or set SELF_HOST_TESTKIT_BINARY.",
|
|
22
|
+
],
|
|
23
|
+
]);
|
|
24
|
+
const startupReasons = new Map([
|
|
25
|
+
["APP", "Choose one supported Catalog App."],
|
|
26
|
+
["OPTIONS", "Check the selected image and lifetime options."],
|
|
27
|
+
["DOCKER", "Check the local Unix Docker socket, daemon and Compose plugin."],
|
|
28
|
+
["CAPABILITIES", "Docker must support memory, CPU quota and PID limits."],
|
|
29
|
+
["PORT", "A required local port could not be reserved."],
|
|
30
|
+
["OWNERSHIP", "Fixture ownership or isolation could not be verified."],
|
|
31
|
+
[
|
|
32
|
+
"LIMITS",
|
|
33
|
+
"Container resource caps or selected image could not be verified.",
|
|
34
|
+
],
|
|
35
|
+
["LOCK", "The private startup lock is unavailable."],
|
|
36
|
+
[
|
|
37
|
+
"UNSUPPORTED",
|
|
38
|
+
"This App's Compose configuration or operations are unsupported.",
|
|
39
|
+
],
|
|
40
|
+
[
|
|
41
|
+
"STORAGE",
|
|
42
|
+
"Private fixture storage or the recovery manifest is unavailable.",
|
|
43
|
+
],
|
|
44
|
+
["CONTAINER", "The selected App container is absent."],
|
|
45
|
+
["SETUP", "App Setup failed or requires a Manual step."],
|
|
46
|
+
]);
|
|
47
|
+
export class TestkitError extends Error {
|
|
48
|
+
code;
|
|
49
|
+
reason;
|
|
50
|
+
constructor(code, reason) {
|
|
51
|
+
let message = messages.get(code);
|
|
52
|
+
if (code === "START" && reason)
|
|
53
|
+
message = `${message} ${startupReasons.get(reason)}`;
|
|
54
|
+
super(message);
|
|
55
|
+
this.name = "TestkitError";
|
|
56
|
+
this.code = code;
|
|
57
|
+
this.reason = reason;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
function fault(code, reason) {
|
|
61
|
+
return new TestkitError(code, reason);
|
|
62
|
+
}
|
|
63
|
+
function record(value) {
|
|
64
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
65
|
+
}
|
|
66
|
+
function strings(value, fields) {
|
|
67
|
+
return (record(value) && fields.every((field) => typeof value[field] === "string"));
|
|
68
|
+
}
|
|
69
|
+
function privateCredentials(value) {
|
|
70
|
+
if (!strings(value, ["username", "password", "email", "apiKey"])) {
|
|
71
|
+
throw fault("PROTOCOL");
|
|
72
|
+
}
|
|
73
|
+
const credentials = Object.create(null);
|
|
74
|
+
for (const field of ["username", "password", "email", "apiKey"]) {
|
|
75
|
+
Object.defineProperty(credentials, field, { get: () => value[field] });
|
|
76
|
+
}
|
|
77
|
+
Object.defineProperty(credentials, "toJSON", {
|
|
78
|
+
value: () => "[Credentials]",
|
|
79
|
+
});
|
|
80
|
+
Object.defineProperty(credentials, inspect.custom, {
|
|
81
|
+
value: () => "[Credentials]",
|
|
82
|
+
});
|
|
83
|
+
return Object.freeze(credentials);
|
|
84
|
+
}
|
|
85
|
+
function runCleanup(binary, manifest, owner) {
|
|
86
|
+
return new Promise((resolve, reject) => {
|
|
87
|
+
const child = spawn(binary, ["--cleanup-manifest", manifest, "--owner", owner], { stdio: "ignore" });
|
|
88
|
+
const timer = setTimeout(() => {
|
|
89
|
+
child.kill("SIGKILL");
|
|
90
|
+
reject(fault("CLEANUP"));
|
|
91
|
+
}, CLEANUP_TIMEOUT);
|
|
92
|
+
child.once("error", () => {
|
|
93
|
+
clearTimeout(timer);
|
|
94
|
+
reject(fault("CLEANUP"));
|
|
95
|
+
});
|
|
96
|
+
child.once("exit", (code) => {
|
|
97
|
+
clearTimeout(timer);
|
|
98
|
+
if (code === 0)
|
|
99
|
+
resolve(undefined);
|
|
100
|
+
else
|
|
101
|
+
reject(fault("CLEANUP"));
|
|
102
|
+
});
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
class Bridge {
|
|
106
|
+
#child;
|
|
107
|
+
#binary;
|
|
108
|
+
#manifest;
|
|
109
|
+
#owner = randomBytes(16).toString("hex");
|
|
110
|
+
#pending = new Map();
|
|
111
|
+
#sequence = 0;
|
|
112
|
+
#buffer = Buffer.alloc(0);
|
|
113
|
+
#failed = false;
|
|
114
|
+
#closing;
|
|
115
|
+
#exited;
|
|
116
|
+
#spawned = false;
|
|
117
|
+
constructor(binary, manifest) {
|
|
118
|
+
this.#binary = binary;
|
|
119
|
+
this.#manifest = manifest;
|
|
120
|
+
this.#child = spawn(binary, ["--manifest", manifest, "--owner", this.#owner], { stdio: ["pipe", "pipe", "ignore"] });
|
|
121
|
+
this.#child.once("spawn", () => {
|
|
122
|
+
this.#spawned = true;
|
|
123
|
+
});
|
|
124
|
+
this.#exited = new Promise((resolve) => {
|
|
125
|
+
this.#child.once("exit", () => {
|
|
126
|
+
this.#fail("TRANSPORT");
|
|
127
|
+
resolve(undefined);
|
|
128
|
+
});
|
|
129
|
+
this.#child.once("error", (error) => {
|
|
130
|
+
let code = "TRANSPORT";
|
|
131
|
+
if (error.code === "ENOENT")
|
|
132
|
+
code = "BINARY";
|
|
133
|
+
this.#fail(code);
|
|
134
|
+
resolve(undefined);
|
|
135
|
+
});
|
|
136
|
+
});
|
|
137
|
+
this.#child.stdin.on("error", () => this.#fail("TRANSPORT"));
|
|
138
|
+
this.#child.stdout.on("data", (chunk) => this.#receive(chunk));
|
|
139
|
+
}
|
|
140
|
+
#fail(code) {
|
|
141
|
+
this.#failed = true;
|
|
142
|
+
this.#buffer = Buffer.alloc(0);
|
|
143
|
+
for (const pending of this.#pending.values()) {
|
|
144
|
+
clearTimeout(pending.timer);
|
|
145
|
+
pending.reject(fault(code));
|
|
146
|
+
}
|
|
147
|
+
this.#pending.clear();
|
|
148
|
+
this.#child.kill("SIGTERM");
|
|
149
|
+
}
|
|
150
|
+
#receive(chunk) {
|
|
151
|
+
if (this.#failed)
|
|
152
|
+
return;
|
|
153
|
+
if (this.#buffer.length + chunk.length > MAX_MESSAGE) {
|
|
154
|
+
this.#fail("PROTOCOL");
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
this.#buffer = Buffer.concat([this.#buffer, chunk]);
|
|
158
|
+
let newline = this.#buffer.indexOf(10);
|
|
159
|
+
while (newline !== -1) {
|
|
160
|
+
const line = this.#buffer.subarray(0, newline).toString("utf8");
|
|
161
|
+
this.#buffer = this.#buffer.subarray(newline + 1);
|
|
162
|
+
try {
|
|
163
|
+
const response = JSON.parse(line);
|
|
164
|
+
if (!record(response) ||
|
|
165
|
+
response.version !== 1 ||
|
|
166
|
+
typeof response.id !== "number" ||
|
|
167
|
+
!Number.isSafeInteger(response.id) ||
|
|
168
|
+
!this.#pending.has(response.id) ||
|
|
169
|
+
Object.hasOwn(response, "error") === Object.hasOwn(response, "result")) {
|
|
170
|
+
throw fault("PROTOCOL");
|
|
171
|
+
}
|
|
172
|
+
const pending = this.#pending.get(response.id);
|
|
173
|
+
if (!pending)
|
|
174
|
+
throw fault("PROTOCOL");
|
|
175
|
+
this.#pending.delete(response.id);
|
|
176
|
+
clearTimeout(pending.timer);
|
|
177
|
+
if (Object.hasOwn(response, "error")) {
|
|
178
|
+
if (!record(response.error) ||
|
|
179
|
+
typeof response.error.code !== "string" ||
|
|
180
|
+
!isErrorCode(response.error.code)) {
|
|
181
|
+
pending.reject(fault("PROTOCOL"));
|
|
182
|
+
this.#fail("PROTOCOL");
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
let reason;
|
|
186
|
+
if (response.error.reason !== undefined) {
|
|
187
|
+
if (response.error.code !== "START" ||
|
|
188
|
+
typeof response.error.reason !== "string" ||
|
|
189
|
+
!isStartupReason(response.error.reason)) {
|
|
190
|
+
pending.reject(fault("PROTOCOL"));
|
|
191
|
+
this.#fail("PROTOCOL");
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
reason = response.error.reason;
|
|
195
|
+
}
|
|
196
|
+
pending.reject(fault(response.error.code, reason));
|
|
197
|
+
}
|
|
198
|
+
else {
|
|
199
|
+
pending.resolve(response.result);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
catch {
|
|
203
|
+
this.#fail("PROTOCOL");
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
newline = this.#buffer.indexOf(10);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
request(method, params = {}, timeout = 35000) {
|
|
210
|
+
if (this.#failed)
|
|
211
|
+
return Promise.reject(fault("TRANSPORT"));
|
|
212
|
+
const id = ++this.#sequence;
|
|
213
|
+
return new Promise((resolve, reject) => {
|
|
214
|
+
const timer = setTimeout(() => this.#fail("TIMEOUT"), timeout);
|
|
215
|
+
this.#pending.set(id, { resolve, reject, timer });
|
|
216
|
+
const message = JSON.stringify({ version: 1, id, method, params });
|
|
217
|
+
if (Buffer.byteLength(message) >= MAX_MESSAGE) {
|
|
218
|
+
this.#fail("PROTOCOL");
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
this.#child.stdin.write(`${message}\n`, (error) => {
|
|
222
|
+
if (error)
|
|
223
|
+
this.#fail("TRANSPORT");
|
|
224
|
+
});
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
close() {
|
|
228
|
+
if (!this.#closing)
|
|
229
|
+
this.#closing = this.#close();
|
|
230
|
+
return this.#closing;
|
|
231
|
+
}
|
|
232
|
+
async #close() {
|
|
233
|
+
let failure;
|
|
234
|
+
if (!this.#failed) {
|
|
235
|
+
try {
|
|
236
|
+
await this.request("close", {}, CLEANUP_TIMEOUT);
|
|
237
|
+
}
|
|
238
|
+
catch {
|
|
239
|
+
failure = fault("CLEANUP");
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
this.#child.stdin.end();
|
|
243
|
+
const kill = setTimeout(() => this.#child.kill("SIGKILL"), CLEANUP_TIMEOUT);
|
|
244
|
+
await this.#exited;
|
|
245
|
+
clearTimeout(kill);
|
|
246
|
+
if (!this.#spawned)
|
|
247
|
+
return;
|
|
248
|
+
try {
|
|
249
|
+
await runCleanup(this.#binary, this.#manifest, this.#owner);
|
|
250
|
+
}
|
|
251
|
+
catch {
|
|
252
|
+
failure = fault("CLEANUP");
|
|
253
|
+
}
|
|
254
|
+
if (failure)
|
|
255
|
+
throw failure;
|
|
256
|
+
}
|
|
257
|
+
[inspect.custom]() {
|
|
258
|
+
return "[TestkitBridge]";
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
class AppHandle {
|
|
262
|
+
#bridge;
|
|
263
|
+
#url;
|
|
264
|
+
#closed = false;
|
|
265
|
+
constructor(bridge, url) {
|
|
266
|
+
this.#bridge = bridge;
|
|
267
|
+
this.#url = url;
|
|
268
|
+
}
|
|
269
|
+
get url() {
|
|
270
|
+
return this.#url;
|
|
271
|
+
}
|
|
272
|
+
async getApiKey(name = "") {
|
|
273
|
+
if (this.#closed || typeof name !== "string")
|
|
274
|
+
throw fault("STATE");
|
|
275
|
+
const value = await this.#bridge.request("getApiKey", { name });
|
|
276
|
+
if (!strings(value, ["apiKey"]))
|
|
277
|
+
throw fault("PROTOCOL");
|
|
278
|
+
return value.apiKey;
|
|
279
|
+
}
|
|
280
|
+
async credentials() {
|
|
281
|
+
if (this.#closed)
|
|
282
|
+
throw fault("STATE");
|
|
283
|
+
return privateCredentials(await this.#bridge.request("credentials"));
|
|
284
|
+
}
|
|
285
|
+
async info() {
|
|
286
|
+
if (this.#closed)
|
|
287
|
+
throw fault("STATE");
|
|
288
|
+
const value = await this.#bridge.request("info");
|
|
289
|
+
if (!strings(value, ["id", "url", "image", "imageId"]) ||
|
|
290
|
+
!Array.isArray(value.repoDigests) ||
|
|
291
|
+
!value.repoDigests.every((digest) => typeof digest === "string")) {
|
|
292
|
+
throw fault("PROTOCOL");
|
|
293
|
+
}
|
|
294
|
+
return {
|
|
295
|
+
id: value.id,
|
|
296
|
+
url: value.url,
|
|
297
|
+
image: value.image,
|
|
298
|
+
imageId: value.imageId,
|
|
299
|
+
repoDigests: [...value.repoDigests],
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
async close() {
|
|
303
|
+
this.#closed = true;
|
|
304
|
+
await this.#bridge.close();
|
|
305
|
+
}
|
|
306
|
+
toJSON() {
|
|
307
|
+
return "[App]";
|
|
308
|
+
}
|
|
309
|
+
[inspect.custom]() {
|
|
310
|
+
return "[App]";
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
class SelfHostHandle {
|
|
314
|
+
#binary;
|
|
315
|
+
#timeout;
|
|
316
|
+
#manifest;
|
|
317
|
+
#directory;
|
|
318
|
+
#bridges = new Set();
|
|
319
|
+
#starts = new Set();
|
|
320
|
+
#closed = false;
|
|
321
|
+
#closing;
|
|
322
|
+
constructor(options) {
|
|
323
|
+
this.#binary =
|
|
324
|
+
options.binary ??
|
|
325
|
+
process.env.SELF_HOST_TESTKIT_BINARY ??
|
|
326
|
+
installedBinary();
|
|
327
|
+
this.#timeout = options.timeoutMs ?? 720000;
|
|
328
|
+
if (typeof this.#binary !== "string" ||
|
|
329
|
+
this.#binary.length === 0 ||
|
|
330
|
+
!Number.isSafeInteger(this.#timeout) ||
|
|
331
|
+
this.#timeout < 1 ||
|
|
332
|
+
this.#timeout > 840000) {
|
|
333
|
+
throw fault("PROTOCOL");
|
|
334
|
+
}
|
|
335
|
+
const manifest = options.manifest ?? process.env.SELF_HOST_TESTKIT_MANIFEST;
|
|
336
|
+
if (manifest !== undefined &&
|
|
337
|
+
(typeof manifest !== "string" || !isAbsolute(manifest))) {
|
|
338
|
+
throw fault("PROTOCOL");
|
|
339
|
+
}
|
|
340
|
+
if (manifest) {
|
|
341
|
+
this.#manifest = manifest;
|
|
342
|
+
}
|
|
343
|
+
else {
|
|
344
|
+
try {
|
|
345
|
+
this.#directory = mkdtempSync(join(tmpdir(), "self-host-testkit-"));
|
|
346
|
+
this.#manifest = join(this.#directory, "manifest.jsonl");
|
|
347
|
+
}
|
|
348
|
+
catch {
|
|
349
|
+
throw fault("START");
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
async spinup(app, options) {
|
|
354
|
+
const selected = options ?? {};
|
|
355
|
+
if (this.#closed)
|
|
356
|
+
throw fault("STATE");
|
|
357
|
+
if (!record(selected) ||
|
|
358
|
+
typeof app !== "string" ||
|
|
359
|
+
!/^[a-z0-9][a-z0-9-]{0,63}$/.test(app) ||
|
|
360
|
+
(selected.image !== undefined && typeof selected.image !== "string")) {
|
|
361
|
+
throw fault("PROTOCOL");
|
|
362
|
+
}
|
|
363
|
+
const bridge = new Bridge(this.#binary, this.#manifest);
|
|
364
|
+
this.#bridges.add(bridge);
|
|
365
|
+
const start = this.#spinup(bridge, app, selected);
|
|
366
|
+
this.#starts.add(start);
|
|
367
|
+
try {
|
|
368
|
+
return await start;
|
|
369
|
+
}
|
|
370
|
+
finally {
|
|
371
|
+
this.#starts.delete(start);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
async #spinup(bridge, app, options) {
|
|
375
|
+
try {
|
|
376
|
+
const value = await bridge.request("spinup", {
|
|
377
|
+
app,
|
|
378
|
+
image: options.image,
|
|
379
|
+
timeoutMs: this.#timeout,
|
|
380
|
+
}, this.#timeout + 1000);
|
|
381
|
+
if (!strings(value, ["url"]) ||
|
|
382
|
+
!/^http:\/\/127\.0\.0\.1:\d+\/?$/.test(value.url)) {
|
|
383
|
+
throw fault("PROTOCOL");
|
|
384
|
+
}
|
|
385
|
+
if (this.#closed)
|
|
386
|
+
throw fault("STATE");
|
|
387
|
+
return new AppHandle(bridge, value.url);
|
|
388
|
+
}
|
|
389
|
+
catch (error) {
|
|
390
|
+
await bridge.close();
|
|
391
|
+
throw error;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
close() {
|
|
395
|
+
if (!this.#closing) {
|
|
396
|
+
this.#closed = true;
|
|
397
|
+
this.#closing = this.#close();
|
|
398
|
+
}
|
|
399
|
+
return this.#closing;
|
|
400
|
+
}
|
|
401
|
+
async #close() {
|
|
402
|
+
const results = await Promise.allSettled([...this.#bridges].map((bridge) => bridge.close()));
|
|
403
|
+
await Promise.allSettled([...this.#starts]);
|
|
404
|
+
if (results.some((result) => result.status === "rejected"))
|
|
405
|
+
throw fault("CLEANUP");
|
|
406
|
+
if (this.#directory) {
|
|
407
|
+
try {
|
|
408
|
+
try {
|
|
409
|
+
unlinkSync(this.#manifest);
|
|
410
|
+
}
|
|
411
|
+
catch (error) {
|
|
412
|
+
if (!(error instanceof Error) ||
|
|
413
|
+
!("code" in error) ||
|
|
414
|
+
error.code !== "ENOENT")
|
|
415
|
+
throw error;
|
|
416
|
+
}
|
|
417
|
+
rmdirSync(this.#directory);
|
|
418
|
+
}
|
|
419
|
+
catch {
|
|
420
|
+
throw fault("CLEANUP");
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
toJSON() {
|
|
425
|
+
return "[SelfHost]";
|
|
426
|
+
}
|
|
427
|
+
[inspect.custom]() {
|
|
428
|
+
return "[SelfHost]";
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
function isErrorCode(value) {
|
|
432
|
+
return [...messages.keys()].some((code) => code === value);
|
|
433
|
+
}
|
|
434
|
+
function isStartupReason(value) {
|
|
435
|
+
return [...startupReasons.keys()].some((reason) => reason === value);
|
|
436
|
+
}
|
|
437
|
+
export function createSelfHost(options = {}) {
|
|
438
|
+
if (!record(options))
|
|
439
|
+
throw fault("PROTOCOL");
|
|
440
|
+
return new SelfHostHandle(options);
|
|
441
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,54 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@ajnart/self-host-testkit",
|
|
3
|
+
"version": "1.2.1",
|
|
4
|
+
"description": "Real, isolated Docker App fixtures for Node.js and TypeScript integration tests",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./index.mjs",
|
|
7
|
+
"types": "./index.d.mts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./index.d.mts",
|
|
11
|
+
"import": "./index.mjs"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"bin": { "self-host-testkit-setup": "./setup.mjs" },
|
|
15
|
+
"files": [
|
|
16
|
+
"index.mjs",
|
|
17
|
+
"index.d.mts",
|
|
18
|
+
"binary.mjs",
|
|
19
|
+
"setup.mjs",
|
|
20
|
+
"examples/sonarr.mjs",
|
|
21
|
+
"README.md",
|
|
22
|
+
"LICENSE"
|
|
23
|
+
],
|
|
24
|
+
"scripts": {
|
|
25
|
+
"build": "tsc -p tsconfig.json && cp ../../LICENSE LICENSE",
|
|
26
|
+
"check": "tsc -p tsconfig.json --noEmit",
|
|
27
|
+
"lint": "biome check .",
|
|
28
|
+
"test": "bun test ./tests",
|
|
29
|
+
"prepack": "npm run build"
|
|
30
|
+
},
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"@biomejs/biome": "1.9.4",
|
|
33
|
+
"@types/node": "^26.6.4",
|
|
34
|
+
"typescript": "^6.0.3"
|
|
35
|
+
},
|
|
36
|
+
"publishConfig": { "access": "public" },
|
|
37
|
+
"keywords": [
|
|
38
|
+
"docker",
|
|
39
|
+
"compose",
|
|
40
|
+
"integration-testing",
|
|
41
|
+
"fixtures",
|
|
42
|
+
"self-hosted",
|
|
43
|
+
"typescript"
|
|
44
|
+
],
|
|
45
|
+
"homepage": "https://github.com/ajnart/self-host/tree/main/testkit",
|
|
46
|
+
"bugs": "https://github.com/ajnart/self-host/issues",
|
|
47
|
+
"engines": { "node": ">=22" },
|
|
48
|
+
"license": "Apache-2.0",
|
|
49
|
+
"repository": {
|
|
50
|
+
"type": "git",
|
|
51
|
+
"url": "https://github.com/ajnart/self-host.git",
|
|
52
|
+
"directory": "testkit/node"
|
|
53
|
+
}
|
|
54
|
+
}
|
package/setup.mjs
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { spawnSync } from "node:child_process";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { chmodSync, lstatSync, mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync, } from "node:fs";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { binaryDirectory, installedBinary, privateDirectory, version, } from "./binary.mjs";
|
|
7
|
+
async function download(url, limit) {
|
|
8
|
+
const response = await fetch(url, { signal: AbortSignal.timeout(60_000) });
|
|
9
|
+
if (!response.ok || !response.body)
|
|
10
|
+
throw new Error("Release download failed; check connectivity and that the matching release exists.");
|
|
11
|
+
const chunks = [];
|
|
12
|
+
let size = 0;
|
|
13
|
+
for await (const chunk of response.body) {
|
|
14
|
+
size += chunk.length;
|
|
15
|
+
if (size > limit) {
|
|
16
|
+
throw new Error("Release download exceeds the size limit.");
|
|
17
|
+
}
|
|
18
|
+
chunks.push(chunk);
|
|
19
|
+
}
|
|
20
|
+
return Buffer.concat(chunks);
|
|
21
|
+
}
|
|
22
|
+
async function setup() {
|
|
23
|
+
if (process.argv.slice(2).length !== 0) {
|
|
24
|
+
if (process.argv.length === 3 && process.argv[2] === "--help") {
|
|
25
|
+
console.log("self-host-testkit-setup: download and verify the matching helper for Linux/macOS x64/arm64. Requires tar. Does not start Docker or modify PATH.");
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
throw new Error("Usage: self-host-testkit-setup [--help]");
|
|
29
|
+
}
|
|
30
|
+
if (!(process.platform === "linux" || process.platform === "darwin") ||
|
|
31
|
+
!(process.arch === "x64" || process.arch === "arm64")) {
|
|
32
|
+
throw new Error("Testkit supports Linux and macOS on x64 or arm64. On Windows, use WSL2 with a local Unix Docker socket.");
|
|
33
|
+
}
|
|
34
|
+
const directory = binaryDirectory();
|
|
35
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
36
|
+
if (!privateDirectory(directory))
|
|
37
|
+
throw new Error("Testkit helper cache must be private and owned by the current user.");
|
|
38
|
+
if (installedBinary() !== "self-host-testkit") {
|
|
39
|
+
console.log(`Testkit helper ${version} is already installed.`);
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
let arch = process.arch;
|
|
43
|
+
if (arch === "x64")
|
|
44
|
+
arch = "amd64";
|
|
45
|
+
const archive = `self-host_${version}_${process.platform}_${arch}.tar.gz`;
|
|
46
|
+
const base = `https://github.com/ajnart/self-host/releases/download/v${version}`;
|
|
47
|
+
console.log(`Downloading and verifying testkit helper ${version} for ${process.platform}/${arch}…`);
|
|
48
|
+
const checksums = (await download(`${base}/checksums.txt`, 1024 * 1024)).toString("utf8");
|
|
49
|
+
const matches = checksums
|
|
50
|
+
.split("\n")
|
|
51
|
+
.map((line) => line.trim().split(/\s+/))
|
|
52
|
+
.filter((entry) => entry[1] === archive);
|
|
53
|
+
if (matches.length !== 1 || !/^[a-f0-9]{64}$/.test(matches[0]?.[0] ?? ""))
|
|
54
|
+
throw new Error("Release lacks an unambiguous helper checksum.");
|
|
55
|
+
const data = await download(`${base}/${archive}`, 128 * 1024 * 1024);
|
|
56
|
+
if (createHash("sha256").update(data).digest("hex") !== matches[0]?.[0])
|
|
57
|
+
throw new Error("Helper checksum mismatch; nothing installed.");
|
|
58
|
+
const staging = mkdtempSync(join(directory, ".download-"));
|
|
59
|
+
try {
|
|
60
|
+
const path = join(staging, archive);
|
|
61
|
+
writeFileSync(path, data, { mode: 0o600 });
|
|
62
|
+
const result = spawnSync("tar", ["-xzf", path, "-C", staging, "self-host-testkit"], { stdio: "ignore", timeout: 30_000 });
|
|
63
|
+
if (result.status !== 0)
|
|
64
|
+
throw new Error("Helper extraction failed; make sure tar is installed.");
|
|
65
|
+
const binary = join(staging, "self-host-testkit");
|
|
66
|
+
if (!lstatSync(binary).isFile())
|
|
67
|
+
throw new Error("Release did not contain a regular helper binary.");
|
|
68
|
+
chmodSync(binary, 0o700);
|
|
69
|
+
renameSync(binary, join(directory, "self-host-testkit"));
|
|
70
|
+
}
|
|
71
|
+
finally {
|
|
72
|
+
rmSync(staging, { recursive: true, force: true });
|
|
73
|
+
}
|
|
74
|
+
console.log("Helper ready. createSelfHost() will find it automatically; no PATH or environment changes needed.");
|
|
75
|
+
}
|
|
76
|
+
try {
|
|
77
|
+
await setup();
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
let message = "Unknown setup failure.";
|
|
81
|
+
if (error instanceof Error)
|
|
82
|
+
message = error.message;
|
|
83
|
+
console.error("Testkit setup failed.", message);
|
|
84
|
+
process.exitCode = 1;
|
|
85
|
+
}
|