@kubb/studio 5.6.0 → 5.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +80 -169
- package/dist/index.cjs +1452 -964
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +102 -406
- package/dist/index.js +1427 -947
- package/dist/index.js.map +1 -1
- package/dist/protocol-P0znFp9w.d.ts +626 -0
- package/dist/protocol.cjs +13 -13
- package/dist/protocol.cjs.map +1 -1
- package/dist/protocol.d.ts +2 -628
- package/dist/protocol.js +12 -14
- package/dist/protocol.js.map +1 -1
- package/package.json +7 -12
- package/dist/configFile-dJtYeqX1.cjs +0 -567
- package/dist/configFile-dJtYeqX1.cjs.map +0 -1
- package/dist/configFile-zhp5DQIe.js +0 -566
- package/dist/configFile-zhp5DQIe.js.map +0 -1
- package/dist/resolveConfig-CjF6j-3y.cjs +0 -399
- package/dist/resolveConfig-CjF6j-3y.cjs.map +0 -1
- package/dist/resolveConfig-DOUv_Tid.js +0 -352
- package/dist/resolveConfig-DOUv_Tid.js.map +0 -1
- package/dist/rolldown-runtime-qbf5tadS.cjs +0 -38
- package/dist/snapshotPackage-BFjiRhGd.cjs +0 -177
- package/dist/snapshotPackage-BFjiRhGd.cjs.map +0 -1
- package/dist/snapshotPackage-BwZ8IJX-.js +0 -176
- package/dist/snapshotPackage-BwZ8IJX-.js.map +0 -1
- package/dist/url-DC87bYiU.cjs +0 -19
- package/dist/url-DC87bYiU.cjs.map +0 -1
- package/dist/url-DhFfJpxp.js +0 -14
- package/dist/url-DhFfJpxp.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,19 +1,47 @@
|
|
|
1
1
|
import "./rolldown-runtime-CRm0XQPb.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
7
|
-
import process$1 from "node:process";
|
|
8
|
-
import path, { isAbsolute, relative, resolve, sep } from "node:path";
|
|
9
|
-
import { mkdtemp, rm } from "node:fs/promises";
|
|
10
|
-
import { FetchError, ofetch } from "ofetch";
|
|
11
|
-
import { stripVTControlCharacters, styleText } from "node:util";
|
|
12
|
-
import { createStorage } from "unstorage";
|
|
13
|
-
import fsDriver from "unstorage/drivers/fs";
|
|
2
|
+
import { AGENT_INSTANCE_HEADER, AGENT_SOCKET_PATH, AgentCloseCode, GENERATION_GONE_MESSAGE, MAX_PAGE_LINES, MAX_SNAPSHOT_BYTES, generationEventTypes } from "./protocol.js";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import { createHash, hash, randomUUID } from "node:crypto";
|
|
5
|
+
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
14
6
|
import { tmpdir } from "node:os";
|
|
7
|
+
import path, { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
8
|
+
import process$1 from "node:process";
|
|
9
|
+
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
10
|
+
import { pathToFileURL } from "node:url";
|
|
11
|
+
import { existsSync } from "node:fs";
|
|
15
12
|
import { Diagnostics, Hookable, cacheStorage, createKubb, fsStorage, memoryStorage, resolveCacheDir } from "@kubb/core";
|
|
16
13
|
import { RpcTarget, newWebSocketRpcSession } from "capnweb";
|
|
14
|
+
import { builders, detectCodeFormat, generateCode, parseModule } from "magicast";
|
|
15
|
+
import { promisify, stripVTControlCharacters } from "node:util";
|
|
16
|
+
import { ofetch } from "ofetch";
|
|
17
|
+
import { gzip } from "node:zlib";
|
|
18
|
+
//#region ../../internals/utils/src/casing.ts
|
|
19
|
+
/**
|
|
20
|
+
* Shared implementation for camelCase and PascalCase conversion.
|
|
21
|
+
* Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
|
|
22
|
+
* and capitalizes each word according to `pascal`.
|
|
23
|
+
*
|
|
24
|
+
* When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
|
|
25
|
+
*/
|
|
26
|
+
function toCamelOrPascal(text, pascal) {
|
|
27
|
+
return text.trim().replace(/([a-z\d])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/(\d)([a-z])/g, "$1 $2").split(/[\s\-_./\\:]+/).filter(Boolean).map((word, i) => {
|
|
28
|
+
if (word.length > 1 && word === word.toUpperCase()) return word;
|
|
29
|
+
return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
|
|
30
|
+
}).join("").replace(/[^a-zA-Z0-9]/g, "");
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Converts `text` to camelCase.
|
|
34
|
+
*
|
|
35
|
+
* @example Word boundaries
|
|
36
|
+
* `camelCase('hello-world') // 'helloWorld'`
|
|
37
|
+
*
|
|
38
|
+
* @example With a prefix
|
|
39
|
+
* `camelCase('tag', { prefix: 'create' }) // 'createTag'`
|
|
40
|
+
*/
|
|
41
|
+
function camelCase(text, { prefix = "", suffix = "" } = {}) {
|
|
42
|
+
return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
|
|
43
|
+
}
|
|
44
|
+
//#endregion
|
|
17
45
|
//#region ../../internals/utils/src/errors.ts
|
|
18
46
|
/**
|
|
19
47
|
* Coerces an unknown thrown value to an `Error` instance.
|
|
@@ -42,6 +70,91 @@ function getErrorMessage(value) {
|
|
|
42
70
|
return value instanceof Error ? value.message : String(value);
|
|
43
71
|
}
|
|
44
72
|
//#endregion
|
|
73
|
+
//#region ../../internals/utils/src/runtime.ts
|
|
74
|
+
/**
|
|
75
|
+
* Detects the JavaScript runtime executing the current process and exposes its name and version.
|
|
76
|
+
*
|
|
77
|
+
* Prefer the shared {@link runtime} instance over constructing your own.
|
|
78
|
+
*/
|
|
79
|
+
var Runtime = class {
|
|
80
|
+
/**
|
|
81
|
+
* `true` when the current process is running under Bun.
|
|
82
|
+
*
|
|
83
|
+
* Detection keys off the global `Bun` object rather than `process.versions`,
|
|
84
|
+
* because Bun polyfills `process.versions.node` for Node compatibility and would
|
|
85
|
+
* otherwise look like Node.
|
|
86
|
+
*
|
|
87
|
+
* @example
|
|
88
|
+
* ```ts
|
|
89
|
+
* if (runtime.isBun) {
|
|
90
|
+
* await Bun.write(path, data)
|
|
91
|
+
* }
|
|
92
|
+
* ```
|
|
93
|
+
*/
|
|
94
|
+
get isBun() {
|
|
95
|
+
return typeof Bun !== "undefined";
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* `true` when the current process is running under Deno.
|
|
99
|
+
*/
|
|
100
|
+
get isDeno() {
|
|
101
|
+
return typeof globalThis.Deno !== "undefined";
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* `true` when the current process is running under Node.
|
|
105
|
+
*
|
|
106
|
+
* Bun and Deno are excluded first so a polyfilled `process` does not register as Node.
|
|
107
|
+
*/
|
|
108
|
+
get isNode() {
|
|
109
|
+
return !this.isBun && !this.isDeno && typeof process !== "undefined" && process.versions?.node != null;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Name of the runtime executing the current process.
|
|
113
|
+
*
|
|
114
|
+
* @example
|
|
115
|
+
* ```ts
|
|
116
|
+
* runtime.name // 'bun' when run with `bun kubb`, 'node' otherwise
|
|
117
|
+
* ```
|
|
118
|
+
*/
|
|
119
|
+
get name() {
|
|
120
|
+
if (this.isBun) return "bun";
|
|
121
|
+
if (this.isDeno) return "deno";
|
|
122
|
+
return "node";
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Version of the active runtime, or an empty string when it cannot be read.
|
|
126
|
+
*
|
|
127
|
+
* @example
|
|
128
|
+
* ```ts
|
|
129
|
+
* runtime.version // '1.3.11' under Bun, '22.22.2' under Node
|
|
130
|
+
* ```
|
|
131
|
+
*/
|
|
132
|
+
get version() {
|
|
133
|
+
if (this.isBun) return process.versions.bun ?? "";
|
|
134
|
+
if (this.isDeno) return globalThis.Deno?.version?.deno ?? "";
|
|
135
|
+
return process.versions?.node ?? "";
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
/**
|
|
139
|
+
* Shared {@link Runtime} instance describing the JavaScript runtime executing the current process.
|
|
140
|
+
*/
|
|
141
|
+
const runtime = new Runtime();
|
|
142
|
+
//#endregion
|
|
143
|
+
//#region ../../internals/utils/src/fs.ts
|
|
144
|
+
/**
|
|
145
|
+
* Reads the file at `path` as a UTF-8 string.
|
|
146
|
+
* Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.
|
|
147
|
+
*
|
|
148
|
+
* @example
|
|
149
|
+
* ```ts
|
|
150
|
+
* const source = await read('./src/Pet.ts')
|
|
151
|
+
* ```
|
|
152
|
+
*/
|
|
153
|
+
async function read(path) {
|
|
154
|
+
if (runtime.isBun) return Bun.file(path).text();
|
|
155
|
+
return readFile(path, { encoding: "utf8" });
|
|
156
|
+
}
|
|
157
|
+
//#endregion
|
|
45
158
|
//#region ../../internals/utils/src/promise.ts
|
|
46
159
|
/**
|
|
47
160
|
* Runs `run` over every item with at most `limit` in flight. Workers share one iterator, so each
|
|
@@ -78,360 +191,800 @@ function getElapsedMs(hrStart) {
|
|
|
78
191
|
return Math.round(ms * 100) / 100;
|
|
79
192
|
}
|
|
80
193
|
//#endregion
|
|
81
|
-
//#region
|
|
194
|
+
//#region package.json
|
|
195
|
+
var version = "5.6.2";
|
|
196
|
+
//#endregion
|
|
197
|
+
//#region src/resolveConfig.ts
|
|
82
198
|
/**
|
|
83
|
-
*
|
|
199
|
+
* Imports a package, falling back to how the user's project would resolve it.
|
|
84
200
|
*
|
|
85
|
-
*
|
|
86
|
-
*
|
|
87
|
-
* The
|
|
88
|
-
* identity that changes on every restart.
|
|
201
|
+
* `import()` resolves from this file, so a linked or globally installed Studio (`pnpm link`,
|
|
202
|
+
* `npm i -g`) only sees its own `node_modules` and misses the plugins installed next to the user's
|
|
203
|
+
* config. The retry resolves from `process.cwd()` instead.
|
|
89
204
|
*/
|
|
90
|
-
|
|
91
|
-
|
|
205
|
+
async function importFromProject(packageName) {
|
|
206
|
+
try {
|
|
207
|
+
return await import(packageName);
|
|
208
|
+
} catch {
|
|
209
|
+
const resolved = createRequire(pathToFileURL(`${process.cwd()}/`)).resolve(packageName);
|
|
210
|
+
const esm = resolved.replace(/\.cjs$/, ".js");
|
|
211
|
+
return await import(pathToFileURL(esm !== resolved && existsSync(esm) ? esm : resolved).href);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
92
214
|
/**
|
|
93
|
-
*
|
|
215
|
+
* Strips the `@kubb/` scope from a plugin package name, matching the `name` convention Kubb
|
|
216
|
+
* plugin factories use internally.
|
|
217
|
+
*
|
|
218
|
+
* @example
|
|
219
|
+
* ```ts
|
|
220
|
+
* toPluginName('@kubb/plugin-ts') // 'plugin-ts'
|
|
221
|
+
* ```
|
|
94
222
|
*/
|
|
95
|
-
function
|
|
96
|
-
|
|
97
|
-
hasInstalledStorage = true;
|
|
223
|
+
function toPluginName(packageName) {
|
|
224
|
+
return packageName.split("/").pop() ?? packageName;
|
|
98
225
|
}
|
|
99
226
|
/**
|
|
100
|
-
*
|
|
101
|
-
*
|
|
227
|
+
* Adds the `@kubb/` scope a plugin's package carries but its `name` does not, the inverse of
|
|
228
|
+
* {@link toPluginName}. A name outside the `plugin-` convention is left alone, so a third-party
|
|
229
|
+
* plugin is not reported as one of Kubb's.
|
|
230
|
+
*
|
|
231
|
+
* @example
|
|
232
|
+
* ```ts
|
|
233
|
+
* toPackageName('plugin-ts') // '@kubb/plugin-ts'
|
|
234
|
+
* toPackageName('@acme/my-plugin') // '@acme/my-plugin'
|
|
235
|
+
* ```
|
|
102
236
|
*/
|
|
103
|
-
function
|
|
104
|
-
return
|
|
237
|
+
function toPackageName(name) {
|
|
238
|
+
return name.startsWith("plugin-") ? `@kubb/${name}` : name;
|
|
105
239
|
}
|
|
106
|
-
let fallbackSecretPromise = null;
|
|
107
240
|
/**
|
|
108
|
-
*
|
|
109
|
-
*
|
|
110
|
-
*
|
|
111
|
-
*
|
|
241
|
+
* Derives the conventional named export for a `@kubb/*` plugin package from its package name.
|
|
242
|
+
*
|
|
243
|
+
* @example
|
|
244
|
+
* ```ts
|
|
245
|
+
* toExportName('@kubb/plugin-react-query') // 'pluginReactQuery'
|
|
246
|
+
* toExportName('@kubb/plugin-ts') // 'pluginTs'
|
|
247
|
+
* ```
|
|
112
248
|
*/
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
const stored = await storage.getItem("machine-secret").catch(() => null);
|
|
116
|
-
if (typeof stored === "string" && stored) return stored;
|
|
117
|
-
const secret = randomBytes(32).toString("hex");
|
|
118
|
-
await storage.setItem("machine-secret", secret).catch(() => {
|
|
119
|
-
console.warn(styleText("yellow", "Could not persist the generated machine secret"), "set KUBB_AGENT_SECRET to keep a stable machine identity across restarts");
|
|
120
|
-
});
|
|
121
|
-
return secret;
|
|
249
|
+
function toExportName(packageName) {
|
|
250
|
+
return camelCase(toPluginName(packageName));
|
|
122
251
|
}
|
|
123
252
|
/**
|
|
124
|
-
*
|
|
125
|
-
*
|
|
253
|
+
* A `@kubb/plugin-*` package specifier. Nothing else may reach `import()`: only Kubb's own
|
|
254
|
+
* plugins are supported, so a payload naming anything else, a third-party package or a path, is
|
|
255
|
+
* refused before it can execute.
|
|
126
256
|
*/
|
|
127
|
-
|
|
128
|
-
return hash("sha256", secret);
|
|
129
|
-
}
|
|
257
|
+
const KUBB_PLUGIN_SPECIFIER = /^@kubb\/plugin-[\w.-]+$/;
|
|
130
258
|
/**
|
|
131
|
-
*
|
|
132
|
-
*
|
|
133
|
-
* The token is hashed with SHA-256.
|
|
259
|
+
* Whether `name` is a `@kubb/plugin-*` specifier. Exported so `configFile.ts` can refuse the same
|
|
260
|
+
* shape before printing a Studio-supplied plugin name into the config file's source text.
|
|
134
261
|
*/
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
fallbackSecretPromise ??= loadOrCreateFallbackSecret();
|
|
138
|
-
return machineTokenFrom(await fallbackSecretPromise);
|
|
262
|
+
function isKubbPluginSpecifier(name) {
|
|
263
|
+
return KUBB_PLUGIN_SPECIFIER.test(name);
|
|
139
264
|
}
|
|
140
|
-
//#endregion
|
|
141
|
-
//#region src/operations/api.ts
|
|
142
265
|
/**
|
|
143
|
-
*
|
|
144
|
-
*
|
|
145
|
-
*
|
|
266
|
+
* Dynamically imports a `@kubb/plugin-*` package and returns its factory function.
|
|
267
|
+
*
|
|
268
|
+
* Packages must be pre-installed in the Docker image at build time via the `KUBB_PACKAGES`
|
|
269
|
+
* build ARG, no runtime installation is possible in the distroless container.
|
|
270
|
+
*
|
|
271
|
+
* Resolution order: the camelCase named export the package name implies (e.g. `pluginTs`), then
|
|
272
|
+
* the default export.
|
|
273
|
+
*
|
|
274
|
+
* @throws if the package cannot be imported or exports no callable factory.
|
|
146
275
|
*/
|
|
147
|
-
function
|
|
148
|
-
if (!
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
276
|
+
async function loadPluginFactory(packageName) {
|
|
277
|
+
if (!isKubbPluginSpecifier(packageName)) throw new Error(`Plugin "${packageName}" is not a @kubb/plugin-* package. Kubb Studio only supports Kubb's own plugins.`);
|
|
278
|
+
let mod;
|
|
279
|
+
try {
|
|
280
|
+
mod = await importFromProject(packageName);
|
|
281
|
+
} catch (cause) {
|
|
282
|
+
throw new Error(`Plugin "${packageName}" could not be loaded. Make sure it is installed: \`npm install ${packageName}\``, { cause });
|
|
283
|
+
}
|
|
284
|
+
const exportName = toExportName(packageName);
|
|
285
|
+
if (typeof mod[exportName] === "function") return mod[exportName];
|
|
286
|
+
if (typeof mod["default"] === "function") return mod["default"];
|
|
287
|
+
throw new Error(`Plugin "${packageName}" does not export a callable factory. Tried the named export "${exportName}" and "default".`);
|
|
155
288
|
}
|
|
156
289
|
/**
|
|
157
|
-
*
|
|
158
|
-
*
|
|
159
|
-
*
|
|
290
|
+
* Resolves each plugin entry by dynamically importing the `@kubb/plugin-*` package and
|
|
291
|
+
* calling its factory with the provided options.
|
|
292
|
+
*
|
|
293
|
+
* Packages must be pre-installed in the Docker image at build time, use the `KUBB_PACKAGES`
|
|
294
|
+
* build ARG to control which ones are available at runtime.
|
|
295
|
+
*
|
|
296
|
+
* @example
|
|
297
|
+
* ```ts
|
|
298
|
+
* { name: '@kubb/plugin-react-query', options: { output: { path: './hooks' } } }
|
|
299
|
+
* { name: '@kubb/plugin-ts', options: { output: { path: './types' } } }
|
|
300
|
+
* ```
|
|
160
301
|
*/
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
302
|
+
async function resolvePlugins(plugins) {
|
|
303
|
+
return Promise.all(plugins.map(async ({ name, options }) => {
|
|
304
|
+
return (await loadPluginFactory(name))(options ?? {});
|
|
305
|
+
}));
|
|
306
|
+
}
|
|
307
|
+
/** The installed version of each plugin's package, plus the names that could not be resolved. */
|
|
308
|
+
async function resolvePeerDependencies(names) {
|
|
309
|
+
const require = createRequire(import.meta.url);
|
|
310
|
+
const uniqueNames = [...new Set(names.map(toPackageName))];
|
|
311
|
+
const peerDependencies = {};
|
|
312
|
+
const missingDependencies = [];
|
|
313
|
+
const versions = await Promise.all(uniqueNames.map(async (name) => {
|
|
314
|
+
try {
|
|
315
|
+
const path = require.resolve(`${name}/package.json`);
|
|
316
|
+
return JSON.parse(await readFile(path, "utf8")).version;
|
|
317
|
+
} catch {
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
}));
|
|
321
|
+
for (const [index, name] of uniqueNames.entries()) {
|
|
322
|
+
const version = versions[index];
|
|
323
|
+
if (version) {
|
|
324
|
+
peerDependencies[name] = version;
|
|
325
|
+
continue;
|
|
326
|
+
}
|
|
327
|
+
missingDependencies.push(name);
|
|
165
328
|
}
|
|
166
|
-
|
|
329
|
+
return {
|
|
330
|
+
peerDependencies,
|
|
331
|
+
missingDependencies
|
|
332
|
+
};
|
|
333
|
+
}
|
|
167
334
|
/**
|
|
168
|
-
*
|
|
169
|
-
* agent is upgraded, so hosts stop instead of reconnecting.
|
|
335
|
+
* Whether `value` is an object literal or a null-prototype object, not an array or class instance.
|
|
170
336
|
*/
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
337
|
+
function isPlainObject(value) {
|
|
338
|
+
if (typeof value !== "object" || value === null) return false;
|
|
339
|
+
const prototype = Object.getPrototypeOf(value);
|
|
340
|
+
return prototype === null || prototype === Object.prototype;
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Whether `value` survives a JSON round trip, so it can be printed into a config file as a literal.
|
|
344
|
+
* A function, `undefined`, a non-finite number or a class instance comes back from Studio as a
|
|
345
|
+
* lossy copy, so an edit carrying one is refused rather than written into the user's source.
|
|
346
|
+
*/
|
|
347
|
+
function isOptionValue(value) {
|
|
348
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return true;
|
|
349
|
+
if (typeof value === "number") return Number.isFinite(value);
|
|
350
|
+
if (Array.isArray(value)) return value.every(isOptionValue);
|
|
351
|
+
if (isPlainObject(value)) return Object.values(value).every(isOptionValue);
|
|
352
|
+
return false;
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
355
|
+
* Deep-merges Studio's options over the disk options, with Studio taking priority, except where the
|
|
356
|
+
* disk value cannot survive JSON. Studio only ever saw a lossy copy of such a value, so the disk
|
|
357
|
+
* value is kept rather than replaced by what Studio echoes back. Plain objects merge key by key, so
|
|
358
|
+
* Studio can still change a literal that sits next to a function (e.g. `group.type` beside `group.name`).
|
|
359
|
+
*
|
|
360
|
+
* @example
|
|
361
|
+
* ```ts
|
|
362
|
+
* mergeOptions({ macros: [camelCaseMacro], syntaxType: 'type' }, { macros: [{ name: 'camelCase' }], syntaxType: 'interface' })
|
|
363
|
+
* // { macros: [camelCaseMacro], syntaxType: 'interface' }
|
|
364
|
+
* ```
|
|
365
|
+
*/
|
|
366
|
+
function mergeOptions(disk, studio) {
|
|
367
|
+
const merged = { ...disk };
|
|
368
|
+
for (const [key, value] of Object.entries(studio)) {
|
|
369
|
+
const current = disk[key];
|
|
370
|
+
if (isPlainObject(current) && isPlainObject(value)) {
|
|
371
|
+
merged[key] = mergeOptions(current, value);
|
|
372
|
+
continue;
|
|
373
|
+
}
|
|
374
|
+
if (current !== void 0 && !isOptionValue(current)) continue;
|
|
375
|
+
merged[key] = value;
|
|
175
376
|
}
|
|
176
|
-
|
|
377
|
+
return merged;
|
|
378
|
+
}
|
|
177
379
|
/**
|
|
178
|
-
*
|
|
179
|
-
*
|
|
380
|
+
* Merges studio plugin options with disk config plugins.
|
|
381
|
+
* Studio takes priority: options from studio win over disk (except values only the disk config
|
|
382
|
+
* can express, see {@link mergeOptions}), and a plugin Studio explicitly
|
|
383
|
+
* disabled is dropped even when the disk config still lists it. Disk plugins without a studio
|
|
384
|
+
* counterpart are kept as-is. Studio plugins not present on disk are appended.
|
|
385
|
+
*
|
|
386
|
+
* For plugins present in both configs, the plugin is re-instantiated with merged options
|
|
387
|
+
* so that all internal closures correctly reference the merged values.
|
|
180
388
|
*/
|
|
181
|
-
function
|
|
182
|
-
|
|
389
|
+
async function mergePlugins(diskPlugins, studioPlugins) {
|
|
390
|
+
const disabledNames = new Set((studioPlugins ?? []).filter((entry) => entry.disabled).map((entry) => toPluginName(entry.name)));
|
|
391
|
+
const activeDiskPlugins = disabledNames.size ? diskPlugins?.filter((plugin) => !disabledNames.has(plugin.name)) : diskPlugins;
|
|
392
|
+
const activeStudioPlugins = studioPlugins?.filter((entry) => !entry.disabled);
|
|
393
|
+
if (!activeDiskPlugins && !activeStudioPlugins?.length) return void 0;
|
|
394
|
+
if (!activeStudioPlugins?.length) return activeDiskPlugins;
|
|
395
|
+
if (!activeDiskPlugins) return resolvePlugins(activeStudioPlugins);
|
|
396
|
+
const studioEntryByName = new Map(activeStudioPlugins.map((entry) => [toPluginName(entry.name), entry]));
|
|
397
|
+
const diskNames = new Set(activeDiskPlugins.map((plugin) => plugin.name));
|
|
398
|
+
const merged = await Promise.all(activeDiskPlugins.map(async (diskPlugin) => {
|
|
399
|
+
const studioEntry = studioEntryByName.get(diskPlugin.name);
|
|
400
|
+
if (!studioEntry) return diskPlugin;
|
|
401
|
+
const options = mergeOptions(diskPlugin.options ?? {}, studioEntry.options ?? {});
|
|
402
|
+
const [resolved] = await resolvePlugins([{
|
|
403
|
+
name: studioEntry.name,
|
|
404
|
+
options
|
|
405
|
+
}]);
|
|
406
|
+
return resolved ?? diskPlugin;
|
|
407
|
+
}));
|
|
408
|
+
const studioOnly = activeStudioPlugins.filter((entry) => !diskNames.has(toPluginName(entry.name)));
|
|
409
|
+
return [...merged, ...await resolvePlugins(studioOnly)];
|
|
183
410
|
}
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
411
|
+
/**
|
|
412
|
+
* Merges Studio-provided adapter option overrides into the disk config's adapter.
|
|
413
|
+
*
|
|
414
|
+
* Adapter instances carry live functions (`parse`, `getImports`, ...) that can't survive
|
|
415
|
+
* JSON serialization over the WebSocket, so `studioOptions` is treated as an options patch
|
|
416
|
+
* rather than a replacement adapter. Re-invokes the same `@kubb/adapter-<name>` factory the
|
|
417
|
+
* disk config used, with the merged options, so the resulting instance has fresh closures
|
|
418
|
+
* over the merged values instead of a plain object missing `parse`.
|
|
419
|
+
*/
|
|
420
|
+
async function mergeAdapter(diskAdapter, studioOptions) {
|
|
421
|
+
if (!studioOptions || !diskAdapter) return diskAdapter;
|
|
422
|
+
const packageName = `@kubb/adapter-${diskAdapter.name}`;
|
|
423
|
+
const factory = (await importFromProject(packageName))[toExportName(packageName)];
|
|
424
|
+
if (typeof factory !== "function") return diskAdapter;
|
|
425
|
+
return factory(mergeOptions(diskAdapter.options ?? {}, studioOptions));
|
|
187
426
|
}
|
|
427
|
+
//#endregion
|
|
428
|
+
//#region src/configFile.ts
|
|
188
429
|
/**
|
|
189
|
-
*
|
|
190
|
-
*
|
|
191
|
-
|
|
430
|
+
* A valid JavaScript identifier, so an import name can only ever print as `import { name } from`,
|
|
431
|
+
* never as source that breaks out of the import statement.
|
|
432
|
+
*/
|
|
433
|
+
const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
|
|
434
|
+
/**
|
|
435
|
+
* `key: value` as an object literal property, in the file's quote and key style.
|
|
192
436
|
*
|
|
193
|
-
*
|
|
194
|
-
*
|
|
195
|
-
* {@link IncompatibleAgentError}, since retrying either cannot help.
|
|
437
|
+
* Uses magicast's literal builder for the key/value nodes, then wraps them as a Babel
|
|
438
|
+
* `ObjectProperty`, the type the rest of this file reads.
|
|
196
439
|
*/
|
|
197
|
-
|
|
198
|
-
const
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
440
|
+
function literalProperty({ key, value }) {
|
|
441
|
+
const built = builders.literal({ [key]: value }).properties[0];
|
|
442
|
+
return {
|
|
443
|
+
type: "ObjectProperty",
|
|
444
|
+
key: built.key,
|
|
445
|
+
value: built.value,
|
|
446
|
+
computed: false,
|
|
447
|
+
shorthand: false
|
|
202
448
|
};
|
|
203
|
-
try {
|
|
204
|
-
return await ofetch(`${studioUrl}/api/agent/connect`, {
|
|
205
|
-
method: "POST",
|
|
206
|
-
headers: { Authorization: `Bearer ${token}` },
|
|
207
|
-
body,
|
|
208
|
-
retry: 0,
|
|
209
|
-
timeout: 1e4,
|
|
210
|
-
signal
|
|
211
|
-
});
|
|
212
|
-
} catch (error) {
|
|
213
|
-
if (rejectedWith(error, 401)) throw new InvalidAgentTokenError(studioUrl, { cause: error });
|
|
214
|
-
if (rejectedWith(error, 426)) throw new IncompatibleAgentError(studioUrl, error instanceof FetchError ? responseMessage(error.data) : void 0, { cause: error });
|
|
215
|
-
throw registrationError(error);
|
|
216
|
-
}
|
|
217
449
|
}
|
|
218
450
|
/**
|
|
219
|
-
*
|
|
451
|
+
* Marks the comment block a `disable-plugin` leaves behind, so `enable-plugin` can find its way
|
|
452
|
+
* back to the exact lines it commented out. Carries the block's line count, so `enable-plugin`
|
|
453
|
+
* restores exactly those lines instead of scanning forward through whatever comments follow.
|
|
220
454
|
*/
|
|
221
|
-
const
|
|
455
|
+
const DISABLED_MARKER = "kubb:disabled";
|
|
222
456
|
/**
|
|
223
|
-
*
|
|
457
|
+
* The plugin and comment-block length a marker line names, when `line` is one.
|
|
224
458
|
*/
|
|
225
|
-
|
|
459
|
+
function parseMarker(line) {
|
|
460
|
+
const trimmed = line.trim();
|
|
461
|
+
if (!trimmed.startsWith(`// ${DISABLED_MARKER} `)) return;
|
|
462
|
+
const match = trimmed.slice(`// ${DISABLED_MARKER} `.length).match(/^(.+)\s+(\d+)$/);
|
|
463
|
+
return match ? {
|
|
464
|
+
plugin: match[1],
|
|
465
|
+
lineCount: Number(match[2])
|
|
466
|
+
} : void 0;
|
|
467
|
+
}
|
|
226
468
|
/**
|
|
227
|
-
*
|
|
228
|
-
*
|
|
229
|
-
* (503, an agent process that is mid-reconnect). Anything else (404 agent not found, 401/403 auth)
|
|
230
|
-
* is thrown straight away, since retrying cannot change the outcome.
|
|
469
|
+
* Steps through a config's wrappers to the object literal underneath: a `satisfies`/`as`
|
|
470
|
+
* assertion, a `() => ...` factory, or a factory whose block body returns the config.
|
|
231
471
|
*/
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
472
|
+
function unwrap(node) {
|
|
473
|
+
if (!node) return;
|
|
474
|
+
if (node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression") return unwrap(node.expression);
|
|
475
|
+
if (node.type !== "ArrowFunctionExpression" && node.type !== "FunctionExpression") return node;
|
|
476
|
+
if (node.body.type !== "BlockStatement") return unwrap(node.body);
|
|
477
|
+
return unwrap(node.body.body.find((statement) => statement.type === "ReturnStatement")?.argument);
|
|
478
|
+
}
|
|
237
479
|
/**
|
|
238
|
-
*
|
|
480
|
+
* Every config object in `export default defineConfig(...)`, or why the file is unmanaged.
|
|
481
|
+
*
|
|
482
|
+
* An array export gets one entry per element, matching {@link ConfigRef}'s numeric index.
|
|
483
|
+
*
|
|
484
|
+
* Walks the parsed AST rather than magicast's proxies, which throw on node types they cannot
|
|
485
|
+
* cast, most of what an unmanaged config file is made of.
|
|
239
486
|
*/
|
|
240
|
-
function
|
|
241
|
-
const
|
|
242
|
-
|
|
487
|
+
function findConfigs(mod) {
|
|
488
|
+
const exported = unwrap((mod.$ast.type === "Program" ? mod.$ast.body : []).find((node) => node.type === "ExportDefaultDeclaration")?.declaration);
|
|
489
|
+
if (!exported) return { reason: "no default export found" };
|
|
490
|
+
if (exported.type !== "CallExpression" || exported.callee.type !== "Identifier" || exported.callee.name !== "defineConfig") return { reason: "default export is not a defineConfig(...) call" };
|
|
491
|
+
const argument = unwrap(exported.arguments[0]);
|
|
492
|
+
if (!argument) return { reason: "defineConfig(...) was called without a config" };
|
|
493
|
+
if (argument.type === "ArrayExpression") {
|
|
494
|
+
const configs = [];
|
|
495
|
+
for (const element of argument.elements) {
|
|
496
|
+
const entry = unwrap(element);
|
|
497
|
+
if (entry?.type !== "ObjectExpression") return { reason: "config is not an object literal" };
|
|
498
|
+
configs.push(entry);
|
|
499
|
+
}
|
|
500
|
+
return { configs };
|
|
501
|
+
}
|
|
502
|
+
if (argument.type !== "ObjectExpression") return { reason: "config is not an object literal" };
|
|
503
|
+
return { configs: [argument] };
|
|
243
504
|
}
|
|
244
505
|
/**
|
|
245
|
-
*
|
|
246
|
-
* lockstep.
|
|
506
|
+
* The config entry an edit names, defaulting to the first when it names none.
|
|
247
507
|
*/
|
|
248
|
-
function
|
|
249
|
-
|
|
508
|
+
function selectConfig(configs, ref) {
|
|
509
|
+
if (ref === void 0) return configs[0];
|
|
510
|
+
if (typeof ref === "number") return configs[ref];
|
|
511
|
+
return configs.find((config) => configName(config) === ref);
|
|
512
|
+
}
|
|
513
|
+
function configName(config) {
|
|
514
|
+
const name = property(config, "name");
|
|
515
|
+
return name?.type === "StringLiteral" ? name.value : void 0;
|
|
250
516
|
}
|
|
251
517
|
/**
|
|
252
|
-
*
|
|
518
|
+
* The name of an object literal property, for the two key shapes a config uses: `key: value` and
|
|
519
|
+
* `'key': value`. `undefined` for a computed key, which the patcher never touches.
|
|
520
|
+
*/
|
|
521
|
+
function propertyKey(entry) {
|
|
522
|
+
if (entry.key.type === "Identifier") return entry.key.name;
|
|
523
|
+
if (entry.key.type === "StringLiteral") return entry.key.value;
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* The index of an object literal's own property named `key`, `-1` when it has none.
|
|
527
|
+
*/
|
|
528
|
+
function entryIndex({ node, key }) {
|
|
529
|
+
return node.properties.findIndex((entry) => entry.type === "ObjectProperty" && propertyKey(entry) === key);
|
|
530
|
+
}
|
|
531
|
+
/**
|
|
532
|
+
* The value node of an object literal's own property.
|
|
533
|
+
*/
|
|
534
|
+
function property(node, key) {
|
|
535
|
+
const index = entryIndex({
|
|
536
|
+
node,
|
|
537
|
+
key
|
|
538
|
+
});
|
|
539
|
+
return index === -1 ? void 0 : node.properties[index].value;
|
|
540
|
+
}
|
|
541
|
+
/**
|
|
542
|
+
* Writes `key: value` on an object literal, replacing the value when the property is already there.
|
|
253
543
|
*
|
|
254
|
-
*
|
|
255
|
-
*
|
|
544
|
+
* An existing property has its value swapped in place rather than being replaced whole, so recast
|
|
545
|
+
* reprints only that value and leaves the object's own layout alone.
|
|
546
|
+
*/
|
|
547
|
+
function setProperty({ node, key, value }) {
|
|
548
|
+
const entry = literalProperty({
|
|
549
|
+
key,
|
|
550
|
+
value
|
|
551
|
+
});
|
|
552
|
+
const index = entryIndex({
|
|
553
|
+
node,
|
|
554
|
+
key
|
|
555
|
+
});
|
|
556
|
+
if (index === -1) {
|
|
557
|
+
node.properties.push(entry);
|
|
558
|
+
return;
|
|
559
|
+
}
|
|
560
|
+
node.properties[index].value = entry.value;
|
|
561
|
+
}
|
|
562
|
+
/**
|
|
563
|
+
* Drops `key` from an object literal.
|
|
564
|
+
*/
|
|
565
|
+
function removeProperty({ node, key }) {
|
|
566
|
+
const index = entryIndex({
|
|
567
|
+
node,
|
|
568
|
+
key
|
|
569
|
+
});
|
|
570
|
+
if (index !== -1) node.properties.splice(index, 1);
|
|
571
|
+
}
|
|
572
|
+
/**
|
|
573
|
+
* Reads a literal node's value: a primitive, or an object/array built only from primitives.
|
|
574
|
+
* `undefined` for anything else, so a caller can use this both to read a value and to check
|
|
575
|
+
* whether a node is a literal at all.
|
|
576
|
+
*/
|
|
577
|
+
function readLiteral(node) {
|
|
578
|
+
if (!node) return;
|
|
579
|
+
if (node.type === "StringLiteral" || node.type === "NumericLiteral" || node.type === "BooleanLiteral") return node.value;
|
|
580
|
+
if (node.type === "NullLiteral") return null;
|
|
581
|
+
if (node.type === "TemplateLiteral") return node.expressions.length === 0 ? node.quasis[0]?.value.cooked ?? "" : void 0;
|
|
582
|
+
if (node.type === "UnaryExpression") {
|
|
583
|
+
const value = readLiteral(node.argument);
|
|
584
|
+
if (typeof value !== "number") return;
|
|
585
|
+
if (node.operator === "-") return -value;
|
|
586
|
+
if (node.operator === "+") return value;
|
|
587
|
+
return;
|
|
588
|
+
}
|
|
589
|
+
if (node.type === "ArrayExpression") {
|
|
590
|
+
const values = node.elements.map((element) => element ? readLiteral(element) : void 0);
|
|
591
|
+
return values.every((value) => value !== void 0) ? values : void 0;
|
|
592
|
+
}
|
|
593
|
+
if (node.type === "ObjectExpression") {
|
|
594
|
+
const entries = {};
|
|
595
|
+
for (const entry of node.properties) {
|
|
596
|
+
if (entry.type !== "ObjectProperty") return;
|
|
597
|
+
const key = propertyKey(entry);
|
|
598
|
+
const value = readLiteral(entry.value);
|
|
599
|
+
if (key === void 0 || value === void 0) return;
|
|
600
|
+
entries[key] = value;
|
|
601
|
+
}
|
|
602
|
+
return entries;
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
/**
|
|
606
|
+
* Maps a factory identifier in the file back to the module it was imported from.
|
|
607
|
+
*/
|
|
608
|
+
function importedFrom(mod) {
|
|
609
|
+
return new Map(mod.imports.$items.map((item) => [item.local, item.from]));
|
|
610
|
+
}
|
|
611
|
+
/**
|
|
612
|
+
* Every `pluginX(...)` element of a config's plugins array that resolves to an import.
|
|
613
|
+
*/
|
|
614
|
+
function pluginCalls(mod, config) {
|
|
615
|
+
const plugins = property(config, "plugins");
|
|
616
|
+
if (plugins?.type !== "ArrayExpression") return [];
|
|
617
|
+
const imports = importedFrom(mod);
|
|
618
|
+
return plugins.elements.flatMap((element) => {
|
|
619
|
+
if (element?.type !== "CallExpression" || element.callee.type !== "Identifier") return [];
|
|
620
|
+
const packageName = imports.get(element.callee.name);
|
|
621
|
+
return packageName ? [{
|
|
622
|
+
importName: element.callee.name,
|
|
623
|
+
packageName,
|
|
624
|
+
call: element
|
|
625
|
+
}] : [];
|
|
626
|
+
});
|
|
627
|
+
}
|
|
628
|
+
/**
|
|
629
|
+
* Plugins a previous `disable-plugin` commented out of this config, keyed by package name.
|
|
256
630
|
*
|
|
257
|
-
*
|
|
258
|
-
|
|
259
|
-
|
|
631
|
+
* Read from the marker lines rather than the AST, since a commented-out call is no longer a node.
|
|
632
|
+
*/
|
|
633
|
+
function disabledMarkers(source) {
|
|
634
|
+
return source.split("\n").flatMap((line, index) => {
|
|
635
|
+
const marker = parseMarker(line);
|
|
636
|
+
return marker ? [{
|
|
637
|
+
packageName: marker.plugin,
|
|
638
|
+
line: index + 1
|
|
639
|
+
}] : [];
|
|
640
|
+
});
|
|
641
|
+
}
|
|
642
|
+
/**
|
|
643
|
+
* Reads which plugins the file declares and which of their options Studio may write.
|
|
260
644
|
*
|
|
261
|
-
* @example
|
|
645
|
+
* @example
|
|
262
646
|
* ```ts
|
|
263
|
-
* const
|
|
264
|
-
*
|
|
265
|
-
*
|
|
266
|
-
*
|
|
267
|
-
* agentId: agent.id,
|
|
268
|
-
* name: '@kubb/demo',
|
|
269
|
-
* version: '1.0.0',
|
|
270
|
-
* })
|
|
271
|
-
* const finished = await waitForJob({ studioUrl, token, id: job.id })
|
|
647
|
+
* const view = readConfig(await readFile('kubb.config.ts', 'utf8'))
|
|
648
|
+
* if (view.managed) {
|
|
649
|
+
* view.configs.forEach((config) => console.log(config.name, config.plugins.length))
|
|
650
|
+
* }
|
|
272
651
|
* ```
|
|
273
652
|
*/
|
|
274
|
-
|
|
275
|
-
const
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
653
|
+
function readConfig(source) {
|
|
654
|
+
const parsed = parseConfigs(source);
|
|
655
|
+
if ("reason" in parsed) return {
|
|
656
|
+
managed: false,
|
|
657
|
+
reason: parsed.reason
|
|
658
|
+
};
|
|
659
|
+
const { mod, configs } = parsed;
|
|
660
|
+
const importNames = new Map([...importedFrom(mod)].map(([local, from]) => [from, local]));
|
|
661
|
+
const disabled = disabledMarkers(source);
|
|
662
|
+
return {
|
|
663
|
+
managed: true,
|
|
664
|
+
configs: configs.map((config) => {
|
|
665
|
+
const plugins = pluginCalls(mod, config).map(({ importName, packageName, call }) => {
|
|
666
|
+
const entries = {};
|
|
667
|
+
const options = call.arguments[0];
|
|
668
|
+
if (options?.type === "ObjectExpression") for (const entry of options.properties) {
|
|
669
|
+
if (entry.type !== "ObjectProperty") continue;
|
|
670
|
+
const key = propertyKey(entry);
|
|
671
|
+
if (key === void 0) continue;
|
|
672
|
+
const value = readLiteral(entry.value);
|
|
673
|
+
entries[key] = value === void 0 ? { literal: false } : {
|
|
674
|
+
literal: true,
|
|
675
|
+
value
|
|
676
|
+
};
|
|
677
|
+
}
|
|
678
|
+
return {
|
|
679
|
+
importName,
|
|
680
|
+
packageName,
|
|
681
|
+
options: entries
|
|
682
|
+
};
|
|
296
683
|
});
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
684
|
+
const start = config.loc?.start.line ?? 0;
|
|
685
|
+
const end = config.loc?.end.line ?? Number.POSITIVE_INFINITY;
|
|
686
|
+
for (const { packageName } of disabled.filter((entry) => entry.line >= start && entry.line <= end)) plugins.push({
|
|
687
|
+
importName: importNames.get(packageName) ?? toExportName(packageName),
|
|
688
|
+
packageName,
|
|
689
|
+
options: {},
|
|
690
|
+
disabled: true
|
|
691
|
+
});
|
|
692
|
+
return {
|
|
693
|
+
name: configName(config),
|
|
694
|
+
plugins
|
|
695
|
+
};
|
|
696
|
+
})
|
|
697
|
+
};
|
|
309
698
|
}
|
|
310
699
|
/**
|
|
311
|
-
*
|
|
700
|
+
* The options object of a plugin call, when it was called with one.
|
|
312
701
|
*/
|
|
313
|
-
|
|
702
|
+
function getOptions(call) {
|
|
703
|
+
const options = call.arguments[0];
|
|
704
|
+
return options?.type === "ObjectExpression" ? options : void 0;
|
|
705
|
+
}
|
|
314
706
|
/**
|
|
315
|
-
*
|
|
316
|
-
* every concurrent run on the same organization key draws on one budget.
|
|
707
|
+
* The options object of a plugin call, creating an empty one when the plugin was called bare.
|
|
317
708
|
*/
|
|
318
|
-
|
|
709
|
+
function ensureOptions(call) {
|
|
710
|
+
if (call.arguments.length === 0) call.arguments.push({
|
|
711
|
+
type: "ObjectExpression",
|
|
712
|
+
properties: []
|
|
713
|
+
});
|
|
714
|
+
return getOptions(call);
|
|
715
|
+
}
|
|
319
716
|
/**
|
|
320
|
-
*
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
if (
|
|
336
|
-
|
|
337
|
-
try {
|
|
338
|
-
const { job } = await ofetch(`${studioUrl}/api/jobs/${id}`, {
|
|
339
|
-
headers: { "x-api-key": token },
|
|
340
|
-
retry: false,
|
|
341
|
-
timeout: Math.max(deadline - Date.now(), 1),
|
|
342
|
-
signal
|
|
343
|
-
});
|
|
344
|
-
if (job.status === "success" || job.status === "failed" || job.status === "canceled") return job;
|
|
345
|
-
} catch (error) {
|
|
346
|
-
signal?.throwIfAborted();
|
|
347
|
-
const response = error.response;
|
|
348
|
-
if (response?.status !== 429) throw error;
|
|
349
|
-
const retryAfter = response._data?.data?.tryAgainIn;
|
|
350
|
-
interval = Math.max(interval, typeof retryAfter === "number" && Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter : MAX_POLL_INTERVAL_MS);
|
|
351
|
-
}
|
|
717
|
+
* Walks `path` down to the object holding its last key, descending only through object literals.
|
|
718
|
+
*/
|
|
719
|
+
function optionParent(options, path) {
|
|
720
|
+
let object = options;
|
|
721
|
+
for (const [index, key] of path.entries()) {
|
|
722
|
+
if (index === path.length - 1) return {
|
|
723
|
+
object,
|
|
724
|
+
key
|
|
725
|
+
};
|
|
726
|
+
if (property(object, key) === void 0) setProperty({
|
|
727
|
+
node: object,
|
|
728
|
+
key,
|
|
729
|
+
value: {}
|
|
730
|
+
});
|
|
731
|
+
const next = property(object, key);
|
|
732
|
+
if (next?.type !== "ObjectExpression") return { reason: `${key} is not an object, so ${path.join(".")} cannot be reached` };
|
|
733
|
+
object = next;
|
|
352
734
|
}
|
|
735
|
+
return { reason: "no option path given" };
|
|
353
736
|
}
|
|
354
737
|
/**
|
|
355
|
-
*
|
|
356
|
-
*
|
|
357
|
-
*
|
|
738
|
+
* Writes `value` at `path` inside a plugin call's options, creating the options object and any
|
|
739
|
+
* intermediate object along the path as needed. Refuses when the current value at `path` is
|
|
740
|
+
* something other than a literal, so an option customized in code is never overwritten.
|
|
358
741
|
*/
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
742
|
+
function applySet(call, path, value) {
|
|
743
|
+
if (!isOptionValue(value)) return "the value is not a literal that can be written to a config file";
|
|
744
|
+
const options = ensureOptions(call);
|
|
745
|
+
if (!options) return "the plugin was not called with an object literal";
|
|
746
|
+
const target = optionParent(options, path);
|
|
747
|
+
if ("reason" in target) return target.reason;
|
|
748
|
+
const current = property(target.object, target.key);
|
|
749
|
+
if (current !== void 0 && readLiteral(current) === void 0) return `${path.join(".")} is customized in code`;
|
|
750
|
+
setProperty({
|
|
751
|
+
node: target.object,
|
|
752
|
+
key: target.key,
|
|
753
|
+
value
|
|
754
|
+
});
|
|
755
|
+
}
|
|
756
|
+
/**
|
|
757
|
+
* Deletes the property at `path` inside a plugin call's options, falling the plugin back to its
|
|
758
|
+
* default for that option. Refuses when the value at `path` is not a literal, for the same reason
|
|
759
|
+
* `applySet` does.
|
|
760
|
+
*/
|
|
761
|
+
function applyRemove(call, path) {
|
|
762
|
+
const options = getOptions(call);
|
|
763
|
+
if (!options) return "the plugin has no options to remove";
|
|
764
|
+
const target = optionParent(options, path);
|
|
765
|
+
if ("reason" in target) return target.reason;
|
|
766
|
+
const current = property(target.object, target.key);
|
|
767
|
+
if (current === void 0) return `${path.join(".")} is not set`;
|
|
768
|
+
if (readLiteral(current) === void 0) return `${path.join(".")} is customized in code`;
|
|
769
|
+
removeProperty({
|
|
770
|
+
node: target.object,
|
|
771
|
+
key: target.key
|
|
772
|
+
});
|
|
773
|
+
}
|
|
774
|
+
/**
|
|
775
|
+
* Adds a `pluginX(...)` call to a config's plugins array. Replaying the same add is a no-op, while
|
|
776
|
+
* an import name collision with an unrelated package remains an error.
|
|
777
|
+
*/
|
|
778
|
+
function applyAddPlugin(mod, config, edit) {
|
|
779
|
+
if (!isKubbPluginSpecifier(edit.plugin)) return { reason: `"${edit.plugin}" is not a @kubb/plugin-* package` };
|
|
780
|
+
const importName = edit.importName ?? toExportName(edit.plugin);
|
|
781
|
+
if (!IDENTIFIER.test(importName)) return { reason: `"${importName}" is not a valid import name` };
|
|
782
|
+
if (pluginCalls(mod, config).some((plugin) => plugin.packageName === edit.plugin)) return { noop: true };
|
|
783
|
+
const taken = importedFrom(mod).get(importName);
|
|
784
|
+
if (taken && taken !== edit.plugin) return { reason: `${importName} is already imported from ${taken}` };
|
|
785
|
+
const options = edit.options ?? {};
|
|
786
|
+
if (!isOptionValue(options)) return { reason: "the options are not literals that can be written to a config file" };
|
|
787
|
+
const plugins = property(config, "plugins");
|
|
788
|
+
if (plugins?.type !== "ArrayExpression") return { reason: "plugins is not an array literal" };
|
|
789
|
+
const call = Object.keys(options).length ? builders.functionCall(importName, options) : builders.functionCall(importName);
|
|
790
|
+
plugins.elements.push(call.$ast);
|
|
791
|
+
return taken ? {} : { addImport: {
|
|
792
|
+
importName,
|
|
793
|
+
moduleSpecifier: edit.plugin
|
|
794
|
+
} };
|
|
795
|
+
}
|
|
796
|
+
/**
|
|
797
|
+
* Comments out a plugin call in place, keeping its options on disk so `enable-plugin` can restore
|
|
798
|
+
* them exactly. Operates on `source` text rather than the AST: a commented-out call is no longer a
|
|
799
|
+
* node magicast can address, and the surrounding array must not reflow when its element count
|
|
800
|
+
* never actually changes.
|
|
801
|
+
*/
|
|
802
|
+
function disablePlugin(source, mod, config, plugin) {
|
|
803
|
+
const target = pluginCalls(mod, config).find((entry) => entry.packageName === plugin);
|
|
804
|
+
if (!target) return { reason: `${plugin} is not in the plugins array` };
|
|
805
|
+
const loc = target.call.loc;
|
|
806
|
+
if (!loc?.start || !loc.end) return { reason: `${plugin} has no source location to comment out` };
|
|
807
|
+
const lines = source.split("\n");
|
|
808
|
+
const from = loc.start.line - 1;
|
|
809
|
+
const to = loc.end.line - 1;
|
|
810
|
+
const firstLine = lines[from] ?? "";
|
|
811
|
+
const lastLine = lines[to] ?? "";
|
|
812
|
+
if (firstLine.slice(0, loc.start.column).trim() !== "" || !/^,?\s*$/.test(lastLine.slice(loc.end.column))) return { reason: `${plugin} shares a line with other code, so it cannot be commented out safely` };
|
|
813
|
+
const indent = firstLine.match(/^\s*/)?.[0] ?? "";
|
|
814
|
+
const commented = lines.slice(from, to + 1).map((line) => line.trim() ? `${indent}// ${line.slice(indent.length)}` : indent ? `${indent}//` : "//");
|
|
815
|
+
lines.splice(from, to - from + 1, `${indent}// ${DISABLED_MARKER} ${plugin} ${commented.length}`, ...commented);
|
|
816
|
+
return { source: lines.join("\n") };
|
|
817
|
+
}
|
|
818
|
+
/**
|
|
819
|
+
* Uncomments the block a previous `disable-plugin` left behind for `plugin`.
|
|
820
|
+
*/
|
|
821
|
+
function enablePlugin(source, plugin) {
|
|
822
|
+
const lines = source.split("\n");
|
|
823
|
+
for (const [index, line] of lines.entries()) {
|
|
824
|
+
const marker = parseMarker(line);
|
|
825
|
+
if (marker?.plugin !== plugin) continue;
|
|
826
|
+
const end = index + 1 + marker.lineCount;
|
|
827
|
+
const restored = lines.slice(index + 1, end).map((commented) => commented.replace(/^(\s*)\/\/ ?/, "$1"));
|
|
828
|
+
lines.splice(index, end - index, ...restored);
|
|
829
|
+
return { source: lines.join("\n") };
|
|
377
830
|
}
|
|
831
|
+
return { reason: `${plugin} is not disabled` };
|
|
378
832
|
}
|
|
379
|
-
//#endregion
|
|
380
|
-
//#region src/operations/constants.ts
|
|
381
833
|
/**
|
|
382
|
-
*
|
|
383
|
-
* not whatever default the client would pick on its own.
|
|
834
|
+
* Parses `source` and finds the config entries it exports.
|
|
384
835
|
*/
|
|
385
|
-
|
|
836
|
+
function parseConfigs(source) {
|
|
837
|
+
let mod;
|
|
838
|
+
try {
|
|
839
|
+
mod = parseModule(source);
|
|
840
|
+
} catch {
|
|
841
|
+
return { reason: "the config file could not be parsed" };
|
|
842
|
+
}
|
|
843
|
+
const found = findConfigs(mod);
|
|
844
|
+
return "reason" in found ? found : {
|
|
845
|
+
mod,
|
|
846
|
+
configs: found.configs
|
|
847
|
+
};
|
|
848
|
+
}
|
|
386
849
|
/**
|
|
387
|
-
*
|
|
388
|
-
*
|
|
850
|
+
* Re-parses `source` and resolves the config entry an edit targets. Every edit re-parses rather
|
|
851
|
+
* than sharing one module across the batch, since the disable/enable edits rewrite `source` as
|
|
852
|
+
* text and would otherwise leave the others working from a stale tree.
|
|
389
853
|
*/
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
maxHeartbeatIntervalMs: 6e4,
|
|
400
|
-
/** How long a heartbeat ping may take before the session is treated as dead. */
|
|
401
|
-
heartbeatTimeoutMs: 1e4,
|
|
402
|
-
maxConcurrent: 1,
|
|
403
|
-
maxGenerations: 8,
|
|
404
|
-
maxGenerationsMb: 100,
|
|
405
|
-
maxSnapshotMb: 50
|
|
406
|
-
};
|
|
407
|
-
function positiveNumber(value) {
|
|
408
|
-
const parsed = Number(value);
|
|
409
|
-
return value && Number.isFinite(parsed) && parsed > 0 ? parsed : void 0;
|
|
854
|
+
function parseTarget(source, ref) {
|
|
855
|
+
const parsed = parseConfigs(source);
|
|
856
|
+
if ("reason" in parsed) return parsed;
|
|
857
|
+
const config = selectConfig(parsed.configs, ref);
|
|
858
|
+
if (!config) return { reason: `no config entry found for ${JSON.stringify(ref)}` };
|
|
859
|
+
return {
|
|
860
|
+
mod: parsed.mod,
|
|
861
|
+
config
|
|
862
|
+
};
|
|
410
863
|
}
|
|
411
864
|
/**
|
|
412
|
-
*
|
|
413
|
-
*
|
|
414
|
-
*
|
|
865
|
+
* Applies edits to a `kubb.config.ts` in place. Every node the edits do not touch keeps its
|
|
866
|
+
* original text, so comments, formatting, and hand-written code around the config survive.
|
|
867
|
+
*
|
|
868
|
+
* Edits are independent: one that cannot be applied is reported in `outcomes` and the rest still run.
|
|
869
|
+
*
|
|
870
|
+
* @example
|
|
871
|
+
* ```ts
|
|
872
|
+
* const { source, outcomes } = applyConfigEdits(current, [
|
|
873
|
+
* { operation: 'set', plugin: '@kubb/plugin-ts', path: ['enum', 'type'], value: 'enum' },
|
|
874
|
+
* ])
|
|
875
|
+
* ```
|
|
876
|
+
*
|
|
877
|
+
* @note recast always reprints a semicolon on a reprinted statement, so editing a block-body
|
|
878
|
+
* `defineConfig` in a semicolon-free file adds one to the `return` line. This is a known gap.
|
|
879
|
+
* Strip it when `detectCodeFormat` reports `useSemi: false`, if it turns out to matter in practice.
|
|
415
880
|
*/
|
|
416
|
-
function
|
|
881
|
+
function applyConfigEdits(source, edits) {
|
|
882
|
+
let current = source;
|
|
883
|
+
const format = detectCodeFormat(source);
|
|
884
|
+
const endsWithNewline = source.endsWith("\n");
|
|
885
|
+
const outcomes = edits.map((edit) => {
|
|
886
|
+
const target = parseTarget(current, edit.config);
|
|
887
|
+
if ("reason" in target) return {
|
|
888
|
+
edit,
|
|
889
|
+
applied: false,
|
|
890
|
+
reason: target.reason
|
|
891
|
+
};
|
|
892
|
+
const { mod, config } = target;
|
|
893
|
+
if (edit.operation === "disable-plugin" || edit.operation === "enable-plugin") {
|
|
894
|
+
const result = edit.operation === "disable-plugin" ? disablePlugin(current, mod, config, edit.plugin) : enablePlugin(current, edit.plugin);
|
|
895
|
+
if ("reason" in result) return {
|
|
896
|
+
edit,
|
|
897
|
+
applied: false,
|
|
898
|
+
reason: result.reason
|
|
899
|
+
};
|
|
900
|
+
current = result.source;
|
|
901
|
+
return {
|
|
902
|
+
edit,
|
|
903
|
+
applied: true
|
|
904
|
+
};
|
|
905
|
+
}
|
|
906
|
+
if (edit.operation === "add-plugin") {
|
|
907
|
+
const result = applyAddPlugin(mod, config, edit);
|
|
908
|
+
if ("reason" in result) return {
|
|
909
|
+
edit,
|
|
910
|
+
applied: false,
|
|
911
|
+
reason: result.reason
|
|
912
|
+
};
|
|
913
|
+
if ("noop" in result) return {
|
|
914
|
+
edit,
|
|
915
|
+
applied: true
|
|
916
|
+
};
|
|
917
|
+
const afterLine = lastImportEndLine(mod);
|
|
918
|
+
let next = generateCode(mod, { format }).code;
|
|
919
|
+
if (result.addImport) next = insertImportLine({
|
|
920
|
+
source: next,
|
|
921
|
+
afterLine,
|
|
922
|
+
...result.addImport
|
|
923
|
+
});
|
|
924
|
+
current = withTrailingNewline(next, endsWithNewline);
|
|
925
|
+
return {
|
|
926
|
+
edit,
|
|
927
|
+
applied: true
|
|
928
|
+
};
|
|
929
|
+
}
|
|
930
|
+
const pluginCall = pluginCalls(mod, config).find((plugin) => plugin.packageName === edit.plugin);
|
|
931
|
+
if (!pluginCall) return {
|
|
932
|
+
edit,
|
|
933
|
+
applied: false,
|
|
934
|
+
reason: `${edit.plugin} is not in the plugins array`
|
|
935
|
+
};
|
|
936
|
+
const reason = edit.operation === "set" ? applySet(pluginCall.call, edit.path, edit.value) : applyRemove(pluginCall.call, edit.path);
|
|
937
|
+
if (!reason) current = withTrailingNewline(generateCode(mod, { format }).code, endsWithNewline);
|
|
938
|
+
return {
|
|
939
|
+
edit,
|
|
940
|
+
applied: !reason,
|
|
941
|
+
reason
|
|
942
|
+
};
|
|
943
|
+
});
|
|
417
944
|
return {
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
945
|
+
source: current,
|
|
946
|
+
outcomes,
|
|
947
|
+
changed: current !== source
|
|
421
948
|
};
|
|
422
949
|
}
|
|
950
|
+
async function writeConfigEdits({ filePath, edits }) {
|
|
951
|
+
const result = applyConfigEdits(await read(filePath), edits);
|
|
952
|
+
if (result.changed) await writeFile(filePath, result.source, "utf-8");
|
|
953
|
+
return result;
|
|
954
|
+
}
|
|
423
955
|
/**
|
|
424
|
-
*
|
|
425
|
-
*
|
|
956
|
+
* The 1-based line where the file's last import declaration ends, or `0` when it has none. Read
|
|
957
|
+
* off the parsed module, so a multi-line `import {\n x,\n} from '...'` reports its closing line
|
|
958
|
+
* rather than the `import` keyword.
|
|
426
959
|
*/
|
|
427
|
-
function
|
|
428
|
-
return
|
|
960
|
+
function lastImportEndLine(mod) {
|
|
961
|
+
return (mod.$ast.type === "Program" ? mod.$ast.body : []).filter((node) => node.type === "ImportDeclaration").at(-1)?.loc?.end.line ?? 0;
|
|
962
|
+
}
|
|
963
|
+
/**
|
|
964
|
+
* Writes an import after the last one already in the file, matching its quote style and whether it
|
|
965
|
+
* ends in a semicolon. `afterLine` is where that last import ends, `0` for a file with none.
|
|
966
|
+
*
|
|
967
|
+
* Written as plain text rather than through magicast's import builder, which prints a brand-new
|
|
968
|
+
* import declaration with its own default spacing and a semicolon regardless of `format`, since
|
|
969
|
+
* that formatting only governs nodes recast can diff against the original source.
|
|
970
|
+
*/
|
|
971
|
+
function insertImportLine({ source, importName, moduleSpecifier, afterLine }) {
|
|
972
|
+
const lines = source.split("\n");
|
|
973
|
+
const lastImportLine = afterLine > 0 ? lines[afterLine - 1] : void 0;
|
|
974
|
+
const quote = lastImportLine?.includes(`"`) ? `"` : `'`;
|
|
975
|
+
const line = `import { ${importName} } from ${quote}${moduleSpecifier}${quote}${lastImportLine?.trimEnd().endsWith(";") ? ";" : ""}`;
|
|
976
|
+
lines.splice(afterLine, 0, ...afterLine > 0 ? [line] : [line, ""]);
|
|
977
|
+
return lines.join("\n");
|
|
978
|
+
}
|
|
979
|
+
/**
|
|
980
|
+
* `generateCode` always drops the file's trailing newline. Restore it when the input had one.
|
|
981
|
+
*/
|
|
982
|
+
function withTrailingNewline(code, hadTrailingNewline) {
|
|
983
|
+
if (!hadTrailingNewline || code.endsWith("\n")) return code;
|
|
984
|
+
return `${code}\n`;
|
|
429
985
|
}
|
|
430
986
|
//#endregion
|
|
431
|
-
//#region
|
|
432
|
-
var version = "5.6.0";
|
|
433
|
-
//#endregion
|
|
434
|
-
//#region src/operations/generations.ts
|
|
987
|
+
//#region src/generations.ts
|
|
435
988
|
const READ_CONCURRENCY = 50;
|
|
436
989
|
const MB = 1048576;
|
|
437
990
|
const INDEX_KEY = "studio/generations.json";
|
|
@@ -441,8 +994,65 @@ const INDEX_KEY = "studio/generations.json";
|
|
|
441
994
|
function relativeStoragePath({ root, filePath }) {
|
|
442
995
|
return (isAbsolute(filePath) ? relative(resolve(root), filePath) : filePath).replaceAll("\\", "/");
|
|
443
996
|
}
|
|
997
|
+
/**
|
|
998
|
+
* The content fingerprint Studio compares snapshots by. Agent runs and CI uploads must agree on it.
|
|
999
|
+
*/
|
|
444
1000
|
const hashOf = (content) => createHash("sha1").update(content).digest("hex").slice(0, 16);
|
|
445
1001
|
const totalBytes = (entries) => entries.reduce((sum, { output, disk }) => sum + output.bytes + (disk?.bytes ?? 0), 0);
|
|
1002
|
+
function positiveNumber(value) {
|
|
1003
|
+
const parsed = Number(value);
|
|
1004
|
+
return value && Number.isFinite(parsed) && parsed > 0 ? parsed : void 0;
|
|
1005
|
+
}
|
|
1006
|
+
/**
|
|
1007
|
+
* How many generations an agent keeps and how large they may get, read from
|
|
1008
|
+
* `KUBB_AGENT_MAX_GENERATIONS`, `KUBB_AGENT_MAX_GENERATIONS_MB` and `KUBB_AGENT_MAX_SNAPSHOT_MB`.
|
|
1009
|
+
* An unset or invalid value keeps the default.
|
|
1010
|
+
*/
|
|
1011
|
+
function resolveGenerationLimits() {
|
|
1012
|
+
return {
|
|
1013
|
+
maxCount: Math.max(1, Math.floor(positiveNumber(process$1.env.KUBB_AGENT_MAX_GENERATIONS) ?? 8)),
|
|
1014
|
+
maxMb: positiveNumber(process$1.env.KUBB_AGENT_MAX_GENERATIONS_MB) ?? 100,
|
|
1015
|
+
maxSnapshotMb: positiveNumber(process$1.env.KUBB_AGENT_MAX_SNAPSHOT_MB) ?? 50
|
|
1016
|
+
};
|
|
1017
|
+
}
|
|
1018
|
+
/**
|
|
1019
|
+
* Folds error-severity diagnostics into one thrown error so logs name the failing plugin or pass.
|
|
1020
|
+
*/
|
|
1021
|
+
function generationFailure(diagnostics) {
|
|
1022
|
+
const reasons = diagnostics.filter(Diagnostics.isProblem).filter((diagnostic) => diagnostic.severity === "error").map((diagnostic) => diagnostic.plugin ? `${diagnostic.plugin}: ${diagnostic.message}` : diagnostic.message);
|
|
1023
|
+
if (!reasons.length) return /* @__PURE__ */ new Error("Generation failed");
|
|
1024
|
+
return /* @__PURE__ */ new Error(`Generation failed: ${reasons.length} error${reasons.length === 1 ? "" : "s"}: ${reasons.join("; ")}`);
|
|
1025
|
+
}
|
|
1026
|
+
/**
|
|
1027
|
+
* Runs one generation and returns the files it produced. The formatter, the linter, and
|
|
1028
|
+
* `output.postGenerate` only run with `allowExec`. Throws when any plugin reports an error.
|
|
1029
|
+
*/
|
|
1030
|
+
async function generate({ config, hooks, signal, allowExec }) {
|
|
1031
|
+
const output = allowExec ? config.output : {
|
|
1032
|
+
...config.output,
|
|
1033
|
+
format: false,
|
|
1034
|
+
lint: false,
|
|
1035
|
+
postGenerate: []
|
|
1036
|
+
};
|
|
1037
|
+
const kubb = createKubb({
|
|
1038
|
+
...config,
|
|
1039
|
+
output
|
|
1040
|
+
}, {
|
|
1041
|
+
hooks,
|
|
1042
|
+
signal
|
|
1043
|
+
});
|
|
1044
|
+
const result = await kubb.generate();
|
|
1045
|
+
if (!result.success) throw generationFailure(result.diagnostics);
|
|
1046
|
+
const { storage, root } = kubb.config;
|
|
1047
|
+
return {
|
|
1048
|
+
storage,
|
|
1049
|
+
root,
|
|
1050
|
+
paths: new Set(result.files.map((file) => relativeStoragePath({
|
|
1051
|
+
root,
|
|
1052
|
+
filePath: file.path
|
|
1053
|
+
})))
|
|
1054
|
+
};
|
|
1055
|
+
}
|
|
446
1056
|
/**
|
|
447
1057
|
* What the output directory holds on disk before a run. `undefined` when `outputPath` is not a real
|
|
448
1058
|
* subdirectory of `root` (listing the root would take in every source file) or holds more than `maxFiles`.
|
|
@@ -521,9 +1131,6 @@ function createGenerationStore({ storage, maxCount, maxMb, ttlMs, now = Date.now
|
|
|
521
1131
|
keep,
|
|
522
1132
|
drop,
|
|
523
1133
|
get: async (jobId) => (await load()).find((generation) => generation.jobId === jobId && isLive(generation)),
|
|
524
|
-
latest: async () => (await load()).filter(isLive).at(-1),
|
|
525
|
-
/** Total bytes of every set the store holds, expired ones too until the next add drops them. */
|
|
526
|
-
bytes: async () => totalBytes(await load()),
|
|
527
1134
|
async add(generation) {
|
|
528
1135
|
const current = await load();
|
|
529
1136
|
for (const expired of current.filter((entry) => !isLive(entry))) await drop(expired.jobId);
|
|
@@ -570,7 +1177,7 @@ function createGenerationStore({ storage, maxCount, maxMb, ttlMs, now = Date.now
|
|
|
570
1177
|
};
|
|
571
1178
|
}
|
|
572
1179
|
//#endregion
|
|
573
|
-
//#region src/
|
|
1180
|
+
//#region src/generationEvents.ts
|
|
574
1181
|
const MAX_QUEUED_EVENTS = 1024;
|
|
575
1182
|
const RESERVED_EVENTS = 64;
|
|
576
1183
|
const isDiscardable = (event) => event.type === "kubb:files:processing:update" || event.type === "kubb:info" || event.type === "kubb:success";
|
|
@@ -751,423 +1358,151 @@ function createGenerationStream(hooks, jobId) {
|
|
|
751
1358
|
};
|
|
752
1359
|
}
|
|
753
1360
|
//#endregion
|
|
754
|
-
//#region src/
|
|
755
|
-
const CONNECT_TIMEOUT_MS = 5e3;
|
|
756
|
-
/**
|
|
757
|
-
* The only methods Studio may call on an agent. A `StudioSession` carries far more than
|
|
758
|
-
* {@link AgentApi}, so it is wrapped rather than exposed: what Cap'n Web can reach is exactly what
|
|
759
|
-
* this class re-declares.
|
|
760
|
-
*/
|
|
761
|
-
var AgentRpcTarget = class extends RpcTarget {
|
|
762
|
-
api;
|
|
763
|
-
constructor(api) {
|
|
764
|
-
super();
|
|
765
|
-
this.api = api;
|
|
766
|
-
}
|
|
767
|
-
connect() {
|
|
768
|
-
return this.api.connect();
|
|
769
|
-
}
|
|
770
|
-
startGeneration(input) {
|
|
771
|
-
return this.api.startGeneration(input);
|
|
772
|
-
}
|
|
773
|
-
saveConfig(input) {
|
|
774
|
-
return this.api.saveConfig(input);
|
|
775
|
-
}
|
|
776
|
-
publishSnapshot(input) {
|
|
777
|
-
return this.api.publishSnapshot(input);
|
|
778
|
-
}
|
|
779
|
-
readFiles(input) {
|
|
780
|
-
return this.api.readFiles(input);
|
|
781
|
-
}
|
|
782
|
-
cancel(jobId) {
|
|
783
|
-
return this.api.cancel(jobId);
|
|
784
|
-
}
|
|
785
|
-
};
|
|
1361
|
+
//#region src/url.ts
|
|
786
1362
|
/**
|
|
787
|
-
*
|
|
788
|
-
* fires no `close` event when the handshake itself fails, only `error`, so `closed` settles as 1006 there.
|
|
1363
|
+
* Hosted Kubb Studio URL, used when a host passes none.
|
|
789
1364
|
*/
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
return
|
|
793
|
-
socket,
|
|
794
|
-
closed: new Promise((resolve) => {
|
|
795
|
-
let opened = false;
|
|
796
|
-
const timer = setTimeout(() => {
|
|
797
|
-
if (socket.readyState === WebSocket.CONNECTING) socket.close(3008, "Connection timeout");
|
|
798
|
-
}, CONNECT_TIMEOUT_MS);
|
|
799
|
-
socket.addEventListener("open", () => {
|
|
800
|
-
opened = true;
|
|
801
|
-
clearTimeout(timer);
|
|
802
|
-
}, { once: true });
|
|
803
|
-
socket.addEventListener("close", (event) => {
|
|
804
|
-
clearTimeout(timer);
|
|
805
|
-
resolve({
|
|
806
|
-
code: event.code,
|
|
807
|
-
reason: event.reason
|
|
808
|
-
});
|
|
809
|
-
}, { once: true });
|
|
810
|
-
socket.addEventListener("error", () => {
|
|
811
|
-
if (opened) return;
|
|
812
|
-
clearTimeout(timer);
|
|
813
|
-
resolve({
|
|
814
|
-
code: 1006,
|
|
815
|
-
reason: ""
|
|
816
|
-
});
|
|
817
|
-
});
|
|
818
|
-
})
|
|
819
|
-
};
|
|
1365
|
+
const defaultStudioUrl = "https://kubb.studio";
|
|
1366
|
+
function isLoopbackHost(hostname) {
|
|
1367
|
+
return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
|
|
820
1368
|
}
|
|
821
1369
|
/**
|
|
822
|
-
*
|
|
823
|
-
*
|
|
1370
|
+
* Appends `path` to the Studio URL and refuses plaintext to anything but this machine, so a token
|
|
1371
|
+
* or API key never crosses the network unencrypted. `socket` switches the scheme to `ws:`/`wss:`.
|
|
824
1372
|
*
|
|
825
1373
|
* @example
|
|
826
1374
|
* ```ts
|
|
827
|
-
*
|
|
828
|
-
* await rpc.studio.ping()
|
|
1375
|
+
* secureUrl({ studioUrl: 'https://kubb.studio', path: '/api/agent/socket', socket: true }).href // 'wss://kubb.studio/api/agent/socket'
|
|
829
1376
|
* ```
|
|
830
1377
|
*/
|
|
831
|
-
|
|
832
|
-
const
|
|
833
|
-
if (protocol !== "
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
Authorization: `Bearer ${token}`,
|
|
838
|
-
[AGENT_INSTANCE_HEADER]: instanceId
|
|
839
|
-
}
|
|
840
|
-
});
|
|
841
|
-
const studio = newWebSocketRpcSession(socket, new AgentRpcTarget(local));
|
|
842
|
-
studio.onRpcBroken(() => socket.close());
|
|
843
|
-
return {
|
|
844
|
-
studio,
|
|
845
|
-
closed,
|
|
846
|
-
close: () => studio[Symbol.dispose]()
|
|
847
|
-
};
|
|
848
|
-
};
|
|
1378
|
+
function secureUrl({ studioUrl, path, socket = false }) {
|
|
1379
|
+
const url = new URL(`${studioUrl.replace(/\/+$/, "")}${path}`);
|
|
1380
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && isLoopbackHost(url.hostname))) throw new Error(`Refusing to reach Kubb Studio at ${url.origin}: use an https:// URL, or a loopback host for local development`);
|
|
1381
|
+
if (socket) url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
1382
|
+
return url;
|
|
1383
|
+
}
|
|
849
1384
|
//#endregion
|
|
850
|
-
//#region src/
|
|
1385
|
+
//#region src/connect.ts
|
|
1386
|
+
const HEARTBEAT_INTERVAL_MS = 3e4;
|
|
1387
|
+
const MAX_HEARTBEAT_INTERVAL_MS = 6e4;
|
|
1388
|
+
const PING_TIMEOUT_MS = 1e4;
|
|
1389
|
+
const OPEN_TIMEOUT_MS = 5e3;
|
|
1390
|
+
const MAX_RETRY_DELAY_MS = 3e4;
|
|
851
1391
|
const DISK_SNAPSHOT_MAX_FILES = 1e4;
|
|
1392
|
+
const SANDBOX_GENERATION_TTL_MS = 9e5;
|
|
852
1393
|
/**
|
|
853
|
-
*
|
|
1394
|
+
* Studio closed with {@link AgentCloseCode.UNAUTHORIZED}. Hosts forget the token and pair again.
|
|
854
1395
|
*/
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
}
|
|
860
|
-
|
|
861
|
-
const SANDBOX_GENERATION_TTL_MS = 9e5;
|
|
1396
|
+
var InvalidAgentTokenError = class extends Error {
|
|
1397
|
+
constructor(studioUrl) {
|
|
1398
|
+
super(`Kubb Studio rejected this agent's token. It expired or was revoked, or the agent was deleted in ${studioUrl}.`);
|
|
1399
|
+
this.name = "InvalidAgentTokenError";
|
|
1400
|
+
}
|
|
1401
|
+
};
|
|
862
1402
|
/**
|
|
863
|
-
*
|
|
864
|
-
* shared the agent's own root would read each other's manifest.
|
|
1403
|
+
* Studio closed with {@link AgentCloseCode.INCOMPATIBLE}. Only an upgrade helps.
|
|
865
1404
|
*/
|
|
866
|
-
|
|
867
|
-
|
|
1405
|
+
var IncompatibleAgentError = class extends Error {
|
|
1406
|
+
constructor({ studioUrl, detail }) {
|
|
1407
|
+
super(`Kubb Studio at ${studioUrl} requires a newer agent${detail ? `: ${detail}` : ""}. Upgrade kubb or the Kubb agent image.`);
|
|
1408
|
+
this.name = "IncompatibleAgentError";
|
|
1409
|
+
}
|
|
1410
|
+
};
|
|
1411
|
+
function emit(hooks, name, ...args) {
|
|
1412
|
+
return Promise.resolve(hooks.callHook(name, ...args)).catch(() => {});
|
|
868
1413
|
}
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
async function removeJobRoot(jobRoot) {
|
|
874
|
-
await Promise.all([rm(jobRoot, {
|
|
875
|
-
recursive: true,
|
|
876
|
-
force: true
|
|
877
|
-
}), rm(resolveCacheDir(jobRoot), {
|
|
878
|
-
recursive: true,
|
|
879
|
-
force: true
|
|
880
|
-
})]).catch(() => {});
|
|
1414
|
+
function isValidPage({ cursor, limit }) {
|
|
1415
|
+
if (limit === void 0) return cursor === void 0;
|
|
1416
|
+
if (cursor !== void 0 && (!Number.isSafeInteger(cursor) || cursor < 0)) return false;
|
|
1417
|
+
return Number.isSafeInteger(limit) && limit >= 1 && limit <= 2e3;
|
|
881
1418
|
}
|
|
882
1419
|
var GenerationRunTarget = class extends RpcTarget {
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
cancelGeneration;
|
|
886
|
-
stopGeneration;
|
|
887
|
-
constructor(generationStream, generationResult, cancelGeneration, stopGeneration) {
|
|
1420
|
+
#run;
|
|
1421
|
+
constructor(run) {
|
|
888
1422
|
super();
|
|
889
|
-
this
|
|
890
|
-
this.generationResult = generationResult;
|
|
891
|
-
this.cancelGeneration = cancelGeneration;
|
|
892
|
-
this.stopGeneration = stopGeneration;
|
|
1423
|
+
this.#run = run;
|
|
893
1424
|
}
|
|
894
1425
|
async events() {
|
|
895
|
-
return this.
|
|
1426
|
+
return this.#run.stream;
|
|
896
1427
|
}
|
|
897
1428
|
result() {
|
|
898
|
-
return this.
|
|
1429
|
+
return this.#run.result;
|
|
899
1430
|
}
|
|
900
|
-
cancel() {
|
|
901
|
-
|
|
1431
|
+
async cancel() {
|
|
1432
|
+
this.#run.stop();
|
|
902
1433
|
}
|
|
903
1434
|
[Symbol.dispose]() {
|
|
904
|
-
this.
|
|
1435
|
+
this.#run.stop();
|
|
905
1436
|
}
|
|
906
1437
|
};
|
|
907
|
-
|
|
908
|
-
* Fills in a host's options: the hosted Studio URL, the current working directory, and every
|
|
909
|
-
* permission off unless granted. Idempotent, so a reconnect can pass an already-resolved bag
|
|
910
|
-
* back in.
|
|
911
|
-
*/
|
|
912
|
-
function applyStudioDefaults(options) {
|
|
913
|
-
const root = options.root ?? process$1.cwd();
|
|
914
|
-
return {
|
|
915
|
-
...options,
|
|
916
|
-
studioUrl: options.studioUrl ?? agentDefaults.studioUrl,
|
|
917
|
-
root,
|
|
918
|
-
configFile: path.resolve(root, options.configPath),
|
|
919
|
-
permissions: {
|
|
920
|
-
allowWrite: false,
|
|
921
|
-
allowConfigEdit: false,
|
|
922
|
-
allowExec: false,
|
|
923
|
-
allowRead: false,
|
|
924
|
-
...options.permissions
|
|
925
|
-
},
|
|
926
|
-
heartbeatInterval: Math.min(options.heartbeatInterval ?? agentDefaults.heartbeatIntervalMs, agentDefaults.maxHeartbeatIntervalMs),
|
|
927
|
-
capacity: {
|
|
928
|
-
...resolveAgentCapacity(),
|
|
929
|
-
...options.capacity
|
|
930
|
-
},
|
|
931
|
-
instanceId: options.instanceId ?? randomUUID()
|
|
932
|
-
};
|
|
933
|
-
}
|
|
934
|
-
/**
|
|
935
|
-
* Jobs one agent process can run at once today. Two runs would share this session's hook emitter,
|
|
936
|
-
* and with it each other's events, so the connection keeps this limit.
|
|
937
|
-
*/
|
|
938
|
-
const RUNTIME_MAX_CONCURRENT = 1;
|
|
939
|
-
/**
|
|
940
|
-
* Reads what Studio meant by closing the connection. A code Studio did not send on purpose is an
|
|
941
|
-
* ordinary drop, and the agent reconnects as it always has.
|
|
942
|
-
*/
|
|
943
|
-
function planEnd(close) {
|
|
944
|
-
const code = close?.code;
|
|
945
|
-
if (code === AgentCloseCode.REAUTHENTICATE) return {
|
|
946
|
-
reason: "Kubb Studio asked the agent to register again",
|
|
947
|
-
retry: true
|
|
948
|
-
};
|
|
949
|
-
if (code === AgentCloseCode.SUPERSEDED) return {
|
|
950
|
-
reason: "another instance of this agent took over",
|
|
951
|
-
retry: false
|
|
952
|
-
};
|
|
953
|
-
if (code === AgentCloseCode.INCOMPATIBLE) return {
|
|
954
|
-
reason: "this agent is too old for Kubb Studio, or was deleted",
|
|
955
|
-
retry: false,
|
|
956
|
-
error: /* @__PURE__ */ new Error("Kubb Studio closed the connection: this agent is too old for it, or was deleted. Upgrade the agent, or pair it again.")
|
|
957
|
-
};
|
|
958
|
-
return {
|
|
959
|
-
reason: "connection closed",
|
|
960
|
-
retry: true
|
|
961
|
-
};
|
|
962
|
-
}
|
|
963
|
-
function isValidPage({ cursor, limit }) {
|
|
964
|
-
if (limit === void 0) return cursor === void 0;
|
|
965
|
-
if (cursor !== void 0 && (!Number.isSafeInteger(cursor) || cursor < 0)) return false;
|
|
966
|
-
return Number.isSafeInteger(limit) && limit >= 1 && limit <= 2e3;
|
|
967
|
-
}
|
|
968
|
-
/**
|
|
969
|
-
* One agent-to-Studio RPC transport: opening it, keeping it alive, and serving remote methods.
|
|
970
|
-
* `runConnection` owns the lifetime and retry of each attempt.
|
|
971
|
-
*/
|
|
972
|
-
var StudioSession = class {
|
|
1438
|
+
var Agent = class extends RpcTarget {
|
|
973
1439
|
#options;
|
|
974
|
-
#
|
|
975
|
-
/**
|
|
976
|
-
* Removers for every listener this session added (socket, shutdown signal, hooks) so `dispose`
|
|
977
|
-
* detaches them in one pass. Listeners a host attached itself through `installLogger` survive.
|
|
978
|
-
*/
|
|
979
|
-
#unhooks = [];
|
|
980
|
-
/**
|
|
981
|
-
* What registration handed back, and the marker for whether the agent registered at all.
|
|
982
|
-
* Before it resolves there is no sandbox flag to read.
|
|
983
|
-
*/
|
|
984
|
-
#registration;
|
|
985
|
-
#rpc;
|
|
986
|
-
#disposed = false;
|
|
987
|
-
#isGenerating = false;
|
|
988
|
-
#activeJob;
|
|
989
|
-
#heartbeatTimer;
|
|
990
|
-
#store;
|
|
1440
|
+
#session;
|
|
991
1441
|
#limits = resolveGenerationLimits();
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
#ended = Promise.withResolvers();
|
|
998
|
-
closed = this.#ended.promise;
|
|
999
|
-
#generationResult;
|
|
1000
|
-
constructor(options) {
|
|
1001
|
-
this.#options = applyStudioDefaults(options);
|
|
1002
|
-
this.#connectAck.promise.catch(() => {});
|
|
1442
|
+
#store;
|
|
1443
|
+
constructor({ options, session }) {
|
|
1444
|
+
super();
|
|
1445
|
+
this.#options = options;
|
|
1446
|
+
this.#session = session;
|
|
1003
1447
|
}
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
get #
|
|
1008
|
-
|
|
1448
|
+
get #sandbox() {
|
|
1449
|
+
return this.#session.info?.sandbox === true;
|
|
1450
|
+
}
|
|
1451
|
+
get #permissions() {
|
|
1452
|
+
const { permissions } = this.#options;
|
|
1453
|
+
return this.#sandbox ? {
|
|
1454
|
+
...permissions,
|
|
1455
|
+
allowWrite: false,
|
|
1456
|
+
allowConfigEdit: false,
|
|
1457
|
+
allowRead: true
|
|
1458
|
+
} : permissions;
|
|
1009
1459
|
}
|
|
1010
|
-
/**
|
|
1011
|
-
* Kept in the project's cache directory, so it survives a restart, except on a sandbox: its pool
|
|
1012
|
-
* sessions run every tenant's jobs, so it keeps them in memory. Looked up by job id only.
|
|
1013
|
-
*/
|
|
1014
1460
|
get #generations() {
|
|
1015
1461
|
this.#store ??= createGenerationStore({
|
|
1016
|
-
storage: this.#
|
|
1462
|
+
storage: this.#sandbox ? memoryStorage() : cacheStorage({ root: this.#options.root }),
|
|
1017
1463
|
maxCount: this.#limits.maxCount,
|
|
1018
1464
|
maxMb: this.#limits.maxMb,
|
|
1019
|
-
ttlMs: this.#
|
|
1465
|
+
ttlMs: this.#sandbox ? SANDBOX_GENERATION_TTL_MS : void 0
|
|
1020
1466
|
});
|
|
1021
1467
|
return this.#store;
|
|
1022
1468
|
}
|
|
1023
|
-
|
|
1024
|
-
return
|
|
1025
|
-
}
|
|
1026
|
-
get #canEditConfig() {
|
|
1027
|
-
return !this.#isSandbox && this.#options.permissions.allowConfigEdit;
|
|
1028
|
-
}
|
|
1029
|
-
/**
|
|
1030
|
-
* A sandbox agent always allows reading its output back; a local agent only when opted in.
|
|
1031
|
-
*/
|
|
1032
|
-
get #canRead() {
|
|
1033
|
-
return this.#isSandbox || this.#options.permissions.allowRead;
|
|
1034
|
-
}
|
|
1035
|
-
async start() {
|
|
1036
|
-
const { token, studioUrl, signal, heartbeatInterval, installLogger, instanceId, capacity } = this.#options;
|
|
1037
|
-
await installLogger?.(this.#hooks);
|
|
1038
|
-
signal?.addEventListener("abort", this.#onAbort, { once: true });
|
|
1039
|
-
this.#unhooks.push(() => signal?.removeEventListener("abort", this.#onAbort));
|
|
1040
|
-
try {
|
|
1041
|
-
signal?.throwIfAborted();
|
|
1042
|
-
await this.#hooks.callHook("studio:connecting", { url: studioUrl });
|
|
1043
|
-
if (capacity.maxConcurrent > RUNTIME_MAX_CONCURRENT) await this.#warn(`Running ${RUNTIME_MAX_CONCURRENT} job at a time: KUBB_AGENT_MAX_CONCURRENT=${capacity.maxConcurrent} needs per-job workers, which this agent does not have yet`);
|
|
1044
|
-
const registration = await registerAgent({
|
|
1045
|
-
signal,
|
|
1046
|
-
token,
|
|
1047
|
-
studioUrl,
|
|
1048
|
-
instanceId,
|
|
1049
|
-
capacity: {
|
|
1050
|
-
...capacity,
|
|
1051
|
-
maxConcurrent: Math.min(capacity.maxConcurrent, RUNTIME_MAX_CONCURRENT)
|
|
1052
|
-
}
|
|
1053
|
-
});
|
|
1054
|
-
signal?.throwIfAborted();
|
|
1055
|
-
this.#registration = registration;
|
|
1056
|
-
const rpc = await (this.#options.connector ?? connectWebSocketRpc)({
|
|
1057
|
-
url: registration.socketUrl,
|
|
1058
|
-
token,
|
|
1059
|
-
instanceId,
|
|
1060
|
-
local: this
|
|
1061
|
-
});
|
|
1062
|
-
this.#rpc = rpc;
|
|
1063
|
-
rpc.closed.then(this.#onClose);
|
|
1064
|
-
if (signal?.aborted || this.#disposed) {
|
|
1065
|
-
rpc.close();
|
|
1066
|
-
throw new Error("Connection stopped during startup");
|
|
1067
|
-
}
|
|
1068
|
-
this.#scheduleHeartbeat(heartbeatInterval);
|
|
1069
|
-
await this.#hooks.callHook("studio:connected", {
|
|
1070
|
-
url: studioUrl,
|
|
1071
|
-
versions: {
|
|
1072
|
-
studio: registration.version,
|
|
1073
|
-
kubb: version,
|
|
1074
|
-
agent: this.#options.version
|
|
1075
|
-
},
|
|
1076
|
-
agentSlug: registration.agentSlug,
|
|
1077
|
-
organizationSlug: registration.organizationSlug
|
|
1078
|
-
});
|
|
1079
|
-
await this.#connectAck.promise;
|
|
1080
|
-
await this.#hooks.callHook("studio:ready", {});
|
|
1081
|
-
} catch (error) {
|
|
1082
|
-
await this.dispose();
|
|
1083
|
-
if (!signal?.aborted) await this.#hooks.callHook("studio:error", { error: toError(error) });
|
|
1084
|
-
throw error;
|
|
1085
|
-
}
|
|
1086
|
-
}
|
|
1087
|
-
reportRetry(delayMs) {
|
|
1088
|
-
return this.#hooks.callHook("studio:reconnecting", { delayMs });
|
|
1089
|
-
}
|
|
1090
|
-
#warn(message, permission) {
|
|
1091
|
-
return this.#hooks.callHook("studio:warn", {
|
|
1469
|
+
#warn({ message, permission }) {
|
|
1470
|
+
return emit(this.#options.hooks, "studio:warn", {
|
|
1092
1471
|
message,
|
|
1093
1472
|
permission
|
|
1094
1473
|
});
|
|
1095
1474
|
}
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
await this.#warn(reason, permission);
|
|
1475
|
+
async #refuse({ message, permission }) {
|
|
1476
|
+
await this.#warn({
|
|
1477
|
+
message,
|
|
1478
|
+
permission
|
|
1479
|
+
});
|
|
1102
1480
|
throw new Error(message);
|
|
1103
1481
|
}
|
|
1104
|
-
/**
|
|
1105
|
-
* Brackets one Studio command with `studio:command:start` and `studio:command:end`. A command
|
|
1106
|
-
* that declined its request reports no `info`, and only the start is heard.
|
|
1107
|
-
*/
|
|
1108
1482
|
async #command({ command, run }) {
|
|
1109
|
-
|
|
1483
|
+
if (!this.#session.info) throw new Error("Studio must call connect() before any other command");
|
|
1110
1484
|
const { value, info } = await run();
|
|
1111
|
-
if (info !== void 0) await this.#hooks
|
|
1485
|
+
if (info !== void 0) await emit(this.#options.hooks, "studio:command", {
|
|
1112
1486
|
command,
|
|
1113
1487
|
info
|
|
1114
1488
|
});
|
|
1115
1489
|
return value;
|
|
1116
1490
|
}
|
|
1117
|
-
#scheduleHeartbeat(interval) {
|
|
1118
|
-
const rpc = this.#rpc;
|
|
1119
|
-
if (!rpc) return;
|
|
1120
|
-
this.#heartbeatTimer = setTimeout(async () => {
|
|
1121
|
-
try {
|
|
1122
|
-
await this.#ping(rpc);
|
|
1123
|
-
} catch {
|
|
1124
|
-
if (this.#rpc === rpc) rpc.close();
|
|
1125
|
-
return;
|
|
1126
|
-
}
|
|
1127
|
-
if (this.#rpc === rpc) this.#scheduleHeartbeat(interval);
|
|
1128
|
-
}, interval);
|
|
1129
|
-
}
|
|
1130
|
-
/**
|
|
1131
|
-
* Races `studio.ping()` against a deadline, so a half-open socket can't hang it forever.
|
|
1132
|
-
* */
|
|
1133
|
-
async #ping(rpc) {
|
|
1134
|
-
const { promise: timedOut, reject: onTimeout } = Promise.withResolvers();
|
|
1135
|
-
const timer = setTimeout(() => onTimeout(/* @__PURE__ */ new Error("Heartbeat ping timed out")), agentDefaults.heartbeatTimeoutMs);
|
|
1136
|
-
try {
|
|
1137
|
-
const load = await Promise.race([this.#load().catch(() => void 0), timedOut]);
|
|
1138
|
-
await Promise.race([rpc.studio.ping(load), timedOut]);
|
|
1139
|
-
} finally {
|
|
1140
|
-
clearTimeout(timer);
|
|
1141
|
-
}
|
|
1142
|
-
}
|
|
1143
|
-
async #load() {
|
|
1144
|
-
return {
|
|
1145
|
-
running: this.#isGenerating ? 1 : 0,
|
|
1146
|
-
rssMb: Math.round(process$1.memoryUsage().rss / 1048576),
|
|
1147
|
-
storeBytes: await this.#generations.bytes(),
|
|
1148
|
-
accepting: true
|
|
1149
|
-
};
|
|
1150
|
-
}
|
|
1151
|
-
/**
|
|
1152
|
-
* Reads `kubb.config.ts` and reports which plugin options Studio may edit.
|
|
1153
|
-
*
|
|
1154
|
-
* Skipped when the host did not grant `allowConfigEdit`. Not cached: the user can edit the file
|
|
1155
|
-
* between two Studio actions.
|
|
1156
|
-
*/
|
|
1157
1491
|
async #readConfigFileView(source) {
|
|
1158
|
-
if (!this.#
|
|
1492
|
+
if (!this.#permissions.allowConfigEdit) return void 0;
|
|
1159
1493
|
try {
|
|
1160
|
-
const { readConfig } = await import("./configFile-zhp5DQIe.js");
|
|
1161
1494
|
return readConfig(source ?? await read(this.#options.configFile));
|
|
1162
1495
|
} catch (error) {
|
|
1163
|
-
await this.#warn(`Could not read ${this.#options.configFile}: ${getErrorMessage(error)}`);
|
|
1496
|
+
await this.#warn({ message: `Could not read ${this.#options.configFile}: ${getErrorMessage(error)}` });
|
|
1164
1497
|
return;
|
|
1165
1498
|
}
|
|
1166
1499
|
}
|
|
1167
|
-
async connect() {
|
|
1168
|
-
|
|
1500
|
+
async connect(info) {
|
|
1501
|
+
this.#session.info = info;
|
|
1502
|
+
const { configPath, root, version: version$1, loadConfig } = this.#options;
|
|
1169
1503
|
const [config, file] = await Promise.all([loadConfig(), this.#readConfigFileView()]);
|
|
1170
|
-
|
|
1504
|
+
this.#session.connected.resolve(info);
|
|
1505
|
+
return {
|
|
1171
1506
|
versions: {
|
|
1172
1507
|
kubb: version,
|
|
1173
1508
|
agent: version$1
|
|
@@ -1181,197 +1516,131 @@ var StudioSession = class {
|
|
|
1181
1516
|
options: plugin.options ?? {}
|
|
1182
1517
|
}))
|
|
1183
1518
|
},
|
|
1184
|
-
permissions:
|
|
1185
|
-
...permissions,
|
|
1186
|
-
allowWrite: this.#canWrite,
|
|
1187
|
-
allowConfigEdit: this.#canEditConfig,
|
|
1188
|
-
allowRead: this.#canRead
|
|
1189
|
-
}
|
|
1519
|
+
permissions: this.#permissions
|
|
1190
1520
|
};
|
|
1191
|
-
this.#connectAck.resolve();
|
|
1192
|
-
return payload;
|
|
1193
|
-
}
|
|
1194
|
-
#onAbort = () => void this.#end({
|
|
1195
|
-
reason: "shutdown",
|
|
1196
|
-
retry: false
|
|
1197
|
-
}).catch(() => {});
|
|
1198
|
-
#onClose = (close) => void this.#end(planEnd(close)).catch(() => {});
|
|
1199
|
-
/** Closes this attempt and waits for its generation to stop before another can start. */
|
|
1200
|
-
dispose() {
|
|
1201
|
-
return this.#end({
|
|
1202
|
-
reason: "shutdown",
|
|
1203
|
-
retry: false
|
|
1204
|
-
});
|
|
1205
|
-
}
|
|
1206
|
-
async #end(plan) {
|
|
1207
|
-
if (this.#disposed) {
|
|
1208
|
-
await this.closed;
|
|
1209
|
-
return;
|
|
1210
|
-
}
|
|
1211
|
-
this.#disposed = true;
|
|
1212
|
-
clearTimeout(this.#heartbeatTimer);
|
|
1213
|
-
this.#rpc?.close();
|
|
1214
|
-
this.#rpc = void 0;
|
|
1215
|
-
this.#connectAck.reject(/* @__PURE__ */ new Error("Session ended before Studio called connect()"));
|
|
1216
|
-
for (const unhook of this.#unhooks) unhook();
|
|
1217
|
-
this.#unhooks.length = 0;
|
|
1218
|
-
try {
|
|
1219
|
-
await this.#activeJob?.cancel();
|
|
1220
|
-
await this.#generationResult?.catch(() => {});
|
|
1221
|
-
await this.#hooks.callHook("studio:disconnected", { reason: plan.reason });
|
|
1222
|
-
if (plan.error) await this.#hooks.callHook("studio:error", { error: plan.error });
|
|
1223
|
-
} finally {
|
|
1224
|
-
this.#ended.resolve(plan);
|
|
1225
|
-
}
|
|
1226
1521
|
}
|
|
1227
|
-
startGeneration(
|
|
1228
|
-
const
|
|
1522
|
+
startGeneration(input) {
|
|
1523
|
+
const stream = createGenerationStream(this.#options.hooks, input.jobId);
|
|
1229
1524
|
const controller = new AbortController();
|
|
1230
|
-
const
|
|
1231
|
-
|
|
1232
|
-
};
|
|
1233
|
-
const result = this.#runGeneration(data, controller, cancelRun).then(async (value) => {
|
|
1234
|
-
await generationStream.close();
|
|
1235
|
-
return value;
|
|
1236
|
-
}).catch((error) => {
|
|
1237
|
-
generationStream.fail(error);
|
|
1525
|
+
const result = this.#runGeneration(input, controller).then((value) => stream.close().then(() => value), (error) => {
|
|
1526
|
+
stream.fail(error);
|
|
1238
1527
|
throw error;
|
|
1239
|
-
}).finally(() => {
|
|
1240
|
-
if (this.#activeJob?.cancel === cancelRun) this.#activeJob = void 0;
|
|
1241
1528
|
});
|
|
1242
|
-
if (this.#activeJob?.cancel === cancelRun) this.#generationResult = result;
|
|
1243
1529
|
result.catch(() => {});
|
|
1244
|
-
return new GenerationRunTarget(
|
|
1245
|
-
|
|
1246
|
-
|
|
1530
|
+
return new GenerationRunTarget({
|
|
1531
|
+
stream: stream.stream,
|
|
1532
|
+
result,
|
|
1533
|
+
stop: () => {
|
|
1534
|
+
controller.abort(/* @__PURE__ */ new Error("Generation canceled"));
|
|
1535
|
+
stream.dispose();
|
|
1536
|
+
}
|
|
1247
1537
|
});
|
|
1248
1538
|
}
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
if (this.#isGenerating) return this.#refuse("Ignored generate: a generation is already in progress", "A generation is already in progress, please wait for it to finish");
|
|
1258
|
-
this.#isGenerating = true;
|
|
1259
|
-
this.#activeJob = {
|
|
1260
|
-
jobId: data.jobId,
|
|
1261
|
-
cancel: cancelRun
|
|
1539
|
+
async #runGeneration(input, controller) {
|
|
1540
|
+
if (this.#session.closed) throw new Error("Connection is closed");
|
|
1541
|
+
if (this.#session.active) return this.#refuse({ message: "A generation is already in progress, please wait for it to finish" });
|
|
1542
|
+
const settled = Promise.withResolvers();
|
|
1543
|
+
this.#session.active = {
|
|
1544
|
+
jobId: input.jobId,
|
|
1545
|
+
abort: () => controller.abort(/* @__PURE__ */ new Error("Generation canceled")),
|
|
1546
|
+
settled: settled.promise
|
|
1262
1547
|
};
|
|
1263
1548
|
let root = this.#options.root;
|
|
1264
1549
|
try {
|
|
1265
|
-
if (this.#
|
|
1550
|
+
if (this.#sandbox) root = await mkdtemp(path.join(tmpdir(), "kubb-job-"));
|
|
1266
1551
|
return await this.#command({
|
|
1267
1552
|
command: "generate",
|
|
1268
1553
|
run: () => this.#generate({
|
|
1269
|
-
|
|
1554
|
+
input,
|
|
1270
1555
|
root,
|
|
1271
1556
|
signal: controller.signal
|
|
1272
1557
|
})
|
|
1273
1558
|
});
|
|
1274
1559
|
} finally {
|
|
1275
|
-
if (root !== this.#options.root) await
|
|
1276
|
-
|
|
1560
|
+
if (root !== this.#options.root) await Promise.all([rm(root, {
|
|
1561
|
+
recursive: true,
|
|
1562
|
+
force: true
|
|
1563
|
+
}), rm(resolveCacheDir(root), {
|
|
1564
|
+
recursive: true,
|
|
1565
|
+
force: true
|
|
1566
|
+
})]).catch(() => {});
|
|
1567
|
+
this.#session.active = void 0;
|
|
1568
|
+
settled.resolve();
|
|
1277
1569
|
}
|
|
1278
1570
|
}
|
|
1279
|
-
async #generate({
|
|
1280
|
-
const {
|
|
1281
|
-
const config = await loadConfig();
|
|
1282
|
-
const
|
|
1283
|
-
const plugins = await mergePlugins(config.plugins, patch?.plugins);
|
|
1571
|
+
async #generate({ input, root, signal }) {
|
|
1572
|
+
const { jobId, config: patch } = input;
|
|
1573
|
+
const config = await this.#options.loadConfig();
|
|
1574
|
+
const plugins = await mergePlugins(config.plugins, patch?.plugins) ?? config.plugins;
|
|
1284
1575
|
const adapter = await mergeAdapter(config.adapter, patch?.adapter);
|
|
1285
|
-
const
|
|
1286
|
-
if (
|
|
1287
|
-
|
|
1288
|
-
const resolvedPlugins = plugins ?? config.plugins;
|
|
1289
|
-
const storage = this.#canWrite ? fsStorage() : memoryStorage();
|
|
1290
|
-
const diskFiles = this.#hasProjectOnDisk ? await listDisk({
|
|
1576
|
+
const studioInput = this.#sandbox ? patch?.input ?? "" : void 0;
|
|
1577
|
+
if (patch?.input && !this.#sandbox) await this.#warn({ message: "Ignored the spec from Studio: generating from a Studio spec is only available to a sandbox agent" });
|
|
1578
|
+
const diskFiles = !this.#sandbox && this.#permissions.allowRead ? await listDisk({
|
|
1291
1579
|
root,
|
|
1292
1580
|
outputPath: config.output.path,
|
|
1293
1581
|
maxFiles: DISK_SNAPSHOT_MAX_FILES
|
|
1294
1582
|
}) : void 0;
|
|
1295
1583
|
const disk = diskFiles ? await this.#generations.keep({
|
|
1296
|
-
jobId
|
|
1584
|
+
jobId,
|
|
1297
1585
|
source: "disk",
|
|
1298
1586
|
files: diskFiles,
|
|
1299
1587
|
maxSetMb: this.#limits.maxSnapshotMb
|
|
1300
1588
|
}) : void 0;
|
|
1301
|
-
const
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
lint: false,
|
|
1310
|
-
postGenerate: []
|
|
1589
|
+
const files = await generate({
|
|
1590
|
+
config: {
|
|
1591
|
+
...config,
|
|
1592
|
+
root,
|
|
1593
|
+
input: studioInput ?? config.input,
|
|
1594
|
+
storage: this.#permissions.allowWrite ? fsStorage() : memoryStorage(),
|
|
1595
|
+
plugins,
|
|
1596
|
+
adapter
|
|
1311
1597
|
},
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
}).generate().catch(async (error) => {
|
|
1318
|
-
await this.#generations.drop(data.jobId);
|
|
1598
|
+
hooks: this.#options.hooks,
|
|
1599
|
+
signal,
|
|
1600
|
+
allowExec: this.#permissions.allowExec
|
|
1601
|
+
}).catch(async (error) => {
|
|
1602
|
+
await this.#generations.drop(jobId);
|
|
1319
1603
|
throw error;
|
|
1320
1604
|
});
|
|
1321
|
-
if (!result.success) {
|
|
1322
|
-
await this.#generations.drop(data.jobId);
|
|
1323
|
-
throw generationFailure(result.diagnostics);
|
|
1324
|
-
}
|
|
1325
|
-
const paths = new Set(result.files.map((file) => relativeStoragePath({
|
|
1326
|
-
root,
|
|
1327
|
-
filePath: file.path
|
|
1328
|
-
})));
|
|
1329
1605
|
const output = await this.#generations.keep({
|
|
1330
|
-
jobId
|
|
1606
|
+
jobId,
|
|
1331
1607
|
source: "output",
|
|
1332
|
-
files
|
|
1333
|
-
storage,
|
|
1334
|
-
root,
|
|
1335
|
-
paths
|
|
1336
|
-
},
|
|
1608
|
+
files,
|
|
1337
1609
|
maxSetMb: this.#limits.maxMb
|
|
1338
1610
|
});
|
|
1339
|
-
if (!output.paths.length && Object.keys(output.hashes).length) await this.#warn("Kept only the hashes of this generation: its output is too large to keep");
|
|
1340
|
-
const { peerDependencies, missingDependencies } = await resolvePeerDependencies(resolvedPlugins.map(({ name }) => name));
|
|
1611
|
+
if (!output.paths.length && Object.keys(output.hashes).length) await this.#warn({ message: "Kept only the hashes of this generation: its output is too large to keep" });
|
|
1341
1612
|
await this.#generations.add({
|
|
1342
|
-
jobId
|
|
1613
|
+
jobId,
|
|
1343
1614
|
output,
|
|
1344
|
-
disk
|
|
1345
|
-
peerDependencies,
|
|
1346
|
-
missingDependencies
|
|
1615
|
+
disk
|
|
1347
1616
|
});
|
|
1348
1617
|
return {
|
|
1349
1618
|
value: {
|
|
1350
1619
|
status: "success",
|
|
1351
|
-
files: [...paths],
|
|
1352
|
-
fileCount: paths.size,
|
|
1620
|
+
files: [...files.paths],
|
|
1621
|
+
fileCount: files.paths.size,
|
|
1353
1622
|
hashes: output.hashes,
|
|
1354
1623
|
disk: disk ? { hashes: disk.hashes } : void 0
|
|
1355
1624
|
},
|
|
1356
|
-
info: `${
|
|
1625
|
+
info: `${plugins.length} plugin${plugins.length === 1 ? "" : "s"}, ${this.#permissions.allowWrite ? "written to disk" : "in memory"}${studioInput !== void 0 ? ", from a Studio spec" : ""}`
|
|
1357
1626
|
};
|
|
1358
1627
|
}
|
|
1359
|
-
saveConfig(
|
|
1628
|
+
saveConfig(input) {
|
|
1360
1629
|
return this.#command({
|
|
1361
1630
|
command: "saveConfig",
|
|
1362
|
-
run: () => this.#saveConfig(
|
|
1631
|
+
run: () => this.#saveConfig(input)
|
|
1363
1632
|
});
|
|
1364
1633
|
}
|
|
1365
|
-
async #saveConfig(
|
|
1634
|
+
async #saveConfig(input) {
|
|
1366
1635
|
const { configPath, configFile } = this.#options;
|
|
1367
|
-
if (!Array.isArray(
|
|
1368
|
-
await this.#warn("Ignored save: the message carried no edits");
|
|
1636
|
+
if (!Array.isArray(input.edits)) {
|
|
1637
|
+
await this.#warn({ message: "Ignored save: the message carried no edits" });
|
|
1369
1638
|
return { value: {
|
|
1370
1639
|
outcomes: [],
|
|
1371
1640
|
changed: false
|
|
1372
1641
|
} };
|
|
1373
1642
|
}
|
|
1374
|
-
const edits =
|
|
1643
|
+
const edits = input.edits;
|
|
1375
1644
|
const refuse = (reason) => ({
|
|
1376
1645
|
outcomes: edits.map((edit) => ({
|
|
1377
1646
|
edit,
|
|
@@ -1380,14 +1649,13 @@ var StudioSession = class {
|
|
|
1380
1649
|
})),
|
|
1381
1650
|
changed: false
|
|
1382
1651
|
});
|
|
1383
|
-
if (!this.#
|
|
1384
|
-
await this.#warn("Ignored save: editing kubb.config.ts was not granted");
|
|
1652
|
+
if (!this.#permissions.allowConfigEdit) {
|
|
1653
|
+
await this.#warn({ message: "Ignored save: editing kubb.config.ts was not granted" });
|
|
1385
1654
|
return { value: refuse("the agent was not granted permission to edit kubb.config.ts") };
|
|
1386
1655
|
}
|
|
1387
|
-
if (this.#
|
|
1656
|
+
if (this.#session.active) return { value: refuse("a generation is in progress") };
|
|
1388
1657
|
try {
|
|
1389
|
-
const {
|
|
1390
|
-
const { source: patched, outcomes, changed } = await writeConfigEdits({
|
|
1658
|
+
const { source, outcomes, changed } = await writeConfigEdits({
|
|
1391
1659
|
filePath: configFile,
|
|
1392
1660
|
edits
|
|
1393
1661
|
});
|
|
@@ -1396,89 +1664,40 @@ var StudioSession = class {
|
|
|
1396
1664
|
value: {
|
|
1397
1665
|
outcomes,
|
|
1398
1666
|
changed,
|
|
1399
|
-
file: changed ? await this.#readConfigFileView(
|
|
1667
|
+
file: changed ? await this.#readConfigFileView(source) : void 0
|
|
1400
1668
|
},
|
|
1401
1669
|
info: `applied ${applied}/${outcomes.length} edits to ${configPath}`
|
|
1402
1670
|
};
|
|
1403
1671
|
} catch (error) {
|
|
1404
|
-
await this.#hooks
|
|
1672
|
+
await emit(this.#options.hooks, "studio:error", { error: toError(error) });
|
|
1405
1673
|
return { value: refuse(getErrorMessage(error)) };
|
|
1406
1674
|
}
|
|
1407
1675
|
}
|
|
1408
|
-
|
|
1409
|
-
return this.#command({
|
|
1410
|
-
command: "snapshot",
|
|
1411
|
-
run: () => this.#publishSnapshot(data)
|
|
1412
|
-
});
|
|
1413
|
-
}
|
|
1414
|
-
async #publishSnapshot(data) {
|
|
1415
|
-
if (this.#isSandbox) return this.#refuse("Ignored snapshot: a sandbox agent has no project to build a package from", "A sandbox agent has no project to build a package from");
|
|
1416
|
-
const { name, version, bundledDependencies, uploadPath } = data;
|
|
1417
|
-
if (!name || !version || !uploadPath) return this.#refuse("Ignored snapshot: the message was missing required fields", "The request was missing required fields");
|
|
1418
|
-
const generation = await this.#generations.latest();
|
|
1419
|
-
if (!generation) return this.#refuse("Ignored snapshot: no prior generation to pack", "No prior generation exists to pack, run a generation first");
|
|
1420
|
-
const bundled = new Set(bundledDependencies ?? []);
|
|
1421
|
-
const missing = generation.missingDependencies.filter((dependency) => !bundled.has(dependency));
|
|
1422
|
-
if (missing.length) return this.#refuse(`Ignored snapshot: missing dependencies: ${missing.join(", ")}`, `Missing dependencies: ${missing.join(", ")}`);
|
|
1423
|
-
try {
|
|
1424
|
-
const { createSnapshotPackage, uploadSnapshot } = await import("./snapshotPackage-BwZ8IJX-.js");
|
|
1425
|
-
const { files } = await this.#generations.read({
|
|
1426
|
-
generation,
|
|
1427
|
-
source: "output",
|
|
1428
|
-
paths: generation.output.paths
|
|
1429
|
-
});
|
|
1430
|
-
const { bytes, integrity } = await createSnapshotPackage(files, {
|
|
1431
|
-
name,
|
|
1432
|
-
version,
|
|
1433
|
-
peerDependencies: generation.peerDependencies
|
|
1434
|
-
});
|
|
1435
|
-
const { token, studioUrl, signal } = this.#options;
|
|
1436
|
-
await uploadSnapshot({
|
|
1437
|
-
bytes,
|
|
1438
|
-
uploadPath,
|
|
1439
|
-
studioUrl,
|
|
1440
|
-
token,
|
|
1441
|
-
shutdown: signal
|
|
1442
|
-
});
|
|
1443
|
-
return {
|
|
1444
|
-
value: {
|
|
1445
|
-
integrity,
|
|
1446
|
-
peerDependencies: generation.peerDependencies
|
|
1447
|
-
},
|
|
1448
|
-
info: `packed ${Object.keys(files).length} file${Object.keys(files).length === 1 ? "" : "s"}`
|
|
1449
|
-
};
|
|
1450
|
-
} catch (error) {
|
|
1451
|
-
await this.#hooks.callHook("studio:error", { error: toError(error) });
|
|
1452
|
-
throw error;
|
|
1453
|
-
}
|
|
1454
|
-
}
|
|
1455
|
-
/** A sandbox has no project directory to snapshot. */
|
|
1456
|
-
get #hasProjectOnDisk() {
|
|
1457
|
-
return !this.#isSandbox && this.#canRead;
|
|
1458
|
-
}
|
|
1459
|
-
readFiles(data) {
|
|
1676
|
+
readFiles(input) {
|
|
1460
1677
|
return this.#command({
|
|
1461
1678
|
command: "readFiles",
|
|
1462
|
-
run: () => this.#readFiles(
|
|
1679
|
+
run: () => this.#readFiles(input)
|
|
1463
1680
|
});
|
|
1464
1681
|
}
|
|
1465
|
-
async #readFiles(
|
|
1466
|
-
if (!this.#
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
if (typeof
|
|
1471
|
-
const
|
|
1472
|
-
if (
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
if (!
|
|
1682
|
+
async #readFiles(input) {
|
|
1683
|
+
if (!this.#permissions.allowRead) return this.#refuse({
|
|
1684
|
+
message: "The agent was not granted permission to read generated files",
|
|
1685
|
+
permission: "allowRead"
|
|
1686
|
+
});
|
|
1687
|
+
if (!Array.isArray(input.paths) || typeof input.jobId !== "string" || !input.jobId) return this.#refuse({ message: "The request must name a job and carry paths" });
|
|
1688
|
+
const { paths } = input;
|
|
1689
|
+
if (paths.length > 50) return this.#refuse({ message: `At most 50 paths may be requested at once` });
|
|
1690
|
+
const generation = await this.#generations.get(input.jobId);
|
|
1691
|
+
if (!generation) return this.#refuse({ message: GENERATION_GONE_MESSAGE });
|
|
1692
|
+
if (!isValidPage(input)) return this.#refuse({ message: `The cursor must be a whole line from 0 and come with a limit of 1 to ${MAX_PAGE_LINES} lines` });
|
|
1693
|
+
const source = input.source === "disk" ? "disk" : "output";
|
|
1694
|
+
if (!generation[source]) return this.#refuse({ message: "This agent kept no snapshot of the files on disk for that job" });
|
|
1476
1695
|
const result = await this.#generations.read({
|
|
1477
1696
|
generation,
|
|
1478
1697
|
source,
|
|
1479
1698
|
paths,
|
|
1480
|
-
cursor:
|
|
1481
|
-
limit:
|
|
1699
|
+
cursor: input.cursor,
|
|
1700
|
+
limit: input.limit
|
|
1482
1701
|
});
|
|
1483
1702
|
return {
|
|
1484
1703
|
value: result,
|
|
@@ -1486,96 +1705,159 @@ var StudioSession = class {
|
|
|
1486
1705
|
};
|
|
1487
1706
|
}
|
|
1488
1707
|
};
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
const
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1708
|
+
const openWebSocketRpc = ({ url, token, instanceId, agent }) => {
|
|
1709
|
+
const socket = new WebSocket(url, { headers: {
|
|
1710
|
+
Authorization: `Bearer ${token}`,
|
|
1711
|
+
[AGENT_INSTANCE_HEADER]: instanceId
|
|
1712
|
+
} });
|
|
1713
|
+
const timer = setTimeout(() => socket.close(3008, "Connection timeout"), OPEN_TIMEOUT_MS);
|
|
1714
|
+
socket.addEventListener("open", () => clearTimeout(timer), { once: true });
|
|
1715
|
+
const closed = new Promise((resolve) => {
|
|
1716
|
+
socket.addEventListener("close", ({ code, reason }) => resolve({
|
|
1717
|
+
code,
|
|
1718
|
+
reason
|
|
1719
|
+
}), { once: true });
|
|
1720
|
+
socket.addEventListener("error", () => {
|
|
1721
|
+
if (socket.readyState !== WebSocket.OPEN) resolve({
|
|
1722
|
+
code: 1006,
|
|
1723
|
+
reason: ""
|
|
1724
|
+
});
|
|
1505
1725
|
});
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
await session.dispose();
|
|
1516
|
-
const end = await session.closed;
|
|
1517
|
-
if (!end.retry && end.reason !== "shutdown") return "stopped";
|
|
1518
|
-
if (error instanceof InvalidAgentTokenError) {
|
|
1519
|
-
const next = await onTokenRejected({
|
|
1520
|
-
error,
|
|
1521
|
-
credentials: current,
|
|
1522
|
-
live
|
|
1523
|
-
});
|
|
1524
|
-
if (!next) return "stopped";
|
|
1525
|
-
current = next;
|
|
1526
|
-
options = clientOptions(current);
|
|
1527
|
-
live = false;
|
|
1528
|
-
attempt = 0;
|
|
1529
|
-
continue;
|
|
1530
|
-
}
|
|
1531
|
-
} finally {
|
|
1532
|
-
await session.dispose();
|
|
1533
|
-
}
|
|
1534
|
-
onStarted?.();
|
|
1535
|
-
const cap = Math.min(1e3 * 2 ** Math.min(attempt++, 16), options.retryInterval ?? agentDefaults.retryIntervalMs);
|
|
1536
|
-
const delayMs = Math.random() * cap;
|
|
1537
|
-
await session.reportRetry(delayMs);
|
|
1538
|
-
try {
|
|
1539
|
-
await setTimeout$1(delayMs, void 0, { signal });
|
|
1540
|
-
} catch (error) {
|
|
1541
|
-
if (!signal?.aborted) throw error;
|
|
1726
|
+
}).finally(() => clearTimeout(timer));
|
|
1727
|
+
const studio = newWebSocketRpcSession(socket, agent);
|
|
1728
|
+
studio.onRpcBroken(() => socket.close());
|
|
1729
|
+
return {
|
|
1730
|
+
studio,
|
|
1731
|
+
closed,
|
|
1732
|
+
close: () => {
|
|
1733
|
+
studio[Symbol.dispose]();
|
|
1734
|
+
socket.close();
|
|
1542
1735
|
}
|
|
1543
|
-
}
|
|
1544
|
-
|
|
1545
|
-
}
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
const
|
|
1552
|
-
|
|
1553
|
-
|
|
1736
|
+
};
|
|
1737
|
+
};
|
|
1738
|
+
async function runSession({ options, openRpc, url, instanceId }) {
|
|
1739
|
+
const { hooks, signal, heartbeatInterval, token, studioUrl, version: version$2 } = options;
|
|
1740
|
+
const session = {
|
|
1741
|
+
connected: Promise.withResolvers(),
|
|
1742
|
+
closed: false
|
|
1743
|
+
};
|
|
1744
|
+
const rpc = openRpc({
|
|
1745
|
+
url,
|
|
1746
|
+
token,
|
|
1747
|
+
instanceId,
|
|
1748
|
+
agent: new Agent({
|
|
1749
|
+
options,
|
|
1750
|
+
session
|
|
1751
|
+
})
|
|
1752
|
+
});
|
|
1753
|
+
signal?.addEventListener("abort", rpc.close, { once: true });
|
|
1754
|
+
let timer;
|
|
1755
|
+
const heartbeat = async () => {
|
|
1756
|
+
let deadline;
|
|
1757
|
+
const timedOut = new Promise((resolve) => deadline = setTimeout(resolve, PING_TIMEOUT_MS, true));
|
|
1758
|
+
const failed = await Promise.race([Promise.resolve(rpc.studio.ping()).then(() => false, () => true), timedOut]);
|
|
1759
|
+
clearTimeout(deadline);
|
|
1760
|
+
if (failed) return rpc.close();
|
|
1761
|
+
if (!session.closed) timer = setTimeout(heartbeat, heartbeatInterval);
|
|
1762
|
+
};
|
|
1763
|
+
session.connected.promise.then(async (info) => {
|
|
1764
|
+
await emit(hooks, "studio:connected", {
|
|
1765
|
+
...info,
|
|
1766
|
+
url: studioUrl,
|
|
1767
|
+
versions: {
|
|
1768
|
+
studio: info.studioVersion,
|
|
1769
|
+
kubb: version,
|
|
1770
|
+
agent: version$2
|
|
1771
|
+
}
|
|
1772
|
+
});
|
|
1773
|
+
if (!session.closed) timer = setTimeout(heartbeat, heartbeatInterval);
|
|
1774
|
+
}, () => {});
|
|
1775
|
+
const close = await rpc.closed;
|
|
1776
|
+
session.closed = true;
|
|
1777
|
+
clearTimeout(timer);
|
|
1778
|
+
signal?.removeEventListener("abort", rpc.close);
|
|
1779
|
+
session.connected.reject(/* @__PURE__ */ new Error("The socket closed before Studio called connect()"));
|
|
1780
|
+
session.active?.abort();
|
|
1781
|
+
await session.active?.settled;
|
|
1554
1782
|
return {
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1783
|
+
...close,
|
|
1784
|
+
connected: session.info !== void 0
|
|
1785
|
+
};
|
|
1786
|
+
}
|
|
1787
|
+
/**
|
|
1788
|
+
* The connection loop with a swappable transport. {@link connectAgent} passes a real WebSocket.
|
|
1789
|
+
*/
|
|
1790
|
+
async function runAgent({ options, openRpc }) {
|
|
1791
|
+
const root = options.root ?? process$1.cwd();
|
|
1792
|
+
const resolved = {
|
|
1793
|
+
...options,
|
|
1794
|
+
studioUrl: options.studioUrl ?? "https://kubb.studio",
|
|
1795
|
+
root,
|
|
1796
|
+
configFile: path.resolve(root, options.configPath),
|
|
1797
|
+
permissions: {
|
|
1798
|
+
allowWrite: false,
|
|
1799
|
+
allowConfigEdit: false,
|
|
1800
|
+
allowExec: false,
|
|
1801
|
+
allowRead: false,
|
|
1802
|
+
...options.permissions
|
|
1571
1803
|
},
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1804
|
+
hooks: options.hooks ?? new Hookable(),
|
|
1805
|
+
maxRetryDelay: options.maxRetryDelay ?? MAX_RETRY_DELAY_MS,
|
|
1806
|
+
heartbeatInterval: Math.min(options.heartbeatInterval ?? HEARTBEAT_INTERVAL_MS, MAX_HEARTBEAT_INTERVAL_MS)
|
|
1575
1807
|
};
|
|
1808
|
+
const { studioUrl, hooks, signal, maxRetryDelay } = resolved;
|
|
1809
|
+
const url = secureUrl({
|
|
1810
|
+
studioUrl,
|
|
1811
|
+
path: AGENT_SOCKET_PATH,
|
|
1812
|
+
socket: true
|
|
1813
|
+
});
|
|
1814
|
+
const instanceId = randomUUID();
|
|
1815
|
+
let attempt = 0;
|
|
1816
|
+
while (!signal?.aborted) {
|
|
1817
|
+
const { code, reason, connected } = await runSession({
|
|
1818
|
+
options: resolved,
|
|
1819
|
+
openRpc,
|
|
1820
|
+
url,
|
|
1821
|
+
instanceId
|
|
1822
|
+
});
|
|
1823
|
+
if (signal?.aborted) return;
|
|
1824
|
+
await emit(hooks, "studio:disconnected", {
|
|
1825
|
+
code,
|
|
1826
|
+
reason
|
|
1827
|
+
});
|
|
1828
|
+
if (code === AgentCloseCode.UNAUTHORIZED) throw new InvalidAgentTokenError(studioUrl);
|
|
1829
|
+
if (code === AgentCloseCode.INCOMPATIBLE) throw new IncompatibleAgentError({
|
|
1830
|
+
studioUrl,
|
|
1831
|
+
detail: reason
|
|
1832
|
+
});
|
|
1833
|
+
if (code === AgentCloseCode.SUPERSEDED) return;
|
|
1834
|
+
if (connected) attempt = 0;
|
|
1835
|
+
const delayMs = Math.random() * Math.min(1e3 * 2 ** Math.min(attempt++, 16), maxRetryDelay);
|
|
1836
|
+
await emit(hooks, "studio:reconnecting", { delayMs });
|
|
1837
|
+
await setTimeout$1(delayMs, void 0, { signal }).catch(() => {});
|
|
1838
|
+
}
|
|
1839
|
+
}
|
|
1840
|
+
/**
|
|
1841
|
+
* Connects this project to Kubb Studio and serves its commands until `signal` aborts. Reconnects
|
|
1842
|
+
* with jittered backoff, and resolves when another process of the agent takes over. Rejects with
|
|
1843
|
+
* {@link InvalidAgentTokenError} so the host can pair again, or {@link IncompatibleAgentError}.
|
|
1844
|
+
*
|
|
1845
|
+
* @example
|
|
1846
|
+
* ```ts
|
|
1847
|
+
* const hooks = new Hookable<KubbHooks>()
|
|
1848
|
+
* hooks.hook('studio:connected', ({ agentSlug }) => console.log(`Connected as ${agentSlug}`))
|
|
1849
|
+
*
|
|
1850
|
+
* await connectAgent({ token, configPath: 'kubb.config.ts', loadConfig, version: '1.0.0', hooks, signal })
|
|
1851
|
+
* ```
|
|
1852
|
+
*/
|
|
1853
|
+
function connectAgent(options) {
|
|
1854
|
+
return runAgent({
|
|
1855
|
+
options,
|
|
1856
|
+
openRpc: openWebSocketRpc
|
|
1857
|
+
});
|
|
1576
1858
|
}
|
|
1577
1859
|
//#endregion
|
|
1578
|
-
//#region src/
|
|
1860
|
+
//#region src/pair.ts
|
|
1579
1861
|
/** Labels, not secrets: a person approving the code in the browser is what authorizes a pairing. */
|
|
1580
1862
|
const CLIENT_IDS = {
|
|
1581
1863
|
cli: "kubb-cli",
|
|
@@ -1607,30 +1889,33 @@ var PairingDeniedError = class extends Error {
|
|
|
1607
1889
|
}
|
|
1608
1890
|
};
|
|
1609
1891
|
/**
|
|
1610
|
-
* Asks Studio for a pairing code
|
|
1611
|
-
* the code, so approval knows which machine it is pairing: the same machine pairing twice rotates
|
|
1612
|
-
* one agent's token instead of creating a second agent.
|
|
1892
|
+
* Asks Studio for a pairing code, sending the hashed machine id with it.
|
|
1613
1893
|
*/
|
|
1614
|
-
async function startPairing({ studioUrl =
|
|
1894
|
+
async function startPairing({ studioUrl = defaultStudioUrl, type, name, hostname, machineId, signal }) {
|
|
1615
1895
|
try {
|
|
1616
|
-
|
|
1896
|
+
const pairing = await ofetch(secureUrl({
|
|
1897
|
+
studioUrl,
|
|
1898
|
+
path: "/api/auth/device/code"
|
|
1899
|
+
}).href, {
|
|
1617
1900
|
method: "POST",
|
|
1618
1901
|
body: {
|
|
1619
1902
|
client_id: type === "cli" ? CLIENT_IDS.cli : CLIENT_IDS.agent,
|
|
1620
1903
|
name,
|
|
1621
1904
|
hostname,
|
|
1622
|
-
machine_token:
|
|
1905
|
+
machine_token: hash("sha256", machineId),
|
|
1623
1906
|
agent_kind: type === "cli" ? void 0 : type
|
|
1624
1907
|
},
|
|
1625
1908
|
signal
|
|
1626
1909
|
});
|
|
1910
|
+
if (typeof pairing?.device_code !== "string") throw new Error("Kubb Studio returned no pairing code");
|
|
1911
|
+
return pairing;
|
|
1627
1912
|
} catch (error) {
|
|
1628
1913
|
if (signal?.aborted) throw new PairingCanceledError();
|
|
1629
1914
|
throw error;
|
|
1630
1915
|
}
|
|
1631
1916
|
}
|
|
1632
1917
|
function isPairingResult(response) {
|
|
1633
|
-
return
|
|
1918
|
+
return "token" in response && typeof response.token === "string";
|
|
1634
1919
|
}
|
|
1635
1920
|
/**
|
|
1636
1921
|
* Polls until the user approves or denies, honoring the server's `slow_down` back-off.
|
|
@@ -1642,7 +1927,7 @@ function isPairingResult(response) {
|
|
|
1642
1927
|
* @throws {PairingDeniedError} when the pairing is denied in the browser.
|
|
1643
1928
|
* @throws {PairingCanceledError} when `signal` aborts.
|
|
1644
1929
|
*/
|
|
1645
|
-
async function pollForPairingToken({ studioUrl =
|
|
1930
|
+
async function pollForPairingToken({ studioUrl = defaultStudioUrl, session, signal, onRetry }) {
|
|
1646
1931
|
const deadline = Date.now() + (session.expires_in > 0 ? session.expires_in : 600) * 1e3;
|
|
1647
1932
|
let intervalMs = (session.interval > 0 ? session.interval : 5) * 1e3;
|
|
1648
1933
|
while (Date.now() < deadline) {
|
|
@@ -1654,19 +1939,24 @@ async function pollForPairingToken({ studioUrl = agentDefaults.studioUrl, sessio
|
|
|
1654
1939
|
}
|
|
1655
1940
|
let response;
|
|
1656
1941
|
try {
|
|
1657
|
-
|
|
1942
|
+
const { status, _data } = await ofetch.raw(secureUrl({
|
|
1943
|
+
studioUrl,
|
|
1944
|
+
path: "/api/agent/token"
|
|
1945
|
+
}).href, {
|
|
1658
1946
|
method: "POST",
|
|
1659
1947
|
body: { device_code: session.device_code },
|
|
1660
|
-
|
|
1661
|
-
|
|
1948
|
+
signal,
|
|
1949
|
+
ignoreResponseError: true
|
|
1662
1950
|
});
|
|
1951
|
+
if (status >= 500 || !_data || typeof _data !== "object") throw new Error(`Kubb Studio answered with status ${status}`);
|
|
1952
|
+
response = _data;
|
|
1663
1953
|
} catch (error) {
|
|
1664
1954
|
if (signal?.aborted) throw new PairingCanceledError();
|
|
1665
1955
|
onRetry?.(toError(error));
|
|
1666
1956
|
continue;
|
|
1667
1957
|
}
|
|
1668
1958
|
if (isPairingResult(response)) return response;
|
|
1669
|
-
if (!
|
|
1959
|
+
if (!("error" in response) || typeof response.error !== "string") throw new Error("Kubb Studio returned an empty pairing response, pair again");
|
|
1670
1960
|
if (response.error === "authorization_pending") continue;
|
|
1671
1961
|
if (response.error === "slow_down") {
|
|
1672
1962
|
intervalMs += 5e3;
|
|
@@ -1698,6 +1988,196 @@ async function pairAgent({ onCode, onRetry, maxAttempts = 1, ...options }) {
|
|
|
1698
1988
|
}
|
|
1699
1989
|
}
|
|
1700
1990
|
//#endregion
|
|
1701
|
-
|
|
1991
|
+
//#region src/snapshot.ts
|
|
1992
|
+
const gzipAsync = promisify(gzip);
|
|
1993
|
+
const UPLOAD_TIMEOUT_MS = 12e4;
|
|
1994
|
+
const BUNDLED_DEPENDENCIES = ["@kubb/plugin-barrel"];
|
|
1995
|
+
/**
|
|
1996
|
+
* Maps a generated file to its path in the package, from its `src`/`dist` segment on, without `..` parts that could escape it.
|
|
1997
|
+
*/
|
|
1998
|
+
function packagePath(filePath) {
|
|
1999
|
+
const normalized = filePath.replaceAll("\\", "/");
|
|
2000
|
+
return (normalized.match(/\/(?:src|dist)\/.*$/)?.[0] ?? normalized).split("/").filter((part) => part && part !== "." && part !== "..").join("/");
|
|
2001
|
+
}
|
|
2002
|
+
/**
|
|
2003
|
+
* Splits a tar path into the 100-byte USTAR `name` and the 155-byte `prefix`, and throws for a path that fits neither.
|
|
2004
|
+
*/
|
|
2005
|
+
function splitEntryPath(path) {
|
|
2006
|
+
if (Buffer.byteLength(path) <= 100) return {
|
|
2007
|
+
name: path,
|
|
2008
|
+
prefix: ""
|
|
2009
|
+
};
|
|
2010
|
+
for (let i = path.lastIndexOf("/"); i > 0; i = path.lastIndexOf("/", i - 1)) {
|
|
2011
|
+
const prefix = path.slice(0, i);
|
|
2012
|
+
const name = path.slice(i + 1);
|
|
2013
|
+
if (Buffer.byteLength(prefix) <= 155 && Buffer.byteLength(name) <= 100) return {
|
|
2014
|
+
name,
|
|
2015
|
+
prefix
|
|
2016
|
+
};
|
|
2017
|
+
}
|
|
2018
|
+
throw new Error(`Snapshot path is too long for a tar entry: ${path}`);
|
|
2019
|
+
}
|
|
2020
|
+
function header(path, size) {
|
|
2021
|
+
const { name, prefix } = splitEntryPath(path);
|
|
2022
|
+
const value = Buffer.alloc(512);
|
|
2023
|
+
value.write(name);
|
|
2024
|
+
value.write("0000644\0", 100);
|
|
2025
|
+
for (const offset of [
|
|
2026
|
+
108,
|
|
2027
|
+
116,
|
|
2028
|
+
265,
|
|
2029
|
+
297
|
|
2030
|
+
]) value.write("0000000\0", offset);
|
|
2031
|
+
value.write(`${size.toString(8).padStart(11, "0")}\0`, 124);
|
|
2032
|
+
value.write("03560116604\0", 136);
|
|
2033
|
+
value.fill(32, 148, 156);
|
|
2034
|
+
value.write("0", 156);
|
|
2035
|
+
value.write("ustar\0", 257);
|
|
2036
|
+
value.write("00", 263);
|
|
2037
|
+
value.write(prefix, 345);
|
|
2038
|
+
const checksum = value.reduce((sum, byte) => sum + byte, 0);
|
|
2039
|
+
value.write(`${checksum.toString(8).padStart(6, "0")}\0 `, 148);
|
|
2040
|
+
return value;
|
|
2041
|
+
}
|
|
2042
|
+
/**
|
|
2043
|
+
* Packs a generation's files into a gzipped, npm-installable tarball: a `package/` root with the
|
|
2044
|
+
* generated sources, a `tsdown`-built `dist/` (esm + cjs), and a `package.json` manifest.
|
|
2045
|
+
*/
|
|
2046
|
+
async function createSnapshotPackage({ files, packageInfo }) {
|
|
2047
|
+
const sources = /* @__PURE__ */ new Map();
|
|
2048
|
+
for (const [name, content] of Object.entries(files)) {
|
|
2049
|
+
const path = packagePath(name);
|
|
2050
|
+
const owner = sources.get(path)?.name;
|
|
2051
|
+
if (owner) throw new Error(`Snapshot has two generated files that sanitize to the same path "package/${path}": "${owner}" and "${name}"`);
|
|
2052
|
+
sources.set(path, {
|
|
2053
|
+
name,
|
|
2054
|
+
content
|
|
2055
|
+
});
|
|
2056
|
+
}
|
|
2057
|
+
const root = await mkdtemp(join(tmpdir(), "kubb-snapshot-"));
|
|
2058
|
+
const dist = join(root, "dist");
|
|
2059
|
+
try {
|
|
2060
|
+
await mkdir(dist);
|
|
2061
|
+
await Promise.all([...sources].map(async ([path, { content }]) => {
|
|
2062
|
+
await mkdir(dirname(join(root, path)), { recursive: true });
|
|
2063
|
+
await writeFile(join(root, path), content);
|
|
2064
|
+
}));
|
|
2065
|
+
const entry = [...sources.keys()].filter((path) => /\.(?:[cm]?[jt]sx?)$/.test(path)).map((path) => join(root, path));
|
|
2066
|
+
if (entry.length) {
|
|
2067
|
+
const { build } = await import("tsdown");
|
|
2068
|
+
await build({
|
|
2069
|
+
entry,
|
|
2070
|
+
outDir: dist,
|
|
2071
|
+
format: ["esm", "cjs"],
|
|
2072
|
+
dts: false,
|
|
2073
|
+
sourcemap: false,
|
|
2074
|
+
unbundle: true,
|
|
2075
|
+
report: false,
|
|
2076
|
+
logLevel: "silent",
|
|
2077
|
+
fixedExtension: true
|
|
2078
|
+
});
|
|
2079
|
+
}
|
|
2080
|
+
const built = await fsStorage().readKeys(dist);
|
|
2081
|
+
const hasBarrel = built.includes("index.mjs") && built.includes("index.cjs");
|
|
2082
|
+
const manifest = {
|
|
2083
|
+
...packageInfo,
|
|
2084
|
+
type: "module",
|
|
2085
|
+
...hasBarrel ? {
|
|
2086
|
+
main: "./dist/index.cjs",
|
|
2087
|
+
module: "./dist/index.mjs"
|
|
2088
|
+
} : {},
|
|
2089
|
+
exports: {
|
|
2090
|
+
...hasBarrel ? { ".": {
|
|
2091
|
+
import: "./dist/index.mjs",
|
|
2092
|
+
require: "./dist/index.cjs"
|
|
2093
|
+
} } : {},
|
|
2094
|
+
"./*": {
|
|
2095
|
+
import: "./dist/*.mjs",
|
|
2096
|
+
require: "./dist/*.cjs"
|
|
2097
|
+
}
|
|
2098
|
+
}
|
|
2099
|
+
};
|
|
2100
|
+
const chunks = [...new Map([
|
|
2101
|
+
["package.json", JSON.stringify(manifest, null, 2)],
|
|
2102
|
+
...[...sources].map(([path, { content }]) => [path, content]),
|
|
2103
|
+
...await Promise.all(built.map(async (key) => [`dist/${key}`, await readFile(join(dist, key), "utf8")]))
|
|
2104
|
+
])].flatMap(([path, content]) => {
|
|
2105
|
+
const bytes = Buffer.from(content);
|
|
2106
|
+
return [
|
|
2107
|
+
header(`package/${path}`, bytes.length),
|
|
2108
|
+
bytes,
|
|
2109
|
+
Buffer.alloc((512 - bytes.length % 512) % 512)
|
|
2110
|
+
];
|
|
2111
|
+
});
|
|
2112
|
+
return await gzipAsync(Buffer.concat([...chunks, Buffer.alloc(1024)]));
|
|
2113
|
+
} finally {
|
|
2114
|
+
await rm(root, {
|
|
2115
|
+
recursive: true,
|
|
2116
|
+
force: true
|
|
2117
|
+
});
|
|
2118
|
+
}
|
|
2119
|
+
}
|
|
2120
|
+
/**
|
|
2121
|
+
* Generates the project, packs it as an npm tarball, and publishes it to Studio in one `POST /api/snapshots` request.
|
|
2122
|
+
*
|
|
2123
|
+
* @example
|
|
2124
|
+
* ```ts
|
|
2125
|
+
* const { url } = await createSnapshot({ apiKey: process.env.KUBB_TOKEN!, config, id: 'gh:123:pr-4', name: 'acme/api#4', packageName: '@acme/api', version: '1.0.0' })
|
|
2126
|
+
* ```
|
|
2127
|
+
*/
|
|
2128
|
+
async function createSnapshot({ studioUrl = defaultStudioUrl, apiKey, config, hooks, signal, ...metadata }) {
|
|
2129
|
+
const url = secureUrl({
|
|
2130
|
+
studioUrl,
|
|
2131
|
+
path: "/api/snapshots"
|
|
2132
|
+
});
|
|
2133
|
+
const generated = await generate({
|
|
2134
|
+
config,
|
|
2135
|
+
hooks,
|
|
2136
|
+
signal,
|
|
2137
|
+
allowExec: true
|
|
2138
|
+
});
|
|
2139
|
+
const files = Object.fromEntries(await Promise.all([...generated.paths].map(async (path) => {
|
|
2140
|
+
const content = await generated.storage.readItem(resolve(generated.root, path));
|
|
2141
|
+
if (content === null) throw new Error(`The generation listed ${path} but did not keep its content`);
|
|
2142
|
+
return [path, content];
|
|
2143
|
+
})));
|
|
2144
|
+
const { peerDependencies, missingDependencies } = await resolvePeerDependencies(config.plugins.map(({ name }) => name));
|
|
2145
|
+
const missing = missingDependencies.filter((dependency) => !BUNDLED_DEPENDENCIES.includes(dependency));
|
|
2146
|
+
if (missing.length) throw new Error(`Missing dependencies: ${missing.join(", ")}`);
|
|
2147
|
+
const bytes = await createSnapshotPackage({
|
|
2148
|
+
files,
|
|
2149
|
+
packageInfo: {
|
|
2150
|
+
name: metadata.packageName,
|
|
2151
|
+
version: metadata.version,
|
|
2152
|
+
peerDependencies
|
|
2153
|
+
}
|
|
2154
|
+
});
|
|
2155
|
+
if (bytes.length > 52428800) throw new Error(`The snapshot is ${Math.ceil(bytes.length / 1024 / 1024)} MB, over the ${MAX_SNAPSHOT_BYTES / 1024 / 1024} MB limit`);
|
|
2156
|
+
const hashes = Object.fromEntries(Object.entries(files).map(([path, content]) => [path, hashOf(content)]));
|
|
2157
|
+
const body = new FormData();
|
|
2158
|
+
body.set("metadata", JSON.stringify({
|
|
2159
|
+
...metadata,
|
|
2160
|
+
hashes,
|
|
2161
|
+
peerDependencies
|
|
2162
|
+
}));
|
|
2163
|
+
body.set("tarball", new Blob([new Uint8Array(bytes)], { type: "application/gzip" }), "snapshot.tgz");
|
|
2164
|
+
const timeout = AbortSignal.timeout(UPLOAD_TIMEOUT_MS);
|
|
2165
|
+
const { ok, status, _data } = await ofetch.raw(url.href, {
|
|
2166
|
+
method: "POST",
|
|
2167
|
+
headers: { "x-api-key": apiKey },
|
|
2168
|
+
body,
|
|
2169
|
+
redirect: "error",
|
|
2170
|
+
signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
|
|
2171
|
+
ignoreResponseError: true
|
|
2172
|
+
});
|
|
2173
|
+
if (!ok) {
|
|
2174
|
+
const upgrade = _data?.data?.upgradeUrl ? ` Upgrade at ${_data.data.upgradeUrl}.` : "";
|
|
2175
|
+
throw new Error(`Kubb Studio refused the snapshot (status ${status})${_data?.message ? `: ${_data.message}` : ""}.${upgrade}`);
|
|
2176
|
+
}
|
|
2177
|
+
if (!_data?.snapshot) throw new Error(`Kubb Studio returned no snapshot (status ${status})`);
|
|
2178
|
+
return _data.snapshot;
|
|
2179
|
+
}
|
|
2180
|
+
//#endregion
|
|
2181
|
+
export { IncompatibleAgentError, InvalidAgentTokenError, PairingCanceledError, PairingDeniedError, PairingExpiredError, connectAgent, createSnapshot, defaultStudioUrl, pairAgent };
|
|
1702
2182
|
|
|
1703
2183
|
//# sourceMappingURL=index.js.map
|