@sparkelf/dsh-artifact-app 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js ADDED
@@ -0,0 +1,2154 @@
1
+ import { readFile, readdir, stat } from "node:fs/promises";
2
+ import { basename, join, relative, resolve, sep } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { credentialRef } from "@deepseek-ai/dsh-credentials";
5
+ import { BUNDLED_SKILL_RANK } from "@deepseek-ai/dsh-skill";
6
+ import { randomUUID } from "node:crypto";
7
+ import { defineTool } from "@deepseek-ai/dsh-tools";
8
+ //#region src/api.ts
9
+ /** Server error carrying the DataOps status. */
10
+ var DataOpsError = class extends Error {
11
+ status;
12
+ constructor(message, status) {
13
+ super(message);
14
+ this.status = status;
15
+ this.name = "DataOpsError";
16
+ }
17
+ };
18
+ /** Client for the DataOps artifact endpoints. */
19
+ var ArtifactApi = class {
20
+ baseUrl;
21
+ tokens;
22
+ timeoutMs;
23
+ constructor(baseUrl, tokens, timeoutMs) {
24
+ this.baseUrl = baseUrl;
25
+ this.tokens = tokens;
26
+ this.timeoutMs = timeoutMs;
27
+ }
28
+ /** Read the workspace token or explain why the call cannot run. */
29
+ async token() {
30
+ const token = await this.tokens.resolve();
31
+ if (token === void 0 || token === "") throw new Error("未找到 DataOps 登录凭证(" + this.baseUrl + "):请先在本工作区完成 DataOps 登录");
32
+ return token;
33
+ }
34
+ async request(path, init = {}, auth = true) {
35
+ const headers = new Headers(init.headers);
36
+ headers.set("accept", "application/json");
37
+ if (init.body !== void 0) headers.set("content-type", "application/json");
38
+ if (auth) headers.set("authorization", "Bearer " + await this.token());
39
+ const response = await fetch(this.baseUrl.replace(/\/+$/u, "") + path, {
40
+ ...init,
41
+ headers,
42
+ signal: AbortSignal.timeout(this.timeoutMs)
43
+ });
44
+ const text = await response.text();
45
+ let payload = null;
46
+ if (text.trim() !== "") try {
47
+ payload = JSON.parse(text);
48
+ } catch {
49
+ payload = null;
50
+ }
51
+ if (response.status === 401) fetch("/integrations/dataops/auth-state", {
52
+ method: "POST",
53
+ headers: { "content-type": "application/json" },
54
+ body: JSON.stringify({ state: "expired" })
55
+ }).catch(() => void 0);
56
+ if (!response.ok) {
57
+ const record = payload !== null && typeof payload === "object" ? payload : {};
58
+ throw new DataOpsError(typeof record.message === "string" ? record.message : typeof record.error === "string" ? record.error : text.trim() !== "" ? text.trim().slice(0, 300) : "HTTP " + response.status, response.status);
59
+ }
60
+ return payload;
61
+ }
62
+ /** Read the current DataOps principal and roles. */
63
+ me() {
64
+ return this.request("/api/auth/me");
65
+ }
66
+ /** List published cockpit templates. */
67
+ listTemplates() {
68
+ return this.request("/api/artifact-templates?appType=COCKPIT");
69
+ }
70
+ /** Read one template's metadata and contract. */
71
+ getTemplate(id) {
72
+ return this.request("/api/artifact-templates/" + encodeURIComponent(id));
73
+ }
74
+ /** Read one template's HTML. */
75
+ getTemplateHtml(id) {
76
+ return this.request("/api/artifact-templates/" + encodeURIComponent(id) + "/html");
77
+ }
78
+ /** List visible cockpit apps. */
79
+ listApps(query = {}) {
80
+ const params = new URLSearchParams();
81
+ if (query.q) params.set("q", query.q);
82
+ if (query.catalog) params.set("catalog", query.catalog);
83
+ if (query.status) params.set("status", query.status);
84
+ if (query.page !== void 0) params.set("page", String(query.page));
85
+ if (query.pageSize !== void 0) params.set("pageSize", String(query.pageSize));
86
+ const suffix = params.toString();
87
+ return this.request("/api/artifact-apps" + (suffix ? "?" + suffix : ""));
88
+ }
89
+ /** Catalog counts for the tab's folder filter. */
90
+ catalogs() {
91
+ return this.request("/api/artifact-apps/catalogs");
92
+ }
93
+ /** Read one app's metadata. */
94
+ getApp(id) {
95
+ return this.request("/api/artifact-apps/" + encodeURIComponent(id));
96
+ }
97
+ /** Read one app's HTML (current for managers, published for viewers). */
98
+ getAppHtml(id, version) {
99
+ const suffix = version === void 0 ? "" : "?version=" + String(version);
100
+ return this.request("/api/artifact-apps/" + encodeURIComponent(id) + "/html" + suffix);
101
+ }
102
+ /** Patch metadata only. */
103
+ patchApp(id, patch) {
104
+ return this.request("/api/artifact-apps/" + encodeURIComponent(id), {
105
+ method: "PATCH",
106
+ body: JSON.stringify(patch)
107
+ });
108
+ }
109
+ /** Soft-delete one app. */
110
+ deleteApp(id) {
111
+ return this.request("/api/artifact-apps/" + encodeURIComponent(id), { method: "DELETE" });
112
+ }
113
+ /** Read one app's grants. */
114
+ getGrants(id) {
115
+ return this.request("/api/artifact-apps/" + encodeURIComponent(id) + "/grants");
116
+ }
117
+ /** Replace one app's grants. */
118
+ putGrants(id, grants) {
119
+ return this.request("/api/artifact-apps/" + encodeURIComponent(id) + "/grants", {
120
+ method: "PUT",
121
+ body: JSON.stringify({ grants })
122
+ });
123
+ }
124
+ /** Create or update a draft without publishing. */
125
+ preview(input) {
126
+ return this.request("/api/artifact-apps/preview", {
127
+ method: "POST",
128
+ body: JSON.stringify(input)
129
+ });
130
+ }
131
+ /** Publish a new app or a new version of an existing one. */
132
+ publish(input) {
133
+ return this.request("/api/artifact-apps/publish", {
134
+ method: "POST",
135
+ body: JSON.stringify(input)
136
+ });
137
+ }
138
+ /** Public runtime script served by DataOps. */
139
+ async runtimeScript() {
140
+ const response = await fetch(this.baseUrl.replace(/\/+$/u, "") + "/api/artifact-apps/runtime.js", { signal: AbortSignal.timeout(this.timeoutMs) });
141
+ if (!response.ok) throw new Error("运行时下载失败(HTTP " + String(response.status) + ")");
142
+ return await response.text();
143
+ }
144
+ /** Public ECharts bundle served by DataOps. */
145
+ async echartsScript() {
146
+ const response = await fetch(this.baseUrl.replace(/\/+$/u, "") + "/api/artifact-apps/echarts.js", { signal: AbortSignal.timeout(this.timeoutMs) });
147
+ if (!response.ok) throw new Error("ECharts 下载失败(HTTP " + String(response.status) + ")");
148
+ return await response.text();
149
+ }
150
+ /** Proxy one gateway call with the caller's own Authorization header. */
151
+ /**
152
+ * 批量解析素材逻辑名 → 可用 URL。
153
+ *
154
+ * 渲染时把 HTML 里的 `asset://<逻辑名>` 换成这里的地址;解析不到的名字保持原样,
155
+ * 由页面自己降级(不阻断渲染)。
156
+ * @param names - 逻辑名列表。
157
+ * @param scope - shared 或 template(默认 template,ownerId 为模板 id)。
158
+ * @param ownerId - 模板 id。
159
+ */
160
+ /**
161
+ * 发布模板包:把打包好的 zip 交给后端解压、校验、落素材并建模板版本。
162
+ * @param zipBase64 - zip 的 base64。
163
+ * @returns 模板 id 与版本。
164
+ */
165
+ async publishTemplatePackage(zipBase64) {
166
+ return this.request("/api/artifact-templates/package", {
167
+ method: "POST",
168
+ body: JSON.stringify({ zipBase64 })
169
+ });
170
+ }
171
+ async resolveAssets(names, scope, ownerId) {
172
+ if (names.length === 0) return {};
173
+ return (await this.request("/api/artifact-assets/resolve", {
174
+ method: "POST",
175
+ body: JSON.stringify({
176
+ names,
177
+ scope,
178
+ ...ownerId === void 0 ? {} : { ownerId }
179
+ })
180
+ })).urls ?? {};
181
+ }
182
+ async gateway(path, init, authorization) {
183
+ const headers = new Headers(init.headers);
184
+ headers.set("accept", "application/json");
185
+ if (init.body !== void 0) headers.set("content-type", "application/json");
186
+ if (authorization !== void 0) headers.set("authorization", authorization);
187
+ const response = await fetch(this.baseUrl.replace(/\/+$/u, "") + path, {
188
+ ...init,
189
+ headers,
190
+ signal: AbortSignal.timeout(this.timeoutMs)
191
+ });
192
+ return {
193
+ status: response.status,
194
+ body: await response.text(),
195
+ contentType: response.headers.get("content-type") ?? "application/json; charset=utf-8"
196
+ };
197
+ }
198
+ };
199
+ //#endregion
200
+ //#region ../../node_modules/.pnpm/@deepseek-ai+cosmokit@1.8.5/node_modules/@deepseek-ai/cosmokit/lib/index.js
201
+ /** Return true when a value is `null` or `undefined`. */
202
+ function isNullable(value) {
203
+ return value === null || value === void 0;
204
+ }
205
+ /** Return true for non-array object values. */
206
+ function isPlainObject(data) {
207
+ return data && typeof data === "object" && !Array.isArray(data);
208
+ }
209
+ /** Filter object entries and return a new object. */
210
+ function filterKeys(object, filter) {
211
+ return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));
212
+ }
213
+ /** Map object values while preserving the original key set. */
214
+ function mapValues(object, transform) {
215
+ return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
216
+ }
217
+ /** Pick selected keys from an object, optionally including `undefined` values. */
218
+ function pick(source, keys, forced) {
219
+ if (!keys) return { ...source };
220
+ const result = {};
221
+ for (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];
222
+ return result;
223
+ }
224
+ /** Shared config references used by schema validators and plugin runtimes. */
225
+ const write = Symbol.for("cosmokit.volatile.write");
226
+ function snapshot(value, ancestors = /* @__PURE__ */ new Set()) {
227
+ if (typeof value === "function") throw new TypeError("volatile config cannot contain functions");
228
+ if (value === null || typeof value !== "object") return value;
229
+ if (ancestors.has(value)) throw new TypeError("volatile config cannot contain cycles");
230
+ ancestors.add(value);
231
+ try {
232
+ if (Array.isArray(value)) return Object.freeze(value.map((item) => snapshot(item, ancestors)));
233
+ if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new TypeError("volatile config objects must be plain objects or arrays");
234
+ return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, snapshot(item, ancestors)])));
235
+ } finally {
236
+ ancestors.delete(value);
237
+ }
238
+ }
239
+ /**
240
+ * Create a detached reference containing an immutable copy of the supplied data.
241
+ * @param value - validated config data; class instances and functions are unsupported.
242
+ * @returns a reference whose value is updated only by its owning runtime.
243
+ */
244
+ function createVolatile(value) {
245
+ let current = snapshot(value);
246
+ return Object.freeze({
247
+ get: () => current,
248
+ [write]: (value) => {
249
+ current = value;
250
+ }
251
+ });
252
+ }
253
+ /**
254
+ * Identify references across ESM/CJS copies of the shared library.
255
+ * @param value - a parsed config value.
256
+ * @returns whether the value implements the shared reference protocol.
257
+ */
258
+ function isVolatile(value) {
259
+ return typeof value === "object" && value !== null && write in value;
260
+ }
261
+ /** Test values using `instanceof` with a `toStringTag` fallback. */
262
+ function is(type, value) {
263
+ if (arguments.length === 1) return (value) => is(type, value);
264
+ return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
265
+ }
266
+ function isArrayBufferLike(value) {
267
+ return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
268
+ }
269
+ function isArrayBufferSource(value) {
270
+ return isArrayBufferLike(value) || ArrayBuffer.isView(value);
271
+ }
272
+ /** Binary source detection and base64/hex conversion helpers. */
273
+ var Binary;
274
+ (function(Binary) {
275
+ Binary.is = isArrayBufferLike;
276
+ Binary.isSource = isArrayBufferSource;
277
+ function fromSource(source) {
278
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
279
+ else return source;
280
+ }
281
+ Binary.fromSource = fromSource;
282
+ function toBase64(source) {
283
+ source = fromSource(source);
284
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("base64");
285
+ let binary = "";
286
+ const bytes = new Uint8Array(source);
287
+ for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
288
+ return btoa(binary);
289
+ }
290
+ Binary.toBase64 = toBase64;
291
+ function fromBase64(source) {
292
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
293
+ return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
294
+ }
295
+ Binary.fromBase64 = fromBase64;
296
+ function toHex(source) {
297
+ source = fromSource(source);
298
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
299
+ return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
300
+ }
301
+ Binary.toHex = toHex;
302
+ function fromHex(source) {
303
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
304
+ const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
305
+ const buffer = [];
306
+ for (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
307
+ return Uint8Array.from(buffer).buffer;
308
+ }
309
+ Binary.fromHex = fromHex;
310
+ })(Binary || (Binary = {}));
311
+ Binary.fromBase64;
312
+ Binary.toBase64;
313
+ Binary.fromHex;
314
+ Binary.toHex;
315
+ /** Deep-clone common JavaScript values while preserving prototypes and cycles. */
316
+ function clone(source, refs = /* @__PURE__ */ new Map()) {
317
+ if (!source || typeof source !== "object") return source;
318
+ if (is("Date", source)) return new Date(source.valueOf());
319
+ if (is("RegExp", source)) return new RegExp(source.source, source.flags);
320
+ if (isArrayBufferLike(source)) return source.slice(0);
321
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
322
+ const cached = refs.get(source);
323
+ if (cached) return cached;
324
+ if (Array.isArray(source)) {
325
+ const result = [];
326
+ refs.set(source, result);
327
+ source.forEach((value, index) => {
328
+ result[index] = Reflect.apply(clone, null, [value, refs]);
329
+ });
330
+ return result;
331
+ }
332
+ const result = Object.create(Object.getPrototypeOf(source));
333
+ refs.set(source, result);
334
+ for (const key of Reflect.ownKeys(source)) {
335
+ const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };
336
+ if ("value" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);
337
+ Reflect.defineProperty(result, key, descriptor);
338
+ }
339
+ return result;
340
+ }
341
+ /**
342
+ * Compare values recursively, treating two volatile references as equal regardless of value.
343
+ * Strict comparison distinguishes null/undefined, treats opaque objects by identity,
344
+ * compares URLs by normalized href, treats array holes as undefined, and considers distinct cyclic structures unequal.
345
+ * @param a - first value.
346
+ * @param b - second value.
347
+ * @param strict - whether to require strict data equality outside volatile references.
348
+ * @returns whether the values compare equal.
349
+ */
350
+ function deepEqual(a, b, strict) {
351
+ const ancestors = /* @__PURE__ */ new Set();
352
+ function compare(a, b) {
353
+ if (a === b) return true;
354
+ if (isVolatile(a) || isVolatile(b)) return isVolatile(a) && isVolatile(b);
355
+ if (!strict && isNullable(a) && isNullable(b)) return true;
356
+ if (typeof a !== typeof b || typeof a !== "object" || !a || !b) return false;
357
+ if (ancestors.has(a)) return false;
358
+ function check(test, then) {
359
+ return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;
360
+ }
361
+ ancestors.add(a);
362
+ try {
363
+ return check(Array.isArray, (a, b) => {
364
+ if (a.length !== b.length) return false;
365
+ for (let index = 0; index < a.length; index++) if (!compare(a[index], b[index])) return false;
366
+ return true;
367
+ }) ?? check(is("Date"), (a, b) => a.valueOf() === b.valueOf()) ?? check(is("URL"), (a, b) => a.href === b.href) ?? check(is("RegExp"), (a, b) => a.source === b.source && a.flags === b.flags) ?? check(isArrayBufferLike, (a, b) => {
368
+ if (a.byteLength !== b.byteLength) return false;
369
+ const viewA = new Uint8Array(a);
370
+ const viewB = new Uint8Array(b);
371
+ for (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;
372
+ return true;
373
+ }) ?? ((!strict || [a, b].every((value) => Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) && Object.keys({
374
+ ...a,
375
+ ...b
376
+ }).every((key) => compare(a[key], b[key])));
377
+ } finally {
378
+ ancestors.delete(a);
379
+ }
380
+ }
381
+ return compare(a, b);
382
+ }
383
+ /** Time constants plus parsing and formatting helpers. */
384
+ var Time;
385
+ (function(Time) {
386
+ Time.millisecond = 1;
387
+ Time.second = 1e3;
388
+ Time.minute = Time.second * 60;
389
+ Time.hour = Time.minute * 60;
390
+ Time.day = Time.hour * 24;
391
+ Time.week = Time.day * 7;
392
+ let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
393
+ function setTimezoneOffset(offset) {
394
+ timezoneOffset = offset;
395
+ }
396
+ Time.setTimezoneOffset = setTimezoneOffset;
397
+ function getTimezoneOffset() {
398
+ return timezoneOffset;
399
+ }
400
+ Time.getTimezoneOffset = getTimezoneOffset;
401
+ function getDateNumber(date = /* @__PURE__ */ new Date(), offset) {
402
+ if (typeof date === "number") date = new Date(date);
403
+ if (offset === void 0) offset = timezoneOffset;
404
+ return Math.floor((date.valueOf() / Time.minute - offset) / 1440);
405
+ }
406
+ Time.getDateNumber = getDateNumber;
407
+ function fromDateNumber(value, offset) {
408
+ const date = new Date(value * Time.day);
409
+ if (offset === void 0) offset = timezoneOffset;
410
+ return new Date(+date + offset * Time.minute);
411
+ }
412
+ Time.fromDateNumber = fromDateNumber;
413
+ const numeric = /\d+(?:\.\d+)?/.source;
414
+ const timeRegExp = new RegExp(`^${[
415
+ "w(?:eek(?:s)?)?",
416
+ "d(?:ay(?:s)?)?",
417
+ "h(?:our(?:s)?)?",
418
+ "m(?:in(?:ute)?(?:s)?)?",
419
+ "s(?:ec(?:ond)?(?:s)?)?"
420
+ ].map((unit) => `(${numeric}${unit})?`).join("")}$`);
421
+ function parseTime(source) {
422
+ const capture = timeRegExp.exec(source);
423
+ if (!capture) return 0;
424
+ return (parseFloat(capture[1]) * Time.week || 0) + (parseFloat(capture[2]) * Time.day || 0) + (parseFloat(capture[3]) * Time.hour || 0) + (parseFloat(capture[4]) * Time.minute || 0) + (parseFloat(capture[5]) * Time.second || 0);
425
+ }
426
+ Time.parseTime = parseTime;
427
+ function parseDate(date) {
428
+ const parsed = parseTime(date);
429
+ if (parsed) date = Date.now() + parsed;
430
+ else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date}`;
431
+ else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date}`;
432
+ return date ? new Date(date) : /* @__PURE__ */ new Date();
433
+ }
434
+ Time.parseDate = parseDate;
435
+ function format(ms) {
436
+ const abs = Math.abs(ms);
437
+ if (abs >= Time.day - Time.hour / 2) return Math.round(ms / Time.day) + "d";
438
+ else if (abs >= Time.hour - Time.minute / 2) return Math.round(ms / Time.hour) + "h";
439
+ else if (abs >= Time.minute - Time.second / 2) return Math.round(ms / Time.minute) + "m";
440
+ else if (abs >= Time.second) return Math.round(ms / Time.second) + "s";
441
+ return ms + "ms";
442
+ }
443
+ Time.format = format;
444
+ function toDigits(source, length = 2) {
445
+ return source.toString().padStart(length, "0");
446
+ }
447
+ Time.toDigits = toDigits;
448
+ function template(template, time = /* @__PURE__ */ new Date()) {
449
+ return template.replace("yyyy", time.getFullYear().toString()).replace("yy", time.getFullYear().toString().slice(2)).replace("MM", toDigits(time.getMonth() + 1)).replace("dd", toDigits(time.getDate())).replace("hh", toDigits(time.getHours())).replace("mm", toDigits(time.getMinutes())).replace("ss", toDigits(time.getSeconds())).replace("SSS", toDigits(time.getMilliseconds(), 3));
450
+ }
451
+ Time.template = template;
452
+ })(Time || (Time = {}));
453
+ //#endregion
454
+ //#region ../../node_modules/.pnpm/@deepseek-ai+schemastery@3.18.4/node_modules/@deepseek-ai/schemastery/lib/index.mjs
455
+ const kSchema = Symbol.for("schemastery");
456
+ const kValidationError = Symbol.for("ValidationError");
457
+ globalThis.__schemastery_index__ ??= 0;
458
+ globalThis.__schemastery_refs__ = void 0;
459
+ var ValidationError = class extends TypeError {
460
+ options;
461
+ name = "ValidationError";
462
+ constructor(message, options) {
463
+ let prefix = "$";
464
+ for (const segment of options.path || []) if (typeof segment === "string") prefix += "." + segment;
465
+ else if (typeof segment === "number") prefix += "[" + segment + "]";
466
+ else if (typeof segment === "symbol") prefix += `[Symbol(${segment.toString()})]`;
467
+ if (prefix.startsWith(".")) prefix = prefix.slice(1);
468
+ super((prefix === "$" ? "" : `${prefix} `) + message);
469
+ this.options = options;
470
+ }
471
+ static is(error) {
472
+ return !!error?.[kValidationError];
473
+ }
474
+ };
475
+ Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
476
+ const Schema = function(options) {
477
+ const schema = function(data, options = {}) {
478
+ return Schema.resolve(data, schema, options)[0];
479
+ };
480
+ if (options.refs) {
481
+ const refs = mapValues(options.refs, (options) => new Schema(options));
482
+ const getRef = (uid) => refs[uid];
483
+ for (const key in refs) {
484
+ const options = refs[key];
485
+ options.sKey = getRef(options.sKey);
486
+ options.inner = getRef(options.inner);
487
+ options.list = options.list && options.list.map(getRef);
488
+ options.dict = options.dict && mapValues(options.dict, getRef);
489
+ }
490
+ return refs[options.uid];
491
+ }
492
+ Object.assign(schema, options);
493
+ if (typeof schema.callback === "string") try {
494
+ schema.callback = new Function("return " + schema.callback)();
495
+ } catch {}
496
+ Object.defineProperty(schema, "uid", { value: globalThis.__schemastery_index__++ });
497
+ Object.setPrototypeOf(schema, Schema.prototype);
498
+ schema.meta ||= {};
499
+ schema.toString = schema.toString.bind(schema);
500
+ return schema;
501
+ };
502
+ Schema.prototype = Object.create(Function.prototype);
503
+ Schema.prototype[kSchema] = true;
504
+ Object.defineProperty(Schema.prototype, "~standard", { get() {
505
+ return {
506
+ version: 1,
507
+ vendor: "schemastery",
508
+ validate: (value) => {
509
+ try {
510
+ return { value: Schema.resolve(value, this, {})[0] };
511
+ } catch (error) {
512
+ if (ValidationError.is(error)) return { issues: [{
513
+ message: error.message,
514
+ path: error.options.path
515
+ }] };
516
+ throw error;
517
+ }
518
+ }
519
+ };
520
+ } });
521
+ Schema.ValidationError = ValidationError;
522
+ Schema.prototype.toJSON = function toJSON() {
523
+ if (globalThis.__schemastery_refs__) {
524
+ globalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
525
+ return this.uid;
526
+ }
527
+ globalThis.__schemastery_refs__ = { [this.uid]: { ...this } };
528
+ globalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
529
+ const result = {
530
+ uid: this.uid,
531
+ refs: globalThis.__schemastery_refs__
532
+ };
533
+ globalThis.__schemastery_refs__ = void 0;
534
+ return result;
535
+ };
536
+ Schema.prototype.set = function set(key, value) {
537
+ this.dict[key] = value;
538
+ return this;
539
+ };
540
+ Schema.prototype.push = function push(value) {
541
+ this.list.push(value);
542
+ return this;
543
+ };
544
+ function mergeDesc(original, messages) {
545
+ const result = typeof original === "string" ? { "": original } : { ...original };
546
+ for (const locale in messages) {
547
+ const value = messages[locale];
548
+ if (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;
549
+ else if (typeof value === "string") result[locale] = value;
550
+ }
551
+ return result;
552
+ }
553
+ function getInner(value) {
554
+ return value?.$value ?? value?.$inner;
555
+ }
556
+ function extractKeys(data) {
557
+ return filterKeys(data ?? {}, (key) => !key.startsWith("$"));
558
+ }
559
+ Schema.prototype.i18n = function i18n(messages) {
560
+ const schema = Schema(this);
561
+ const desc = mergeDesc(schema.meta.description, messages);
562
+ if (Object.keys(desc).length) schema.meta.description = desc;
563
+ if (schema.dict) schema.dict = mapValues(schema.dict, (inner, key) => {
564
+ return inner.i18n(mapValues(messages, (data) => getInner(data)?.[key] ?? data?.[key]));
565
+ });
566
+ if (schema.list) schema.list = schema.list.map((inner, index) => {
567
+ return inner.i18n(mapValues(messages, (data = {}) => {
568
+ if (Array.isArray(getInner(data))) return getInner(data)[index];
569
+ if (Array.isArray(data)) return data[index];
570
+ return extractKeys(data);
571
+ }));
572
+ });
573
+ if (schema.inner) schema.inner = schema.inner.i18n(mapValues(messages, (data) => {
574
+ if (getInner(data)) return getInner(data);
575
+ return extractKeys(data);
576
+ }));
577
+ if (schema.sKey) schema.sKey = schema.sKey.i18n(mapValues(messages, (data) => data?.$key));
578
+ return schema;
579
+ };
580
+ Schema.prototype.extra = function extra(key, value) {
581
+ const schema = Schema(this);
582
+ schema.meta = {
583
+ ...schema.meta,
584
+ [key]: value
585
+ };
586
+ return schema;
587
+ };
588
+ for (const key of [
589
+ "required",
590
+ "disabled",
591
+ "collapse",
592
+ "hidden",
593
+ "loose"
594
+ ]) Object.assign(Schema.prototype, { [key](value = true) {
595
+ const schema = Schema(this);
596
+ schema.meta = {
597
+ ...schema.meta,
598
+ [key]: value
599
+ };
600
+ return schema;
601
+ } });
602
+ Schema.prototype.deprecated = function deprecated() {
603
+ const schema = Schema(this);
604
+ schema.meta.badges ||= [];
605
+ schema.meta.badges.push({
606
+ text: "deprecated",
607
+ type: "danger"
608
+ });
609
+ return schema;
610
+ };
611
+ Schema.prototype.experimental = function experimental() {
612
+ const schema = Schema(this);
613
+ schema.meta.badges ||= [];
614
+ schema.meta.badges.push({
615
+ text: "experimental",
616
+ type: "warning"
617
+ });
618
+ return schema;
619
+ };
620
+ Schema.prototype.pattern = function pattern(regexp) {
621
+ const schema = Schema(this);
622
+ const pattern = pick(regexp, ["source", "flags"]);
623
+ schema.meta = {
624
+ ...schema.meta,
625
+ pattern
626
+ };
627
+ return schema;
628
+ };
629
+ Schema.prototype.simplify = function simplify(value) {
630
+ if (isVolatile(value)) value = value.get();
631
+ if (deepEqual(value, this.meta.default, this.type === "dict")) return null;
632
+ if (isNullable(value)) return value;
633
+ if (this.type === "object" || this.type === "dict") {
634
+ const result = {};
635
+ for (const key in value) {
636
+ const item = (this.type === "object" ? this.dict[key] : this.inner)?.simplify(value[key]);
637
+ if (this.type === "dict" || !isNullable(item)) result[key] = item;
638
+ }
639
+ if (deepEqual(result, this.meta.default, this.type === "dict")) return null;
640
+ return result;
641
+ } else if (this.type === "array" || this.type === "tuple") {
642
+ const result = [];
643
+ value.forEach((value, index) => {
644
+ const schema = this.type === "array" ? this.inner : this.list[index];
645
+ const item = schema ? schema.simplify(value) : value;
646
+ result.push(item);
647
+ });
648
+ return result;
649
+ } else if (this.type === "intersect") {
650
+ const result = {};
651
+ for (const item of this.list) Object.assign(result, item.simplify(value));
652
+ return result;
653
+ } else if (this.type === "union") for (const schema of this.list) try {
654
+ Schema.resolve(value, schema, {});
655
+ return schema.simplify(value);
656
+ } catch {}
657
+ return value;
658
+ };
659
+ Schema.prototype.toString = function toString(inline) {
660
+ return formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;
661
+ };
662
+ Schema.prototype.role = function role(role, extra) {
663
+ const schema = Schema(this);
664
+ schema.meta = {
665
+ ...schema.meta,
666
+ role,
667
+ extra
668
+ };
669
+ return schema;
670
+ };
671
+ for (const key of [
672
+ "default",
673
+ "link",
674
+ "comment",
675
+ "description",
676
+ "max",
677
+ "min",
678
+ "step"
679
+ ]) Object.assign(Schema.prototype, { [key](value) {
680
+ const schema = Schema(this);
681
+ schema.meta = {
682
+ ...schema.meta,
683
+ [key]: value
684
+ };
685
+ return schema;
686
+ } });
687
+ Schema.prototype.volatile = function volatile() {
688
+ if (this.meta.volatile) throw new TypeError("volatile schema is already wrapped");
689
+ return this.extra("volatile", true);
690
+ };
691
+ const resolvers = {};
692
+ const checkedVolatile = Symbol("checked-volatile-schema");
693
+ function validateVolatileSchema(schema, path = [], blocked = false, seen = /* @__PURE__ */ new Map()) {
694
+ const states = seen.get(schema) ?? /* @__PURE__ */ new Set();
695
+ if (states.has(blocked)) return;
696
+ states.add(blocked);
697
+ seen.set(schema, states);
698
+ if (schema.meta?.volatile && blocked) throw new ValidationError("volatile fields require a fixed object path without an enclosing volatile field", { path });
699
+ const nested = blocked || !!schema.meta?.volatile;
700
+ if (schema.dict) for (const [key, child] of Object.entries(schema.dict)) validateVolatileSchema(child, [...path, key], nested, seen);
701
+ if (schema.sKey) validateVolatileSchema(schema.sKey, [...path, "<key>"], true, seen);
702
+ if (schema.inner && (schema.type !== "lazy" || schema.inner[kSchema])) validateVolatileSchema(schema.inner, [...path, "*"], true, seen);
703
+ if (schema.list) for (let index = 0; index < schema.list.length; index++) validateVolatileSchema(schema.list[index], [...path, String(index)], true, seen);
704
+ }
705
+ Schema.extend = function extend(type, resolve) {
706
+ resolvers[type] = resolve;
707
+ };
708
+ Schema.resolve = function resolve(data, schema, options = {}, strict = false) {
709
+ if (!schema) return [data];
710
+ if (!options[checkedVolatile]) {
711
+ validateVolatileSchema(schema, options.path);
712
+ options = {
713
+ ...options,
714
+ [checkedVolatile]: true
715
+ };
716
+ }
717
+ if (schema.meta?.volatile) {
718
+ const inner = Schema(schema);
719
+ inner.meta = {
720
+ ...schema.meta,
721
+ volatile: false
722
+ };
723
+ const [value, adapted] = Schema.resolve(data, inner, options, strict);
724
+ try {
725
+ return [createVolatile(value), adapted];
726
+ } catch (error) {
727
+ throw new ValidationError(error instanceof Error ? error.message : String(error), options);
728
+ }
729
+ }
730
+ if (options.ignore?.(data, schema)) return [data];
731
+ if (isNullable(data) && schema.type !== "lazy") {
732
+ if (schema.meta.required) throw new ValidationError(`missing required value`, options);
733
+ let current = schema;
734
+ let fallback = schema.meta.default;
735
+ while (current?.type === "intersect" && isNullable(fallback)) {
736
+ current = current.list[0];
737
+ fallback = current?.meta.default;
738
+ }
739
+ if (isNullable(fallback)) return [data];
740
+ data = clone(fallback);
741
+ }
742
+ const callback = resolvers[schema.type];
743
+ if (!callback) throw new ValidationError(`unsupported type "${schema.type}"`, options);
744
+ try {
745
+ return callback(data, schema, options, strict);
746
+ } catch (error) {
747
+ if (!schema.meta.loose) throw error;
748
+ return [schema.meta.default];
749
+ }
750
+ };
751
+ Schema.from = function from(source) {
752
+ if (isNullable(source)) return Schema.any();
753
+ else if ([
754
+ "string",
755
+ "number",
756
+ "boolean"
757
+ ].includes(typeof source)) return Schema.const(source).required();
758
+ else if (source[kSchema]) return source;
759
+ else if (typeof source === "function") switch (source) {
760
+ case String: return Schema.string().required();
761
+ case Number: return Schema.number().required();
762
+ case Boolean: return Schema.boolean().required();
763
+ case Function: return Schema.function().required();
764
+ default: return Schema.is(source).required();
765
+ }
766
+ else throw new TypeError(`cannot infer schema from ${source}`);
767
+ };
768
+ Schema.lazy = function lazy(builder) {
769
+ const toJSON = () => {
770
+ if (!schema.inner[kSchema]) {
771
+ schema.inner = schema.builder();
772
+ schema.inner.meta = {
773
+ ...schema.meta,
774
+ ...schema.inner.meta
775
+ };
776
+ }
777
+ return schema.inner.toJSON();
778
+ };
779
+ const schema = new Schema({
780
+ type: "lazy",
781
+ builder,
782
+ inner: { toJSON }
783
+ });
784
+ return schema;
785
+ };
786
+ Schema.natural = function natural() {
787
+ return Schema.number().step(1).min(0);
788
+ };
789
+ Schema.percent = function percent() {
790
+ return Schema.number().step(.01).min(0).max(1).role("slider");
791
+ };
792
+ Schema.date = function date() {
793
+ return Schema.union([Schema.is(Date), Schema.transform(Schema.string().role("datetime"), (value, options) => {
794
+ const date = new Date(value);
795
+ if (isNaN(+date)) throw new ValidationError(`invalid date "${value}"`, options);
796
+ return date;
797
+ }, true)]);
798
+ };
799
+ Schema.regExp = function regExp(flag = "") {
800
+ return Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role("regexp", { flag }), (value, options) => {
801
+ try {
802
+ return new RegExp(value, flag);
803
+ } catch (e) {
804
+ throw new ValidationError(e.message, options);
805
+ }
806
+ }, true)]);
807
+ };
808
+ Schema.arrayBuffer = function arrayBuffer(encoding) {
809
+ return Schema.union([
810
+ Schema.is(ArrayBuffer),
811
+ Schema.is(SharedArrayBuffer),
812
+ Schema.transform(Schema.any(), (value, options) => {
813
+ if (Binary.isSource(value)) return Binary.fromSource(value);
814
+ throw new ValidationError(`expected ArrayBufferSource but got ${value}`, options);
815
+ }, true),
816
+ ...encoding ? [Schema.transform(Schema.string(), (value, options) => {
817
+ try {
818
+ return encoding === "base64" ? Binary.fromBase64(value) : Binary.fromHex(value);
819
+ } catch (e) {
820
+ throw new ValidationError(e.message, options);
821
+ }
822
+ }, true)] : []
823
+ ]);
824
+ };
825
+ Schema.extend("lazy", (data, schema, options, strict) => {
826
+ if (!schema.inner[kSchema]) {
827
+ schema.inner = schema.builder();
828
+ schema.inner.meta = {
829
+ ...schema.meta,
830
+ ...schema.inner.meta
831
+ };
832
+ validateVolatileSchema(schema.inner, options.path, true);
833
+ }
834
+ return Schema.resolve(data, schema.inner, options, strict);
835
+ });
836
+ Schema.extend("any", (data) => {
837
+ return [data];
838
+ });
839
+ Schema.extend("never", (data, _, options) => {
840
+ throw new ValidationError(`expected nullable but got ${data}`, options);
841
+ });
842
+ Schema.extend("const", (data, { value }, options) => {
843
+ if (deepEqual(data, value)) return [value];
844
+ throw new ValidationError(`expected ${value} but got ${data}`, options);
845
+ });
846
+ function checkWithinRange(data, meta, description, options, skipMin = false) {
847
+ const { max = Infinity, min = -Infinity } = meta;
848
+ if (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);
849
+ if (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);
850
+ }
851
+ Schema.extend("string", (data, { meta }, options) => {
852
+ if (typeof data !== "string") throw new ValidationError(`expected string but got ${data}`, options);
853
+ if (meta.pattern) {
854
+ const regexp = new RegExp(meta.pattern.source, meta.pattern.flags);
855
+ if (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);
856
+ }
857
+ checkWithinRange(data.length, meta, "string length", options);
858
+ return [data];
859
+ });
860
+ function decimalShift(data, digits) {
861
+ const str = data.toString();
862
+ if (str.includes("e")) return data * Math.pow(10, digits);
863
+ const index = str.indexOf(".");
864
+ if (index === -1) return data * Math.pow(10, digits);
865
+ const frac = str.slice(index + 1);
866
+ const integer = str.slice(0, index);
867
+ if (frac.length <= digits) return +(integer + frac.padEnd(digits, "0"));
868
+ return +(integer + frac.slice(0, digits) + "." + frac.slice(digits));
869
+ }
870
+ function isMultipleOf(data, min, step) {
871
+ step = Math.abs(step);
872
+ if (!/^\d+\.\d+$/.test(step.toString())) return (data - min) % step === 0;
873
+ const index = step.toString().indexOf(".");
874
+ const digits = step.toString().slice(index + 1).length;
875
+ return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;
876
+ }
877
+ Schema.extend("number", (data, { meta }, options) => {
878
+ if (typeof data !== "number") throw new ValidationError(`expected number but got ${data}`, options);
879
+ checkWithinRange(data, meta, "number", options);
880
+ const { step } = meta;
881
+ if (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);
882
+ return [data];
883
+ });
884
+ Schema.extend("boolean", (data, _, options) => {
885
+ if (typeof data === "boolean") return [data];
886
+ throw new ValidationError(`expected boolean but got ${data}`, options);
887
+ });
888
+ Schema.extend("bitset", (data, { bits, meta }, options) => {
889
+ let value = 0, keys = [];
890
+ if (typeof data === "number") {
891
+ value = data;
892
+ for (const key in bits) if (data & bits[key]) keys.push(key);
893
+ } else if (Array.isArray(data)) {
894
+ keys = data;
895
+ for (const key of keys) {
896
+ if (typeof key !== "string") throw new ValidationError(`expected string but got ${key}`, options);
897
+ if (key in bits) value |= bits[key];
898
+ }
899
+ } else throw new ValidationError(`expected number or array but got ${data}`, options);
900
+ if (value === meta.default) return [value];
901
+ return [value, keys];
902
+ });
903
+ Schema.extend("function", (data, _, options) => {
904
+ if (typeof data === "function") return [data];
905
+ throw new ValidationError(`expected function but got ${data}`, options);
906
+ });
907
+ Schema.extend("is", (data, { constructor }, options) => {
908
+ if (typeof constructor === "function") {
909
+ if (data instanceof constructor) return [data];
910
+ throw new ValidationError(`expected ${constructor.name} but got ${data}`, options);
911
+ } else {
912
+ if (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);
913
+ let prototype = Object.getPrototypeOf(data);
914
+ while (prototype) {
915
+ if (prototype.constructor?.name === constructor) return [data];
916
+ prototype = Object.getPrototypeOf(prototype);
917
+ }
918
+ throw new ValidationError(`expected ${constructor} but got ${data}`, options);
919
+ }
920
+ });
921
+ function property(data, key, schema, options) {
922
+ try {
923
+ const [value, adapted] = Schema.resolve(data[key], schema, {
924
+ ...options,
925
+ path: [...options.path || [], key]
926
+ });
927
+ if (adapted !== void 0) data[key] = adapted;
928
+ return value;
929
+ } catch (e) {
930
+ if (!options?.autofix) throw e;
931
+ delete data[key];
932
+ return schema.meta.volatile ? createVolatile(schema.meta.default) : schema.meta.default;
933
+ }
934
+ }
935
+ Schema.extend("array", (data, { inner, meta }, options) => {
936
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
937
+ checkWithinRange(data.length, meta, "array length", options, !isNullable(inner.meta.default));
938
+ return [data.map((_, index) => property(data, index, inner, options))];
939
+ });
940
+ Schema.extend("dict", (data, { inner, sKey }, options, strict) => {
941
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
942
+ const result = {};
943
+ for (const key in data) {
944
+ let rKey;
945
+ try {
946
+ rKey = Schema.resolve(key, sKey, options)[0];
947
+ } catch (error) {
948
+ if (strict) continue;
949
+ throw error;
950
+ }
951
+ result[rKey] = property(data, key, inner, options);
952
+ data[rKey] = data[key];
953
+ if (key !== rKey) delete data[key];
954
+ }
955
+ return [result];
956
+ });
957
+ Schema.extend("tuple", (data, { list }, options, strict) => {
958
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
959
+ const result = list.map((inner, index) => property(data, index, inner, options));
960
+ if (strict) return [result];
961
+ result.push(...data.slice(list.length));
962
+ return [result];
963
+ });
964
+ function merge(result, data) {
965
+ for (const key in data) {
966
+ if (key in result) continue;
967
+ result[key] = data[key];
968
+ }
969
+ }
970
+ Schema.extend("object", (data, { dict }, options, strict) => {
971
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
972
+ const result = {};
973
+ for (const key in dict) {
974
+ const value = property(data, key, dict[key], options);
975
+ if (!isNullable(value) || key in data) result[key] = value;
976
+ }
977
+ if (!strict) merge(result, data);
978
+ return [result];
979
+ });
980
+ Schema.extend("union", (data, { list, toString }, options, strict) => {
981
+ const messages = [];
982
+ for (const inner of list) try {
983
+ return Schema.resolve(data, inner, options, strict);
984
+ } catch (error) {
985
+ messages.push(error);
986
+ }
987
+ throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
988
+ });
989
+ Schema.extend("intersect", (data, { list, toString }, options, strict) => {
990
+ if (!list.length) return [data];
991
+ let result;
992
+ for (const inner of list) {
993
+ const value = Schema.resolve(data, inner, options, true)[0];
994
+ if (isNullable(value)) continue;
995
+ if (isNullable(result)) result = value;
996
+ else if (typeof result !== typeof value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
997
+ else if (typeof value === "object") merge(result ??= {}, value);
998
+ else if (result !== value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
999
+ }
1000
+ if (!strict && isPlainObject(data)) merge(result, data);
1001
+ return [result];
1002
+ });
1003
+ Schema.extend("transform", (data, { inner, callback, preserve }, options) => {
1004
+ const [result, adapted = data] = Schema.resolve(data, inner, options, true);
1005
+ if (preserve) return [callback(result)];
1006
+ else return [callback(result), callback(adapted)];
1007
+ });
1008
+ const formatters = {};
1009
+ function defineMethod(name, keys, format) {
1010
+ formatters[name] = format;
1011
+ Object.assign(Schema, { [name](...args) {
1012
+ const schema = new Schema({ type: name });
1013
+ keys.forEach((key, index) => {
1014
+ switch (key) {
1015
+ case "sKey":
1016
+ schema.sKey = args[index] ?? Schema.string();
1017
+ break;
1018
+ case "inner":
1019
+ schema.inner = Schema.from(args[index]);
1020
+ break;
1021
+ case "list":
1022
+ schema.list = args[index].map(Schema.from);
1023
+ break;
1024
+ case "dict":
1025
+ schema.dict = mapValues(args[index], Schema.from);
1026
+ break;
1027
+ case "bits":
1028
+ schema.bits = {};
1029
+ for (const key in args[index]) {
1030
+ if (typeof args[index][key] !== "number") continue;
1031
+ schema.bits[key] = args[index][key];
1032
+ }
1033
+ break;
1034
+ case "callback": {
1035
+ const callback = schema.callback = args[index];
1036
+ callback["toJSON"] ||= () => callback.toString();
1037
+ break;
1038
+ }
1039
+ case "constructor": {
1040
+ const constructor = schema.constructor = args[index];
1041
+ if (typeof constructor === "function") constructor["toJSON"] ||= () => constructor["name"];
1042
+ break;
1043
+ }
1044
+ default: schema[key] = args[index];
1045
+ }
1046
+ });
1047
+ if (name === "object" || name === "dict") schema.meta.default = {};
1048
+ else if (name === "array" || name === "tuple") schema.meta.default = [];
1049
+ else if (name === "bitset") schema.meta.default = 0;
1050
+ return schema;
1051
+ } });
1052
+ }
1053
+ defineMethod("is", ["constructor"], ({ constructor }) => {
1054
+ if (typeof constructor === "function") return constructor.name;
1055
+ else return constructor;
1056
+ });
1057
+ defineMethod("any", [], () => "any");
1058
+ defineMethod("never", [], () => "never");
1059
+ defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
1060
+ defineMethod("string", [], () => "string");
1061
+ defineMethod("number", [], () => "number");
1062
+ defineMethod("boolean", [], () => "boolean");
1063
+ defineMethod("bitset", ["bits"], () => "bitset");
1064
+ defineMethod("function", [], () => "function");
1065
+ defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
1066
+ defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
1067
+ defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
1068
+ defineMethod("object", ["dict"], ({ dict }) => {
1069
+ if (Object.keys(dict).length === 0) return "{}";
1070
+ return `{ ${Object.entries(dict).map(([key, inner]) => {
1071
+ return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
1072
+ }).join(", ")} }`;
1073
+ });
1074
+ defineMethod("union", ["list"], ({ list }, inline) => {
1075
+ const result = list.map(({ toString: format }) => format()).join(" | ");
1076
+ return inline ? `(${result})` : result;
1077
+ });
1078
+ defineMethod("intersect", ["list"], ({ list }) => {
1079
+ return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
1080
+ });
1081
+ defineMethod("transform", [
1082
+ "inner",
1083
+ "callback",
1084
+ "preserve"
1085
+ ], ({ inner }, isInner) => inner.toString(isInner));
1086
+ //#endregion
1087
+ //#region src/config.ts
1088
+ /**
1089
+ * Host configuration for the artifact-app plugin.
1090
+ *
1091
+ * `baseUrl` is the DataOps API the host calls server-side; `webBaseUrl` is the
1092
+ * browser-facing DataOps frontend, only used to explain where the embed page
1093
+ * lives. The credential ref is shared with `dataops-managed`, so a managed
1094
+ * workspace signs in once.
1095
+ *
1096
+ * @module config
1097
+ */
1098
+ /** Schemastery parser for the artifact-app config. */
1099
+ const Config$1 = Schema.object({
1100
+ baseUrl: Schema.string().default("http://host.docker.internal:3101"),
1101
+ webBaseUrl: Schema.string().default(""),
1102
+ credentialRef: Schema.string().default("DATAOPS_ACCESS_TOKEN"),
1103
+ htmlMaxBytes: Schema.number().default(104857600),
1104
+ injectRuntime: Schema.boolean().default(true),
1105
+ workspaceRoot: Schema.string().default("/workspace"),
1106
+ requestTimeoutMs: Schema.number().default(3e4)
1107
+ });
1108
+ //#endregion
1109
+ //#region src/open-hub.ts
1110
+ /** SSE route the client subscribes to. */
1111
+ const OPEN_EVENTS_PATH = "/dsh-artifact-app/open/events";
1112
+ /** Same-origin route the client uses to read render and gateway addresses. */
1113
+ const CONFIG_PATH = "/dsh-artifact-app/config";
1114
+ /** Same-origin route the client uses to read the workspace token for postMessage. */
1115
+ const TOKEN_PATH = "/dsh-artifact-app/token";
1116
+ /** Same-origin app-list proxy used by the sidebar tab. */
1117
+ const APPS_PATH = "/dsh-artifact-app/apps";
1118
+ /** Same-origin preview creation used by the HTML file viewer. */
1119
+ const PREVIEW_PATH = "/dsh-artifact-app/preview";
1120
+ /** Render route prefix; `:id` follows it. */
1121
+ const RENDER_PATH = "/dsh-artifact-app/render";
1122
+ /** Gateway prefix the sandboxed cockpit HTML may call. */
1123
+ const GATEWAY_PATH = "/dsh-artifact-app/gateway";
1124
+ /** Tab type registered by the client half. */
1125
+ const ARTIFACT_TAB_TYPE = "dataops-artifact-apps";
1126
+ /** Fan-out registry for the workspace's live SSE subscribers. */
1127
+ var OpenCockpitHub = class {
1128
+ logger;
1129
+ clients = /* @__PURE__ */ new Set();
1130
+ heartbeat;
1131
+ constructor(logger) {
1132
+ this.logger = logger;
1133
+ }
1134
+ /** Accept one SSE subscription and own its response until the client disconnects. */
1135
+ subscribe(request, response) {
1136
+ response.writeHead(200, {
1137
+ "content-type": "text/event-stream; charset=utf-8",
1138
+ "cache-control": "no-cache, no-transform",
1139
+ connection: "keep-alive",
1140
+ "x-accel-buffering": "no"
1141
+ });
1142
+ response.write(": connected\n\n");
1143
+ this.clients.add(response);
1144
+ this.ensureHeartbeat();
1145
+ const remove = () => {
1146
+ this.clients.delete(response);
1147
+ if (this.clients.size === 0 && this.heartbeat !== void 0) {
1148
+ clearInterval(this.heartbeat);
1149
+ this.heartbeat = void 0;
1150
+ }
1151
+ };
1152
+ request.on("close", remove);
1153
+ request.on("aborted", remove);
1154
+ response.on("error", (error) => {
1155
+ this.logger.warn("artifact-app: SSE response failed: " + String(error));
1156
+ remove();
1157
+ });
1158
+ }
1159
+ /** Send one navigation event to every connected client. */
1160
+ broadcastOpen(event) {
1161
+ const payload = {
1162
+ type: "open_cockpit",
1163
+ requestId: event.requestId ?? randomUUID(),
1164
+ cockpitId: event.cockpitId,
1165
+ cockpitName: event.cockpitName,
1166
+ mode: event.mode,
1167
+ nonce: event.nonce
1168
+ };
1169
+ this.write("dataops-open-cockpit", payload);
1170
+ return payload;
1171
+ }
1172
+ /** Ask open viewers of one cockpit to reload it. */
1173
+ broadcastUpdated(event) {
1174
+ const payload = {
1175
+ type: "cockpit_updated",
1176
+ cockpitId: event.cockpitId,
1177
+ nonce: event.nonce
1178
+ };
1179
+ this.write("dataops-cockpit-updated", payload);
1180
+ return payload;
1181
+ }
1182
+ /** Number of live subscribers, used by a tool result to explain a missing browser. */
1183
+ size() {
1184
+ return this.clients.size;
1185
+ }
1186
+ /** Close every subscriber; called by the plugin disposer. */
1187
+ dispose() {
1188
+ if (this.heartbeat !== void 0) clearInterval(this.heartbeat);
1189
+ this.heartbeat = void 0;
1190
+ for (const client of this.clients) try {
1191
+ client.end();
1192
+ } catch {}
1193
+ this.clients.clear();
1194
+ }
1195
+ write(eventName, payload) {
1196
+ const frame = "event: " + eventName + "\ndata: " + JSON.stringify(payload) + "\n\n";
1197
+ for (const client of this.clients) try {
1198
+ client.write(frame);
1199
+ } catch (error) {
1200
+ this.clients.delete(client);
1201
+ this.logger.warn("artifact-app: SSE write failed: " + String(error));
1202
+ }
1203
+ }
1204
+ ensureHeartbeat() {
1205
+ if (this.heartbeat !== void 0) return;
1206
+ this.heartbeat = setInterval(() => {
1207
+ for (const client of this.clients) try {
1208
+ client.write(": keep-alive\n\n");
1209
+ } catch {
1210
+ this.clients.delete(client);
1211
+ }
1212
+ }, 25e3);
1213
+ this.heartbeat.unref?.();
1214
+ }
1215
+ };
1216
+ //#endregion
1217
+ //#region src/templates.ts
1218
+ /**
1219
+ * Cockpit HTML contract, validation and runtime injection.
1220
+ *
1221
+ * The HTML is untrusted content rendered in an opaque-origin iframe. The plugin
1222
+ * never "sanitizes" it; instead it refuses files that cannot be rendered safely
1223
+ * (missing SDK markers or external resources) and injects the SDK, ECharts and a
1224
+ * small theme reset before the bytes leave the host.
1225
+ *
1226
+ * @module templates
1227
+ */
1228
+ /** One failed contract check. */
1229
+ var TemplateContractError = class extends Error {
1230
+ missing;
1231
+ code = "TEMPLATE_CONTRACT_MISSING";
1232
+ constructor(missing) {
1233
+ super("模板合同不满足:" + missing.join(";"));
1234
+ this.missing = missing;
1235
+ this.name = "TemplateContractError";
1236
+ }
1237
+ };
1238
+ /** External-resource patterns the sandbox cannot load. */
1239
+ const EXTERNAL_PATTERNS = [
1240
+ {
1241
+ label: "外链 script",
1242
+ pattern: /<script[^>]+src\s*=\s*["']\s*(?:https?:)?\/\//iu
1243
+ },
1244
+ {
1245
+ label: "外链样式",
1246
+ pattern: /<link[^>]+href\s*=\s*["']\s*(?:https?:)?\/\//iu
1247
+ },
1248
+ {
1249
+ label: "外链图片",
1250
+ pattern: /<img[^>]+src\s*=\s*["']\s*(?:https?:)?\/\//iu
1251
+ },
1252
+ {
1253
+ label: "外链字体",
1254
+ pattern: /@import\s+url\(\s*["']?\s*(?:https?:)?\/\//iu
1255
+ }
1256
+ ];
1257
+ /**
1258
+ * Validate one cockpit HTML document against the template contract.
1259
+ * @param html - document bytes as text.
1260
+ * @param maxBytes - configured size ceiling.
1261
+ * @throws TemplateContractError when a required marker is missing or an external resource is present.
1262
+ * @throws Error when the document is too large.
1263
+ */
1264
+ function assertCockpitHtml(html, maxBytes) {
1265
+ const bytes = Buffer.byteLength(html, "utf8");
1266
+ if (bytes > maxBytes) throw new Error("HTML 超过 " + String(maxBytes) + " 字节上限(当前 " + String(bytes) + " 字节)");
1267
+ const missing = [];
1268
+ if (!/window\.artifactApp/u.test(html) && !/\bartifactApp\s*\./u.test(html)) missing.push("缺少 window.artifactApp");
1269
+ if (!/artifactApp\.ready\s*\(/u.test(html)) missing.push("缺少 artifactApp.ready()");
1270
+ if (!/data-slot\s*=\s*["']charts["']/iu.test(html)) missing.push("缺少 data-slot=\"charts\"");
1271
+ for (const rule of EXTERNAL_PATTERNS) if (rule.pattern.test(html)) missing.push("禁止" + rule.label);
1272
+ if (missing.length > 0) throw new TemplateContractError(missing);
1273
+ }
1274
+ /** Keep an inline script from closing its own tag. */
1275
+ const inlineScript = (source) => source.replace(/<\/script/giu, "<\\/script").replace(/<!--/gu, "<\\!--");
1276
+ /** Theme reset prepended to every rendered document. */
1277
+ const THEME_RESET = `<style id="dsh-artifact-app-theme">
1278
+ :root{color-scheme:dark}
1279
+ html,body{margin:0;width:100%;height:100%;background:#060a14;color:#e6edf7;font-family:Inter,"PingFang SC","Microsoft YaHei",system-ui,sans-serif}
1280
+ body{overflow:auto}
1281
+ ::-webkit-scrollbar{width:8px;height:8px}
1282
+ ::-webkit-scrollbar-thumb{background:rgba(120,150,200,.35);border-radius:4px}
1283
+ </style>`;
1284
+ /**
1285
+ * Inject the theme reset, ECharts and the artifact runtime into a cockpit document.
1286
+ * @param html - validated document.
1287
+ * @param options - runtime sources; `echartsJs` is omitted when ECharts injection is off.
1288
+ * @returns the document the render route serves.
1289
+ */
1290
+ function injectCockpitRuntime(html, options) {
1291
+ const head = THEME_RESET + (options.echartsJs === void 0 ? "" : "<script>" + inlineScript(options.echartsJs) + "<\/script>") + "<script>" + inlineScript(options.runtimeJs) + "<\/script>";
1292
+ if (/<\/head\s*>/iu.test(html)) return html.replace(/<\/head\s*>/iu, (match) => head + "\n" + match);
1293
+ if (/<html[^>]*>/iu.test(html)) return html.replace(/<html[^>]*>/iu, (match) => match + "\n<head>" + head + "</head>");
1294
+ return head + html;
1295
+ }
1296
+ /**
1297
+ * Build the CSP header for a rendered cockpit.
1298
+ * @param origin - the DSH origin the sandboxed page may call for gateway traffic.
1299
+ * @returns the header value.
1300
+ */
1301
+ function cockpitCsp(origin) {
1302
+ return [
1303
+ "sandbox allow-scripts allow-same-origin",
1304
+ "default-src 'none'",
1305
+ "style-src 'unsafe-inline'",
1306
+ "script-src 'unsafe-inline' 'unsafe-eval'",
1307
+ "img-src 'self' data: blob: http: https:",
1308
+ "font-src data:",
1309
+ "connect-src 'self'",
1310
+ "form-action 'none'",
1311
+ "base-uri 'none'"
1312
+ ].join("; ");
1313
+ }
1314
+ //#endregion
1315
+ //#region src/client/pack.ts
1316
+ /**
1317
+ * 模板目录 → zip(store 模式)。
1318
+ *
1319
+ * 与后端 `zip-store` 保持同一算法:素材多为已压缩格式,deflate 收益接近 0,
1320
+ * 用 store 可以零依赖且实现简单。
1321
+ */
1322
+ const crcTable = (() => {
1323
+ const table = /* @__PURE__ */ new Uint32Array(256);
1324
+ for (let i = 0; i < 256; i += 1) {
1325
+ let c = i;
1326
+ for (let k = 0; k < 8; k += 1) c = (c & 1) !== 0 ? 3988292384 ^ c >>> 1 : c >>> 1;
1327
+ table[i] = c >>> 0;
1328
+ }
1329
+ return table;
1330
+ })();
1331
+ const crc32 = (buffer) => {
1332
+ let crc = 4294967295;
1333
+ for (const byte of buffer) crc = crcTable[(crc ^ byte) & 255] ^ crc >>> 8;
1334
+ return (crc ^ 4294967295) >>> 0;
1335
+ };
1336
+ /** zip 打包(仅 store)。 */
1337
+ const zipStore = (entries) => {
1338
+ const locals = [];
1339
+ const centrals = [];
1340
+ let offset = 0;
1341
+ for (const entry of entries) {
1342
+ const nameBytes = Buffer.from(entry.name, "utf8");
1343
+ const crc = crc32(entry.data);
1344
+ const size = entry.data.byteLength;
1345
+ const local = Buffer.alloc(30 + nameBytes.length);
1346
+ local.writeUInt32LE(67324752, 0);
1347
+ local.writeUInt16LE(20, 4);
1348
+ local.writeUInt16LE(2048, 6);
1349
+ local.writeUInt16LE(0, 8);
1350
+ local.writeUInt32LE(crc, 14);
1351
+ local.writeUInt32LE(size, 18);
1352
+ local.writeUInt32LE(size, 22);
1353
+ local.writeUInt16LE(nameBytes.length, 26);
1354
+ nameBytes.copy(local, 30);
1355
+ locals.push(local, entry.data);
1356
+ const central = Buffer.alloc(46 + nameBytes.length);
1357
+ central.writeUInt32LE(33639248, 0);
1358
+ central.writeUInt16LE(20, 4);
1359
+ central.writeUInt16LE(20, 6);
1360
+ central.writeUInt16LE(2048, 8);
1361
+ central.writeUInt32LE(crc, 16);
1362
+ central.writeUInt32LE(size, 20);
1363
+ central.writeUInt32LE(size, 24);
1364
+ central.writeUInt16LE(nameBytes.length, 28);
1365
+ central.writeUInt32LE(offset, 42);
1366
+ nameBytes.copy(central, 46);
1367
+ centrals.push(central);
1368
+ offset += local.length + size;
1369
+ }
1370
+ const cd = Buffer.concat(centrals);
1371
+ const end = Buffer.alloc(22);
1372
+ end.writeUInt32LE(101010256, 0);
1373
+ end.writeUInt16LE(entries.length, 8);
1374
+ end.writeUInt16LE(entries.length, 10);
1375
+ end.writeUInt32LE(cd.length, 12);
1376
+ end.writeUInt32LE(offset, 16);
1377
+ return Buffer.concat([
1378
+ ...locals,
1379
+ cd,
1380
+ end
1381
+ ]);
1382
+ };
1383
+ /**
1384
+ * 递归读取目录并打包。
1385
+ *
1386
+ * @param dir - 模板目录(含 template.json / template.html / assets/)。
1387
+ * @returns zip 字节。
1388
+ */
1389
+ const packTemplateDir = async (dir) => {
1390
+ const entries = [];
1391
+ const walk = async (current) => {
1392
+ for (const name of await readdir(current)) {
1393
+ if (name === "node_modules" || name.startsWith(".")) continue;
1394
+ const full = join(current, name);
1395
+ if ((await stat(full)).isDirectory()) {
1396
+ await walk(full);
1397
+ continue;
1398
+ }
1399
+ entries.push({
1400
+ name: relative(dir, full).split(sep).join("/"),
1401
+ data: await readFile(full)
1402
+ });
1403
+ }
1404
+ };
1405
+ await walk(dir);
1406
+ entries.sort((a, b) => a.name.localeCompare(b.name));
1407
+ return zipStore(entries);
1408
+ };
1409
+ //#endregion
1410
+ //#region src/tools.ts
1411
+ /**
1412
+ * The nine model tools that drive cockpit artifacts.
1413
+ *
1414
+ * They are deliberately thin: every authorization and data decision stays on the
1415
+ * DataOps API, and the tools only shape a small JSON answer for the model. HTML is
1416
+ * read from the workspace, validated against the template contract, and published
1417
+ * through the same endpoint the browser uses.
1418
+ *
1419
+ * @module tools
1420
+ */
1421
+ const toolJson = (value) => value;
1422
+ const open = {
1423
+ type: "object",
1424
+ additionalProperties: true
1425
+ };
1426
+ const textOutput = (_args, value) => [{
1427
+ type: "text",
1428
+ text: JSON.stringify(value, null, 2)
1429
+ }];
1430
+ /** Resolve a tool-supplied HTML path inside the configured workspace root. */
1431
+ const resolveHtmlPath = (config, htmlPath) => {
1432
+ const root = resolve(config.workspaceRoot);
1433
+ const target = resolve(root, htmlPath);
1434
+ if (target !== root && !target.startsWith(root + sep)) throw new Error("html_path 必须位于工作区内:" + config.workspaceRoot);
1435
+ return target;
1436
+ };
1437
+ /** Read the cockpit HTML a publish call names. */
1438
+ const readCockpitHtml = async (config, htmlPath) => {
1439
+ const target = resolveHtmlPath(config, htmlPath);
1440
+ const html = await readFile(target, "utf8");
1441
+ assertCockpitHtml(html, config.htmlMaxBytes);
1442
+ return html;
1443
+ };
1444
+ /** Shape one app row for a tool answer. */
1445
+ const appSummary = (app) => ({
1446
+ id: app.id,
1447
+ name: app.name,
1448
+ description: app.description ?? null,
1449
+ catalog: app.catalog ?? null,
1450
+ status: app.status,
1451
+ currentVersion: app.currentVersion,
1452
+ publishedVersion: app.publishedVersion,
1453
+ refreshIntervalSeconds: app.refreshIntervalSeconds ?? null,
1454
+ keepConnection: app.keepConnection ?? false,
1455
+ canManage: app.canManage ?? false,
1456
+ updatedAt: app.updatedAt
1457
+ });
1458
+ /**
1459
+ * Register the cockpit tools on one plugin instance.
1460
+ * @param deps - API client, SSE hub and host config.
1461
+ */
1462
+ function registerCockpitTools(deps) {
1463
+ const { ctx, api, hub, config } = deps;
1464
+ ctx.effect(() => ctx.tools.register(defineTool({
1465
+ name: "artifact_template_list",
1466
+ description: "List the published cockpit templates (id, name, catalog, slots, question). Call this before writing cockpit HTML; pick a template instead of writing a layout from scratch.",
1467
+ parameters: {},
1468
+ output: {
1469
+ schema: open,
1470
+ render: textOutput
1471
+ },
1472
+ execute: async () => {
1473
+ const rows = await api.listTemplates();
1474
+ return toolJson({
1475
+ ok: true,
1476
+ items: rows.map((row) => ({
1477
+ id: row.id,
1478
+ name: row.name,
1479
+ description: row.description ?? null,
1480
+ catalog: row.catalog ?? null,
1481
+ slots: row.contract?.slots ?? [],
1482
+ question: row.contract?.question ?? null,
1483
+ version: row.currentVersion ?? 1,
1484
+ updatedAt: row.updatedAt ?? null
1485
+ }))
1486
+ });
1487
+ }
1488
+ })), "artifact-app: template list tool");
1489
+ ctx.effect(() => ctx.tools.register(defineTool({
1490
+ name: "artifact_template_publish",
1491
+ description: "Publish a cockpit template from a directory in the workspace. The directory must contain template.json (id/name/catalog/slots/question), template.html, and an optional assets/ folder. Reference assets in the HTML as asset://<logical-name> where <logical-name> is the file name without extension. The server validates the archive (path traversal, size, extension whitelist, SVG scripts) before storing it.",
1492
+ parameters: { directory: {
1493
+ type: "string",
1494
+ required: true,
1495
+ description: "Workspace-relative directory holding the template package."
1496
+ } },
1497
+ output: {
1498
+ schema: open,
1499
+ render: textOutput
1500
+ },
1501
+ execute: async (args) => {
1502
+ const dir = args.directory.trim();
1503
+ if (dir === "") throw new Error("directory 不能为空");
1504
+ const zip = await packTemplateDir(dir);
1505
+ const result = await api.publishTemplatePackage(zip.toString("base64"));
1506
+ return toolJson({
1507
+ ok: true,
1508
+ templateId: result.templateId,
1509
+ version: result.version,
1510
+ assets: result.assets,
1511
+ bytes: zip.byteLength,
1512
+ hint: "模板已发布。现在可以用 artifact_app_create 或 artifact_app_publish 引用 template_id 建应用。"
1513
+ });
1514
+ }
1515
+ })), "artifact-app: template publish tool");
1516
+ ctx.effect(() => ctx.tools.register(defineTool({
1517
+ name: "artifact_template_get",
1518
+ description: "Read one cockpit template: metadata, required slots, and its full HTML skeleton. Fill only the data-slot regions; never rewrite the artifactApp runtime or the required markers.",
1519
+ parameters: { template_id: {
1520
+ type: "string",
1521
+ required: true,
1522
+ description: "Template id from artifact_template_list."
1523
+ } },
1524
+ output: {
1525
+ schema: open,
1526
+ render: textOutput
1527
+ },
1528
+ execute: async (args) => {
1529
+ const [meta, body] = await Promise.all([api.getTemplate(args.template_id), api.getTemplateHtml(args.template_id)]);
1530
+ return toolJson({
1531
+ ok: true,
1532
+ id: meta.id,
1533
+ name: meta.name,
1534
+ description: meta.description ?? null,
1535
+ catalog: meta.catalog ?? null,
1536
+ slots: meta.contract?.slots ?? [],
1537
+ question: meta.contract?.question ?? null,
1538
+ version: body.version,
1539
+ html: body.html
1540
+ });
1541
+ }
1542
+ })), "artifact-app: template get tool");
1543
+ ctx.effect(() => ctx.tools.register(defineTool({
1544
+ name: "cockpit_list",
1545
+ description: "List cockpit apps the current user can see, newest first. Use it to find an existing cockpit before publishing a new one.",
1546
+ parameters: {
1547
+ query: {
1548
+ type: "string",
1549
+ description: "Case-insensitive name/description filter."
1550
+ },
1551
+ catalog: {
1552
+ type: "string",
1553
+ description: "Catalog (folder) filter."
1554
+ },
1555
+ status: {
1556
+ type: "string",
1557
+ description: "DRAFT or PUBLISHED."
1558
+ },
1559
+ limit: {
1560
+ type: "number",
1561
+ description: "Maximum rows, default 20, max 50."
1562
+ }
1563
+ },
1564
+ output: {
1565
+ schema: open,
1566
+ render: textOutput
1567
+ },
1568
+ execute: async (args) => {
1569
+ const pageSize = Math.max(1, Math.min(50, Math.trunc(args.limit ?? 20)));
1570
+ const page = await api.listApps({
1571
+ q: args.query,
1572
+ catalog: args.catalog,
1573
+ status: args.status,
1574
+ page: 1,
1575
+ pageSize
1576
+ });
1577
+ return toolJson({
1578
+ ok: true,
1579
+ total: page.total,
1580
+ items: page.items.map(appSummary)
1581
+ });
1582
+ }
1583
+ })), "artifact-app: cockpit list tool");
1584
+ ctx.effect(() => ctx.tools.register(defineTool({
1585
+ name: "cockpit_get",
1586
+ description: "Read one cockpit by id: metadata, grants visibility, and optionally its published HTML.",
1587
+ parameters: {
1588
+ cockpit_id: {
1589
+ type: "string",
1590
+ required: true
1591
+ },
1592
+ include_html: {
1593
+ type: "boolean",
1594
+ description: "Include the HTML the viewer would render."
1595
+ }
1596
+ },
1597
+ output: {
1598
+ schema: open,
1599
+ render: textOutput
1600
+ },
1601
+ execute: async (args) => {
1602
+ const app = await api.getApp(args.cockpit_id);
1603
+ const answer = {
1604
+ ok: true,
1605
+ cockpit: appSummary(app)
1606
+ };
1607
+ if (args.include_html === true) {
1608
+ const body = await api.getAppHtml(app.id);
1609
+ answer.html = body.html;
1610
+ answer.version = body.version;
1611
+ }
1612
+ return toolJson(answer);
1613
+ }
1614
+ })), "artifact-app: cockpit get tool");
1615
+ ctx.effect(() => ctx.tools.register(defineTool({
1616
+ name: "cockpit_publish",
1617
+ description: "Publish a cockpit from a workspace HTML file. Without artifact_id it creates and publishes a new cockpit; with artifact_id it publishes a new version. Validates the artifactApp markers and size first. Call only after the user explicitly confirms publishing.",
1618
+ parameters: {
1619
+ html_path: {
1620
+ type: "string",
1621
+ required: true,
1622
+ description: "Workspace path, e.g. /workspace/artifact-apps/sales.html or artifact-apps/sales.html."
1623
+ },
1624
+ artifact_id: {
1625
+ type: "string",
1626
+ description: "Existing cockpit id; omit to create a new one."
1627
+ },
1628
+ name: {
1629
+ type: "string",
1630
+ description: "Cockpit name; defaults to the existing name or the file name."
1631
+ },
1632
+ description: { type: "string" },
1633
+ catalog: { type: "string" },
1634
+ template_id: { type: "string" },
1635
+ template_version: { type: "string" },
1636
+ refresh_interval_seconds: {
1637
+ type: "number",
1638
+ description: "Polling interval for the runtime, 5..86400."
1639
+ },
1640
+ keep_connection: {
1641
+ type: "boolean",
1642
+ description: "Keep the viewer connected instead of timing out."
1643
+ }
1644
+ },
1645
+ output: {
1646
+ schema: open,
1647
+ render: textOutput
1648
+ },
1649
+ execute: async (args) => {
1650
+ const html = await readCockpitHtml(config, args.html_path);
1651
+ const published = await api.publish({
1652
+ ...args.artifact_id === void 0 ? {} : { artifactId: args.artifact_id },
1653
+ ...args.name === void 0 ? {} : { name: args.name },
1654
+ ...args.description === void 0 ? {} : { description: args.description },
1655
+ ...args.catalog === void 0 ? {} : { catalog: args.catalog },
1656
+ ...args.template_id === void 0 ? {} : { templateId: args.template_id },
1657
+ ...args.template_version === void 0 ? {} : { templateVersion: args.template_version },
1658
+ html
1659
+ });
1660
+ const metadata = {};
1661
+ if (args.refresh_interval_seconds !== void 0) metadata.refreshIntervalSeconds = Math.max(5, Math.min(86400, Math.trunc(args.refresh_interval_seconds)));
1662
+ if (args.keep_connection !== void 0) metadata.keepConnection = args.keep_connection;
1663
+ if (Object.keys(metadata).length > 0) await api.patchApp(published.id, metadata);
1664
+ const app = await api.getApp(published.id);
1665
+ hub.broadcastUpdated({
1666
+ cockpitId: published.id,
1667
+ nonce: randomUUID()
1668
+ });
1669
+ return toolJson({
1670
+ ok: true,
1671
+ id: published.id,
1672
+ version: published.version,
1673
+ publishedVersion: published.publishedVersion,
1674
+ created: published.created,
1675
+ name: app.name,
1676
+ refreshIntervalSeconds: args.refresh_interval_seconds ?? app.refreshIntervalSeconds ?? null,
1677
+ keepConnection: args.keep_connection ?? app.keepConnection ?? false
1678
+ });
1679
+ }
1680
+ })), "artifact-app: cockpit publish tool");
1681
+ ctx.effect(() => ctx.tools.register(defineTool({
1682
+ name: "cockpit_open",
1683
+ description: "Open a cockpit viewer in the right sidebar. Navigation only: it grants nothing and changes no data.",
1684
+ parameters: {
1685
+ cockpit_id: {
1686
+ type: "string",
1687
+ required: true
1688
+ },
1689
+ mode: {
1690
+ type: "string",
1691
+ description: "focus (default) or detail."
1692
+ }
1693
+ },
1694
+ output: {
1695
+ schema: open,
1696
+ render: textOutput
1697
+ },
1698
+ execute: async (args) => {
1699
+ const app = await api.getApp(args.cockpit_id);
1700
+ const mode = args.mode === "detail" ? "detail" : "focus";
1701
+ const event = hub.broadcastOpen({
1702
+ cockpitId: app.id,
1703
+ cockpitName: app.name,
1704
+ mode,
1705
+ nonce: randomUUID()
1706
+ });
1707
+ return toolJson({
1708
+ ok: true,
1709
+ opened: true,
1710
+ subscribers: hub.size(),
1711
+ requestId: event.requestId,
1712
+ cockpitId: app.id
1713
+ });
1714
+ }
1715
+ })), "artifact-app: cockpit open tool");
1716
+ ctx.effect(() => ctx.tools.register(defineTool({
1717
+ name: "cockpit_update",
1718
+ description: "Update cockpit metadata only (name, description, catalog, refresh interval, keep-connection). Never touches HTML; publish a file for content changes.",
1719
+ parameters: {
1720
+ cockpit_id: {
1721
+ type: "string",
1722
+ required: true
1723
+ },
1724
+ name: { type: "string" },
1725
+ description: { type: "string" },
1726
+ catalog: { type: "string" },
1727
+ refresh_interval_seconds: { type: "number" },
1728
+ keep_connection: { type: "boolean" }
1729
+ },
1730
+ output: {
1731
+ schema: open,
1732
+ render: textOutput
1733
+ },
1734
+ execute: async (args) => {
1735
+ const patch = {};
1736
+ if (args.name !== void 0) patch.name = args.name;
1737
+ if (args.description !== void 0) patch.description = args.description;
1738
+ if (args.catalog !== void 0) patch.catalog = args.catalog;
1739
+ if (args.refresh_interval_seconds !== void 0) patch.refreshIntervalSeconds = Math.max(5, Math.min(86400, Math.trunc(args.refresh_interval_seconds)));
1740
+ if (args.keep_connection !== void 0) patch.keepConnection = args.keep_connection;
1741
+ if (Object.keys(patch).length === 0) throw new Error("cockpit_update 至少需要一个要修改的字段");
1742
+ await api.patchApp(args.cockpit_id, patch);
1743
+ hub.broadcastUpdated({
1744
+ cockpitId: args.cockpit_id,
1745
+ nonce: randomUUID()
1746
+ });
1747
+ return toolJson({
1748
+ ok: true,
1749
+ cockpit: appSummary(await api.getApp(args.cockpit_id))
1750
+ });
1751
+ }
1752
+ })), "artifact-app: cockpit update tool");
1753
+ ctx.effect(() => ctx.tools.register(defineTool({
1754
+ name: "cockpit_delete",
1755
+ description: "Soft-delete one cockpit after explicit user approval. Deletion is reversible only by an administrator.",
1756
+ parameters: { cockpit_id: {
1757
+ type: "string",
1758
+ required: true
1759
+ } },
1760
+ output: {
1761
+ schema: open,
1762
+ render: textOutput
1763
+ },
1764
+ execute: async (args, exec) => {
1765
+ if (exec.agent === void 0) throw new Error("cockpit_delete requires an initiating agent");
1766
+ const app = await api.getApp(args.cockpit_id);
1767
+ const outcome = await ctx.approval.request({
1768
+ agent: exec.agent,
1769
+ toolName: "cockpit_delete",
1770
+ callId: exec.callId,
1771
+ signal: exec.signal,
1772
+ reason: "删除驾驶舱「" + app.name + "」(" + app.id + ")"
1773
+ });
1774
+ if (outcome !== "allowed-once") throw new Error("删除未获批准:" + outcome);
1775
+ await api.deleteApp(app.id);
1776
+ return toolJson({
1777
+ ok: true,
1778
+ deleted: app.id,
1779
+ name: app.name
1780
+ });
1781
+ }
1782
+ })), "artifact-app: cockpit delete tool");
1783
+ ctx.effect(() => ctx.tools.register(defineTool({
1784
+ name: "cockpit_grant",
1785
+ description: "Replace one cockpit's grants. Only call when the user names the principals and their access; never share automatically.",
1786
+ parameters: {
1787
+ cockpit_id: {
1788
+ type: "string",
1789
+ required: true
1790
+ },
1791
+ grants: {
1792
+ type: "array",
1793
+ required: true,
1794
+ description: "Full desired grant list; it replaces the current grants.",
1795
+ items: {
1796
+ type: "object",
1797
+ additionalProperties: false,
1798
+ properties: {
1799
+ principal_type: {
1800
+ type: "string",
1801
+ enum: [
1802
+ "USER",
1803
+ "ROLE",
1804
+ "DEPARTMENT"
1805
+ ],
1806
+ required: true
1807
+ },
1808
+ principal_id: {
1809
+ type: "string",
1810
+ required: true
1811
+ },
1812
+ action: {
1813
+ type: "string",
1814
+ enum: ["READ", "MANAGE"],
1815
+ required: true
1816
+ }
1817
+ }
1818
+ }
1819
+ }
1820
+ },
1821
+ output: {
1822
+ schema: open,
1823
+ render: textOutput
1824
+ },
1825
+ execute: async (args) => {
1826
+ const grants = args.grants.map((grant) => {
1827
+ const principalType = grant.principal_type.toUpperCase();
1828
+ const action = grant.action.toUpperCase();
1829
+ if (principalType !== "USER" && principalType !== "ROLE" && principalType !== "DEPARTMENT") throw new Error("principal_type 必须是 USER / ROLE / DEPARTMENT");
1830
+ if (action !== "READ" && action !== "MANAGE") throw new Error("action 必须是 READ / MANAGE");
1831
+ return {
1832
+ principalType,
1833
+ principalId: grant.principal_id,
1834
+ action
1835
+ };
1836
+ });
1837
+ const result = await api.putGrants(args.cockpit_id, grants);
1838
+ return toolJson({
1839
+ ok: true,
1840
+ ownerId: result.ownerId,
1841
+ grants: result.grants
1842
+ });
1843
+ }
1844
+ })), "artifact-app: cockpit grant tool");
1845
+ }
1846
+ //#endregion
1847
+ //#region src/index.ts
1848
+ const Config = Config$1;
1849
+ /** Cordis plugin name. */
1850
+ const name = "artifact-app";
1851
+ /** Host services this plugin needs. */
1852
+ const inject = [
1853
+ "webServer",
1854
+ "tools",
1855
+ "approval",
1856
+ "credentials",
1857
+ "skills"
1858
+ ];
1859
+ /** Skill id contributed by this package. */
1860
+ const SKILL_NAME = "artifact-app-authoring";
1861
+ const SKILL_FILE = new URL("../skills/artifact-app-authoring/SKILL.md", import.meta.url);
1862
+ const SKILL_ROOT = fileURLToPath(new URL("../", import.meta.url));
1863
+ /** Read a request body with a hard ceiling. */
1864
+ const readJsonBody = async (request, limit) => {
1865
+ const chunks = [];
1866
+ let size = 0;
1867
+ for await (const chunk of request) {
1868
+ const buffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
1869
+ size += buffer.length;
1870
+ if (size > limit) throw new Error("请求体超过上限");
1871
+ chunks.push(buffer);
1872
+ }
1873
+ const text = Buffer.concat(chunks).toString("utf8");
1874
+ return text.trim() === "" ? {} : JSON.parse(text);
1875
+ };
1876
+ /** Write one JSON response. */
1877
+ const writeJson = (response, status, value) => {
1878
+ response.writeHead(status, {
1879
+ "content-type": "application/json; charset=utf-8",
1880
+ "cache-control": "no-store"
1881
+ });
1882
+ response.end(JSON.stringify(value));
1883
+ };
1884
+ /** The browser-facing origin of this DSH instance. */
1885
+ const requestOrigin = (request) => {
1886
+ const header = (name) => {
1887
+ const value = request.headers[name];
1888
+ return Array.isArray(value) ? value[0] : value;
1889
+ };
1890
+ const proto = header("x-forwarded-proto")?.split(",")[0]?.trim() || "http";
1891
+ const host = header("x-forwarded-host")?.split(",")[0]?.trim() || header("host") || "127.0.0.1:3080";
1892
+ return proto + "://" + host;
1893
+ };
1894
+ /** Cache the principal's create capability; the backend still authorizes every call. */
1895
+ var PermissionCache = class {
1896
+ api;
1897
+ roles = [];
1898
+ expiresAt = 0;
1899
+ pending;
1900
+ constructor(api) {
1901
+ this.api = api;
1902
+ }
1903
+ async load() {
1904
+ return ((await this.api.me()).user?.roles ?? []).map((role) => role.code ?? role.name ?? "").filter((role) => role !== "");
1905
+ }
1906
+ async canCreate() {
1907
+ if (Date.now() > this.expiresAt) {
1908
+ this.pending ??= this.load().finally(() => {
1909
+ this.pending = void 0;
1910
+ });
1911
+ try {
1912
+ this.roles = await this.pending;
1913
+ this.expiresAt = Date.now() + 6e4;
1914
+ } catch {
1915
+ this.expiresAt = Date.now() + 1e4;
1916
+ }
1917
+ }
1918
+ return this.roles.some((role) => role.includes("管理员") || /admin/iu.test(role));
1919
+ }
1920
+ };
1921
+ /** Skill descriptor; the body is read only when the catalog loads it. */
1922
+ const buildSkill = () => ({
1923
+ name: SKILL_NAME,
1924
+ description: "根据数据资源制作驾驶舱 / 大屏 / 看板,或修改已有驾驶舱时使用。包含模板选择、data-slot 填写、artifactApp 运行时约束、HTML 文件预览和发布前用户确认。",
1925
+ invocation: {
1926
+ modelInvocable: true,
1927
+ userInvocable: true
1928
+ },
1929
+ provider: SKILL_NAME,
1930
+ source: "bundled",
1931
+ resourceBase: {
1932
+ kind: "directory",
1933
+ path: SKILL_ROOT
1934
+ },
1935
+ rank: BUNDLED_SKILL_RANK,
1936
+ locator: SKILL_FILE,
1937
+ metadata: { permissions: ["artifact-app:create"] }
1938
+ });
1939
+ /**
1940
+ * Register the host routes, the model tools and the authoring skill.
1941
+ * @param ctx - DSH host context with web routes, tools, approval and credentials.
1942
+ * @param config - DataOps origin, credential ref and HTML limits.
1943
+ */
1944
+ function apply(ctx, config) {
1945
+ const api = new ArtifactApi(config.baseUrl, { resolve: async () => (await ctx.credentials.resolve(credentialRef(config.credentialRef)))?.value }, config.requestTimeoutMs);
1946
+ const hub = new OpenCockpitHub(ctx.logger);
1947
+ const permissions = new PermissionCache(api);
1948
+ const previewIds = /* @__PURE__ */ new Map();
1949
+ let runtimeScript;
1950
+ let echartsScript;
1951
+ const runtime = () => runtimeScript ??= api.runtimeScript();
1952
+ const echarts = () => echartsScript ??= api.echartsScript();
1953
+ ctx.effect(() => () => hub.dispose(), "artifact-app: SSE clients");
1954
+ ctx.effect(() => ctx.webServer.register({
1955
+ kind: "exact",
1956
+ path: CONFIG_PATH,
1957
+ handler: (request, response) => {
1958
+ writeJson(response, 200, {
1959
+ renderBaseUrl: RENDER_PATH,
1960
+ gatewayBaseUrl: GATEWAY_PATH + "/api/artifact-apps",
1961
+ tabType: ARTIFACT_TAB_TYPE,
1962
+ dataopsWebBaseUrl: config.webBaseUrl.trim() || origin
1963
+ });
1964
+ }
1965
+ }), "artifact-app: config route");
1966
+ ctx.effect(() => ctx.webServer.register({
1967
+ kind: "exact",
1968
+ path: TOKEN_PATH,
1969
+ handler: async (_request, response) => {
1970
+ try {
1971
+ writeJson(response, 200, { token: await api.token() });
1972
+ } catch (error) {
1973
+ writeJson(response, 401, { error: error instanceof Error ? error.message : String(error) });
1974
+ }
1975
+ }
1976
+ }), "artifact-app: token route");
1977
+ ctx.effect(() => ctx.webServer.register({
1978
+ kind: "exact",
1979
+ path: OPEN_EVENTS_PATH,
1980
+ handler: (request, response) => hub.subscribe(request, response)
1981
+ }), "artifact-app: open events route");
1982
+ ctx.effect(() => ctx.webServer.register({
1983
+ kind: "exact",
1984
+ path: APPS_PATH,
1985
+ handler: async (request, response) => {
1986
+ try {
1987
+ const url = new URL(request.url ?? "/", "http://dsh.internal");
1988
+ const page = await api.listApps({
1989
+ q: url.searchParams.get("q") ?? void 0,
1990
+ catalog: url.searchParams.get("catalog") ?? void 0,
1991
+ status: url.searchParams.get("status") ?? void 0,
1992
+ page: 1,
1993
+ pageSize: Math.max(1, Math.min(100, Number(url.searchParams.get("pageSize") ?? 50) || 50))
1994
+ });
1995
+ writeJson(response, 200, page);
1996
+ } catch (error) {
1997
+ writeJson(response, 500, { error: error instanceof Error ? error.message : String(error) });
1998
+ }
1999
+ }
2000
+ }), "artifact-app: apps route");
2001
+ ctx.effect(() => ctx.webServer.register({
2002
+ kind: "exact",
2003
+ path: PREVIEW_PATH,
2004
+ handler: async (request, response) => {
2005
+ if (request.method !== "POST") {
2006
+ writeJson(response, 405, { error: "POST only" });
2007
+ return;
2008
+ }
2009
+ try {
2010
+ const body = await readJsonBody(request, config.htmlMaxBytes + 65536);
2011
+ const path = typeof body.path === "string" ? body.path : "";
2012
+ const html = typeof body.html === "string" ? body.html : "";
2013
+ if (path === "" || html === "") throw new Error("path 和 html 都是必填项");
2014
+ assertCockpitHtml(html, config.htmlMaxBytes);
2015
+ const existing = previewIds.get(path);
2016
+ const result = await api.preview({
2017
+ ...existing === void 0 ? {} : { artifactId: existing },
2018
+ html,
2019
+ name: typeof body.name === "string" && body.name.trim() !== "" ? body.name.trim() : basename(path).replace(/\.html?$/iu, ""),
2020
+ description: "驾驶舱文件预览",
2021
+ ...typeof body.templateId === "string" ? { templateId: body.templateId } : {},
2022
+ ...typeof body.templateVersion === "string" ? { templateVersion: body.templateVersion } : {}
2023
+ });
2024
+ previewIds.set(path, result.id);
2025
+ writeJson(response, 200, {
2026
+ artifactId: result.id,
2027
+ version: result.version,
2028
+ created: result.created
2029
+ });
2030
+ } catch (error) {
2031
+ const message = error instanceof Error ? error.message : String(error);
2032
+ writeJson(response, error instanceof Error && "code" in error && error.code === "TEMPLATE_CONTRACT_MISSING" ? 422 : 400, { error: message });
2033
+ }
2034
+ }
2035
+ }), "artifact-app: preview route");
2036
+ ctx.effect(() => ctx.webServer.register({
2037
+ kind: "prefix",
2038
+ path: RENDER_PATH,
2039
+ handler: async (request, response) => {
2040
+ try {
2041
+ const rest = new URL(request.url ?? "/", "http://dsh.internal").pathname.slice(24).replace(/^\/+/u, "");
2042
+ const id = decodeURIComponent(rest);
2043
+ if (id === "" || id.includes("/")) {
2044
+ writeJson(response, 400, { error: "缺少驾驶舱 id" });
2045
+ return;
2046
+ }
2047
+ const body = await api.getAppHtml(id);
2048
+ assertCockpitHtml(body.html, config.htmlMaxBytes);
2049
+ const logicalNames = [...new Set([...body.html.matchAll(/asset:\/\/([a-zA-Z0-9][a-zA-Z0-9._-]{0,62})/gu)].map((m) => m[1]))];
2050
+ let resolvedHtml = body.html;
2051
+ if (logicalNames.length > 0) {
2052
+ const templateId = body.templateId ?? void 0;
2053
+ const templateUrls = templateId === void 0 ? {} : await api.resolveAssets(logicalNames, "template", templateId).catch(() => ({}));
2054
+ const rest = logicalNames.filter((name) => templateUrls[name] === void 0);
2055
+ const sharedUrls = rest.length === 0 ? {} : await api.resolveAssets(rest, "shared").catch(() => ({}));
2056
+ for (const [name, url] of Object.entries({
2057
+ ...sharedUrls,
2058
+ ...templateUrls
2059
+ })) resolvedHtml = resolvedHtml.split("asset://" + name).join(url);
2060
+ }
2061
+ const withRuntime = injectCockpitRuntime(resolvedHtml, {
2062
+ runtimeJs: await runtime(),
2063
+ ...config.injectRuntime ? { echartsJs: await echarts() } : {}
2064
+ });
2065
+ response.writeHead(200, {
2066
+ "content-type": "text/html; charset=utf-8",
2067
+ "content-security-policy": cockpitCsp(requestOrigin(request)),
2068
+ "x-content-type-options": "nosniff",
2069
+ "cache-control": "no-store"
2070
+ });
2071
+ response.end(withRuntime);
2072
+ } catch (error) {
2073
+ const message = error instanceof Error ? error.message : String(error);
2074
+ response.writeHead(502, {
2075
+ "content-type": "text/plain; charset=utf-8",
2076
+ "cache-control": "no-store"
2077
+ });
2078
+ response.end("驾驶舱渲染失败:" + message);
2079
+ }
2080
+ }
2081
+ }), "artifact-app: render route");
2082
+ ctx.effect(() => ctx.webServer.register({
2083
+ kind: "prefix",
2084
+ path: GATEWAY_PATH,
2085
+ handler: async (request, response) => {
2086
+ const cors = {
2087
+ "access-control-allow-origin": "*",
2088
+ "access-control-allow-methods": "POST, OPTIONS",
2089
+ "access-control-allow-headers": "authorization, content-type, accept",
2090
+ "access-control-max-age": "600"
2091
+ };
2092
+ if (request.method === "OPTIONS") {
2093
+ response.writeHead(204, cors);
2094
+ response.end();
2095
+ return;
2096
+ }
2097
+ try {
2098
+ const upstream = new URL(request.url ?? "/", "http://dsh.internal").pathname.slice(25);
2099
+ if (!/^\/api\/artifact-apps\/(?:[^/]+(?:\/(?:query|call-api|html))?|(?:runtime|echarts)\.js)$/u.test(upstream)) {
2100
+ response.writeHead(403, {
2101
+ ...cors,
2102
+ "content-type": "application/json; charset=utf-8"
2103
+ });
2104
+ response.end(JSON.stringify({ error: "网关只代理驾驶舱取数接口" }));
2105
+ return;
2106
+ }
2107
+ const forwarded = request.headers["x-dataops-token"];
2108
+ const authorization = typeof forwarded === "string" && forwarded.trim() !== "" ? `Bearer ${forwarded.trim()}` : request.headers.authorization;
2109
+ const rawBody = request.method === "POST" ? await readJsonBody(request, 1048576) : void 0;
2110
+ const bodyToken = typeof rawBody?.__dataopsToken === "string" ? rawBody.__dataopsToken : void 0;
2111
+ if (rawBody !== void 0) delete rawBody.__dataopsToken;
2112
+ const effectiveAuth = bodyToken !== void 0 && bodyToken !== "" ? `Bearer ${bodyToken}` : authorization;
2113
+ const init = {
2114
+ method: request.method,
2115
+ ...rawBody !== void 0 ? { body: JSON.stringify(rawBody) } : {}
2116
+ };
2117
+ const result = await api.gateway(upstream, init, typeof effectiveAuth === "string" ? effectiveAuth : void 0);
2118
+ response.writeHead(result.status, {
2119
+ ...cors,
2120
+ "content-type": result.contentType,
2121
+ "cache-control": "no-store"
2122
+ });
2123
+ response.end(result.body);
2124
+ } catch (error) {
2125
+ const message = error instanceof Error ? error.message : String(error);
2126
+ response.writeHead(502, {
2127
+ ...cors,
2128
+ "content-type": "application/json; charset=utf-8"
2129
+ });
2130
+ response.end(JSON.stringify({ error: message }));
2131
+ }
2132
+ }
2133
+ }), "artifact-app: gateway route");
2134
+ registerCockpitTools({
2135
+ ctx,
2136
+ api,
2137
+ hub,
2138
+ config
2139
+ });
2140
+ const skill = buildSkill();
2141
+ const provider = {
2142
+ name: SKILL_NAME,
2143
+ list: async () => await permissions.canCreate() ? [skill] : [],
2144
+ async get() {
2145
+ return {
2146
+ ...skill,
2147
+ content: await readFile(SKILL_FILE, "utf8")
2148
+ };
2149
+ }
2150
+ };
2151
+ ctx.skills.registerProvider(() => provider);
2152
+ }
2153
+ //#endregion
2154
+ export { APPS_PATH, ARTIFACT_TAB_TYPE, ArtifactApi, CONFIG_PATH, Config, DataOpsError, GATEWAY_PATH, OPEN_EVENTS_PATH, OpenCockpitHub, PREVIEW_PATH, RENDER_PATH, TOKEN_PATH, TemplateContractError, apply, assertCockpitHtml, cockpitCsp, inject, injectCockpitRuntime, name };