@hasna/configs 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +264 -0
  2. package/dashboard/dist/assets/index-DQ3P1g1z.css +1 -0
  3. package/dashboard/dist/assets/index-DbXmAL_d.js +11 -0
  4. package/dashboard/dist/index.html +14 -0
  5. package/dashboard/dist/vite.svg +1 -0
  6. package/dist/cli/index.d.ts +3 -0
  7. package/dist/cli/index.d.ts.map +1 -0
  8. package/dist/cli/index.js +3087 -0
  9. package/dist/db/configs.d.ts +10 -0
  10. package/dist/db/configs.d.ts.map +1 -0
  11. package/dist/db/configs.test.d.ts +2 -0
  12. package/dist/db/configs.test.d.ts.map +1 -0
  13. package/dist/db/database.d.ts +7 -0
  14. package/dist/db/database.d.ts.map +1 -0
  15. package/dist/db/machines.d.ts +8 -0
  16. package/dist/db/machines.d.ts.map +1 -0
  17. package/dist/db/machines.test.d.ts +2 -0
  18. package/dist/db/machines.test.d.ts.map +1 -0
  19. package/dist/db/profiles.d.ts +11 -0
  20. package/dist/db/profiles.d.ts.map +1 -0
  21. package/dist/db/profiles.test.d.ts +2 -0
  22. package/dist/db/profiles.test.d.ts.map +1 -0
  23. package/dist/db/snapshots.d.ts +8 -0
  24. package/dist/db/snapshots.d.ts.map +1 -0
  25. package/dist/db/snapshots.test.d.ts +2 -0
  26. package/dist/db/snapshots.test.d.ts.map +1 -0
  27. package/dist/index.d.ts +17 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +896 -0
  30. package/dist/lib/apply.d.ts +11 -0
  31. package/dist/lib/apply.d.ts.map +1 -0
  32. package/dist/lib/apply.test.d.ts +2 -0
  33. package/dist/lib/apply.test.d.ts.map +1 -0
  34. package/dist/lib/export.d.ts +12 -0
  35. package/dist/lib/export.d.ts.map +1 -0
  36. package/dist/lib/import.d.ts +14 -0
  37. package/dist/lib/import.d.ts.map +1 -0
  38. package/dist/lib/sync.d.ts +19 -0
  39. package/dist/lib/sync.d.ts.map +1 -0
  40. package/dist/lib/sync.test.d.ts +2 -0
  41. package/dist/lib/sync.test.d.ts.map +1 -0
  42. package/dist/lib/template.d.ts +10 -0
  43. package/dist/lib/template.d.ts.map +1 -0
  44. package/dist/lib/template.test.d.ts +2 -0
  45. package/dist/lib/template.test.d.ts.map +1 -0
  46. package/dist/mcp/index.d.ts +3 -0
  47. package/dist/mcp/index.d.ts.map +1 -0
  48. package/dist/mcp/index.js +662 -0
  49. package/dist/mcp/mcp.test.d.ts +2 -0
  50. package/dist/mcp/mcp.test.d.ts.map +1 -0
  51. package/dist/server/index.d.ts +7 -0
  52. package/dist/server/index.d.ts.map +1 -0
  53. package/dist/server/index.js +2390 -0
  54. package/dist/server/server.test.d.ts +2 -0
  55. package/dist/server/server.test.d.ts.map +1 -0
  56. package/dist/types/index.d.ts +152 -0
  57. package/dist/types/index.d.ts.map +1 -0
  58. package/package.json +78 -0
@@ -0,0 +1,2390 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+
4
+ // node_modules/hono/dist/compose.js
5
+ var compose = (middleware, onError, onNotFound) => {
6
+ return (context, next) => {
7
+ let index = -1;
8
+ return dispatch(0);
9
+ async function dispatch(i) {
10
+ if (i <= index) {
11
+ throw new Error("next() called multiple times");
12
+ }
13
+ index = i;
14
+ let res;
15
+ let isError = false;
16
+ let handler;
17
+ if (middleware[i]) {
18
+ handler = middleware[i][0][0];
19
+ context.req.routeIndex = i;
20
+ } else {
21
+ handler = i === middleware.length && next || undefined;
22
+ }
23
+ if (handler) {
24
+ try {
25
+ res = await handler(context, () => dispatch(i + 1));
26
+ } catch (err) {
27
+ if (err instanceof Error && onError) {
28
+ context.error = err;
29
+ res = await onError(err, context);
30
+ isError = true;
31
+ } else {
32
+ throw err;
33
+ }
34
+ }
35
+ } else {
36
+ if (context.finalized === false && onNotFound) {
37
+ res = await onNotFound(context);
38
+ }
39
+ }
40
+ if (res && (context.finalized === false || isError)) {
41
+ context.res = res;
42
+ }
43
+ return context;
44
+ }
45
+ };
46
+ };
47
+
48
+ // node_modules/hono/dist/request/constants.js
49
+ var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
50
+
51
+ // node_modules/hono/dist/utils/body.js
52
+ var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
53
+ const { all = false, dot = false } = options;
54
+ const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
55
+ const contentType = headers.get("Content-Type");
56
+ if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
57
+ return parseFormData(request, { all, dot });
58
+ }
59
+ return {};
60
+ };
61
+ async function parseFormData(request, options) {
62
+ const formData = await request.formData();
63
+ if (formData) {
64
+ return convertFormDataToBodyData(formData, options);
65
+ }
66
+ return {};
67
+ }
68
+ function convertFormDataToBodyData(formData, options) {
69
+ const form = /* @__PURE__ */ Object.create(null);
70
+ formData.forEach((value, key) => {
71
+ const shouldParseAllValues = options.all || key.endsWith("[]");
72
+ if (!shouldParseAllValues) {
73
+ form[key] = value;
74
+ } else {
75
+ handleParsingAllValues(form, key, value);
76
+ }
77
+ });
78
+ if (options.dot) {
79
+ Object.entries(form).forEach(([key, value]) => {
80
+ const shouldParseDotValues = key.includes(".");
81
+ if (shouldParseDotValues) {
82
+ handleParsingNestedValues(form, key, value);
83
+ delete form[key];
84
+ }
85
+ });
86
+ }
87
+ return form;
88
+ }
89
+ var handleParsingAllValues = (form, key, value) => {
90
+ if (form[key] !== undefined) {
91
+ if (Array.isArray(form[key])) {
92
+ form[key].push(value);
93
+ } else {
94
+ form[key] = [form[key], value];
95
+ }
96
+ } else {
97
+ if (!key.endsWith("[]")) {
98
+ form[key] = value;
99
+ } else {
100
+ form[key] = [value];
101
+ }
102
+ }
103
+ };
104
+ var handleParsingNestedValues = (form, key, value) => {
105
+ if (/(?:^|\.)__proto__\./.test(key)) {
106
+ return;
107
+ }
108
+ let nestedForm = form;
109
+ const keys = key.split(".");
110
+ keys.forEach((key2, index) => {
111
+ if (index === keys.length - 1) {
112
+ nestedForm[key2] = value;
113
+ } else {
114
+ if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
115
+ nestedForm[key2] = /* @__PURE__ */ Object.create(null);
116
+ }
117
+ nestedForm = nestedForm[key2];
118
+ }
119
+ });
120
+ };
121
+
122
+ // node_modules/hono/dist/utils/url.js
123
+ var splitPath = (path) => {
124
+ const paths = path.split("/");
125
+ if (paths[0] === "") {
126
+ paths.shift();
127
+ }
128
+ return paths;
129
+ };
130
+ var splitRoutingPath = (routePath) => {
131
+ const { groups, path } = extractGroupsFromPath(routePath);
132
+ const paths = splitPath(path);
133
+ return replaceGroupMarks(paths, groups);
134
+ };
135
+ var extractGroupsFromPath = (path) => {
136
+ const groups = [];
137
+ path = path.replace(/\{[^}]+\}/g, (match, index) => {
138
+ const mark = `@${index}`;
139
+ groups.push([mark, match]);
140
+ return mark;
141
+ });
142
+ return { groups, path };
143
+ };
144
+ var replaceGroupMarks = (paths, groups) => {
145
+ for (let i = groups.length - 1;i >= 0; i--) {
146
+ const [mark] = groups[i];
147
+ for (let j = paths.length - 1;j >= 0; j--) {
148
+ if (paths[j].includes(mark)) {
149
+ paths[j] = paths[j].replace(mark, groups[i][1]);
150
+ break;
151
+ }
152
+ }
153
+ }
154
+ return paths;
155
+ };
156
+ var patternCache = {};
157
+ var getPattern = (label, next) => {
158
+ if (label === "*") {
159
+ return "*";
160
+ }
161
+ const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
162
+ if (match) {
163
+ const cacheKey = `${label}#${next}`;
164
+ if (!patternCache[cacheKey]) {
165
+ if (match[2]) {
166
+ patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)];
167
+ } else {
168
+ patternCache[cacheKey] = [label, match[1], true];
169
+ }
170
+ }
171
+ return patternCache[cacheKey];
172
+ }
173
+ return null;
174
+ };
175
+ var tryDecode = (str, decoder) => {
176
+ try {
177
+ return decoder(str);
178
+ } catch {
179
+ return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
180
+ try {
181
+ return decoder(match);
182
+ } catch {
183
+ return match;
184
+ }
185
+ });
186
+ }
187
+ };
188
+ var tryDecodeURI = (str) => tryDecode(str, decodeURI);
189
+ var getPath = (request) => {
190
+ const url = request.url;
191
+ const start = url.indexOf("/", url.indexOf(":") + 4);
192
+ let i = start;
193
+ for (;i < url.length; i++) {
194
+ const charCode = url.charCodeAt(i);
195
+ if (charCode === 37) {
196
+ const queryIndex = url.indexOf("?", i);
197
+ const hashIndex = url.indexOf("#", i);
198
+ const end = queryIndex === -1 ? hashIndex === -1 ? undefined : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
199
+ const path = url.slice(start, end);
200
+ return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
201
+ } else if (charCode === 63 || charCode === 35) {
202
+ break;
203
+ }
204
+ }
205
+ return url.slice(start, i);
206
+ };
207
+ var getPathNoStrict = (request) => {
208
+ const result = getPath(request);
209
+ return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
210
+ };
211
+ var mergePath = (base, sub, ...rest) => {
212
+ if (rest.length) {
213
+ sub = mergePath(sub, ...rest);
214
+ }
215
+ return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
216
+ };
217
+ var checkOptionalParameter = (path) => {
218
+ if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
219
+ return null;
220
+ }
221
+ const segments = path.split("/");
222
+ const results = [];
223
+ let basePath = "";
224
+ segments.forEach((segment) => {
225
+ if (segment !== "" && !/\:/.test(segment)) {
226
+ basePath += "/" + segment;
227
+ } else if (/\:/.test(segment)) {
228
+ if (/\?/.test(segment)) {
229
+ if (results.length === 0 && basePath === "") {
230
+ results.push("/");
231
+ } else {
232
+ results.push(basePath);
233
+ }
234
+ const optionalSegment = segment.replace("?", "");
235
+ basePath += "/" + optionalSegment;
236
+ results.push(basePath);
237
+ } else {
238
+ basePath += "/" + segment;
239
+ }
240
+ }
241
+ });
242
+ return results.filter((v, i, a) => a.indexOf(v) === i);
243
+ };
244
+ var _decodeURI = (value) => {
245
+ if (!/[%+]/.test(value)) {
246
+ return value;
247
+ }
248
+ if (value.indexOf("+") !== -1) {
249
+ value = value.replace(/\+/g, " ");
250
+ }
251
+ return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
252
+ };
253
+ var _getQueryParam = (url, key, multiple) => {
254
+ let encoded;
255
+ if (!multiple && key && !/[%+]/.test(key)) {
256
+ let keyIndex2 = url.indexOf("?", 8);
257
+ if (keyIndex2 === -1) {
258
+ return;
259
+ }
260
+ if (!url.startsWith(key, keyIndex2 + 1)) {
261
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
262
+ }
263
+ while (keyIndex2 !== -1) {
264
+ const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
265
+ if (trailingKeyCode === 61) {
266
+ const valueIndex = keyIndex2 + key.length + 2;
267
+ const endIndex = url.indexOf("&", valueIndex);
268
+ return _decodeURI(url.slice(valueIndex, endIndex === -1 ? undefined : endIndex));
269
+ } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
270
+ return "";
271
+ }
272
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
273
+ }
274
+ encoded = /[%+]/.test(url);
275
+ if (!encoded) {
276
+ return;
277
+ }
278
+ }
279
+ const results = {};
280
+ encoded ??= /[%+]/.test(url);
281
+ let keyIndex = url.indexOf("?", 8);
282
+ while (keyIndex !== -1) {
283
+ const nextKeyIndex = url.indexOf("&", keyIndex + 1);
284
+ let valueIndex = url.indexOf("=", keyIndex);
285
+ if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
286
+ valueIndex = -1;
287
+ }
288
+ let name = url.slice(keyIndex + 1, valueIndex === -1 ? nextKeyIndex === -1 ? undefined : nextKeyIndex : valueIndex);
289
+ if (encoded) {
290
+ name = _decodeURI(name);
291
+ }
292
+ keyIndex = nextKeyIndex;
293
+ if (name === "") {
294
+ continue;
295
+ }
296
+ let value;
297
+ if (valueIndex === -1) {
298
+ value = "";
299
+ } else {
300
+ value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? undefined : nextKeyIndex);
301
+ if (encoded) {
302
+ value = _decodeURI(value);
303
+ }
304
+ }
305
+ if (multiple) {
306
+ if (!(results[name] && Array.isArray(results[name]))) {
307
+ results[name] = [];
308
+ }
309
+ results[name].push(value);
310
+ } else {
311
+ results[name] ??= value;
312
+ }
313
+ }
314
+ return key ? results[key] : results;
315
+ };
316
+ var getQueryParam = _getQueryParam;
317
+ var getQueryParams = (url, key) => {
318
+ return _getQueryParam(url, key, true);
319
+ };
320
+ var decodeURIComponent_ = decodeURIComponent;
321
+
322
+ // node_modules/hono/dist/request.js
323
+ var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
324
+ var HonoRequest = class {
325
+ raw;
326
+ #validatedData;
327
+ #matchResult;
328
+ routeIndex = 0;
329
+ path;
330
+ bodyCache = {};
331
+ constructor(request, path = "/", matchResult = [[]]) {
332
+ this.raw = request;
333
+ this.path = path;
334
+ this.#matchResult = matchResult;
335
+ this.#validatedData = {};
336
+ }
337
+ param(key) {
338
+ return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
339
+ }
340
+ #getDecodedParam(key) {
341
+ const paramKey = this.#matchResult[0][this.routeIndex][1][key];
342
+ const param = this.#getParamValue(paramKey);
343
+ return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
344
+ }
345
+ #getAllDecodedParams() {
346
+ const decoded = {};
347
+ const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
348
+ for (const key of keys) {
349
+ const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
350
+ if (value !== undefined) {
351
+ decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
352
+ }
353
+ }
354
+ return decoded;
355
+ }
356
+ #getParamValue(paramKey) {
357
+ return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
358
+ }
359
+ query(key) {
360
+ return getQueryParam(this.url, key);
361
+ }
362
+ queries(key) {
363
+ return getQueryParams(this.url, key);
364
+ }
365
+ header(name) {
366
+ if (name) {
367
+ return this.raw.headers.get(name) ?? undefined;
368
+ }
369
+ const headerData = {};
370
+ this.raw.headers.forEach((value, key) => {
371
+ headerData[key] = value;
372
+ });
373
+ return headerData;
374
+ }
375
+ async parseBody(options) {
376
+ return this.bodyCache.parsedBody ??= await parseBody(this, options);
377
+ }
378
+ #cachedBody = (key) => {
379
+ const { bodyCache, raw } = this;
380
+ const cachedBody = bodyCache[key];
381
+ if (cachedBody) {
382
+ return cachedBody;
383
+ }
384
+ const anyCachedKey = Object.keys(bodyCache)[0];
385
+ if (anyCachedKey) {
386
+ return bodyCache[anyCachedKey].then((body) => {
387
+ if (anyCachedKey === "json") {
388
+ body = JSON.stringify(body);
389
+ }
390
+ return new Response(body)[key]();
391
+ });
392
+ }
393
+ return bodyCache[key] = raw[key]();
394
+ };
395
+ json() {
396
+ return this.#cachedBody("text").then((text) => JSON.parse(text));
397
+ }
398
+ text() {
399
+ return this.#cachedBody("text");
400
+ }
401
+ arrayBuffer() {
402
+ return this.#cachedBody("arrayBuffer");
403
+ }
404
+ blob() {
405
+ return this.#cachedBody("blob");
406
+ }
407
+ formData() {
408
+ return this.#cachedBody("formData");
409
+ }
410
+ addValidatedData(target, data) {
411
+ this.#validatedData[target] = data;
412
+ }
413
+ valid(target) {
414
+ return this.#validatedData[target];
415
+ }
416
+ get url() {
417
+ return this.raw.url;
418
+ }
419
+ get method() {
420
+ return this.raw.method;
421
+ }
422
+ get [GET_MATCH_RESULT]() {
423
+ return this.#matchResult;
424
+ }
425
+ get matchedRoutes() {
426
+ return this.#matchResult[0].map(([[, route]]) => route);
427
+ }
428
+ get routePath() {
429
+ return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
430
+ }
431
+ };
432
+
433
+ // node_modules/hono/dist/utils/html.js
434
+ var HtmlEscapedCallbackPhase = {
435
+ Stringify: 1,
436
+ BeforeStream: 2,
437
+ Stream: 3
438
+ };
439
+ var raw = (value, callbacks) => {
440
+ const escapedString = new String(value);
441
+ escapedString.isEscaped = true;
442
+ escapedString.callbacks = callbacks;
443
+ return escapedString;
444
+ };
445
+ var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
446
+ if (typeof str === "object" && !(str instanceof String)) {
447
+ if (!(str instanceof Promise)) {
448
+ str = str.toString();
449
+ }
450
+ if (str instanceof Promise) {
451
+ str = await str;
452
+ }
453
+ }
454
+ const callbacks = str.callbacks;
455
+ if (!callbacks?.length) {
456
+ return Promise.resolve(str);
457
+ }
458
+ if (buffer) {
459
+ buffer[0] += str;
460
+ } else {
461
+ buffer = [str];
462
+ }
463
+ const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then((res) => Promise.all(res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))).then(() => buffer[0]));
464
+ if (preserveCallbacks) {
465
+ return raw(await resStr, callbacks);
466
+ } else {
467
+ return resStr;
468
+ }
469
+ };
470
+
471
+ // node_modules/hono/dist/context.js
472
+ var TEXT_PLAIN = "text/plain; charset=UTF-8";
473
+ var setDefaultContentType = (contentType, headers) => {
474
+ return {
475
+ "Content-Type": contentType,
476
+ ...headers
477
+ };
478
+ };
479
+ var createResponseInstance = (body, init) => new Response(body, init);
480
+ var Context = class {
481
+ #rawRequest;
482
+ #req;
483
+ env = {};
484
+ #var;
485
+ finalized = false;
486
+ error;
487
+ #status;
488
+ #executionCtx;
489
+ #res;
490
+ #layout;
491
+ #renderer;
492
+ #notFoundHandler;
493
+ #preparedHeaders;
494
+ #matchResult;
495
+ #path;
496
+ constructor(req, options) {
497
+ this.#rawRequest = req;
498
+ if (options) {
499
+ this.#executionCtx = options.executionCtx;
500
+ this.env = options.env;
501
+ this.#notFoundHandler = options.notFoundHandler;
502
+ this.#path = options.path;
503
+ this.#matchResult = options.matchResult;
504
+ }
505
+ }
506
+ get req() {
507
+ this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
508
+ return this.#req;
509
+ }
510
+ get event() {
511
+ if (this.#executionCtx && "respondWith" in this.#executionCtx) {
512
+ return this.#executionCtx;
513
+ } else {
514
+ throw Error("This context has no FetchEvent");
515
+ }
516
+ }
517
+ get executionCtx() {
518
+ if (this.#executionCtx) {
519
+ return this.#executionCtx;
520
+ } else {
521
+ throw Error("This context has no ExecutionContext");
522
+ }
523
+ }
524
+ get res() {
525
+ return this.#res ||= createResponseInstance(null, {
526
+ headers: this.#preparedHeaders ??= new Headers
527
+ });
528
+ }
529
+ set res(_res) {
530
+ if (this.#res && _res) {
531
+ _res = createResponseInstance(_res.body, _res);
532
+ for (const [k, v] of this.#res.headers.entries()) {
533
+ if (k === "content-type") {
534
+ continue;
535
+ }
536
+ if (k === "set-cookie") {
537
+ const cookies = this.#res.headers.getSetCookie();
538
+ _res.headers.delete("set-cookie");
539
+ for (const cookie of cookies) {
540
+ _res.headers.append("set-cookie", cookie);
541
+ }
542
+ } else {
543
+ _res.headers.set(k, v);
544
+ }
545
+ }
546
+ }
547
+ this.#res = _res;
548
+ this.finalized = true;
549
+ }
550
+ render = (...args) => {
551
+ this.#renderer ??= (content) => this.html(content);
552
+ return this.#renderer(...args);
553
+ };
554
+ setLayout = (layout) => this.#layout = layout;
555
+ getLayout = () => this.#layout;
556
+ setRenderer = (renderer) => {
557
+ this.#renderer = renderer;
558
+ };
559
+ header = (name, value, options) => {
560
+ if (this.finalized) {
561
+ this.#res = createResponseInstance(this.#res.body, this.#res);
562
+ }
563
+ const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers;
564
+ if (value === undefined) {
565
+ headers.delete(name);
566
+ } else if (options?.append) {
567
+ headers.append(name, value);
568
+ } else {
569
+ headers.set(name, value);
570
+ }
571
+ };
572
+ status = (status) => {
573
+ this.#status = status;
574
+ };
575
+ set = (key, value) => {
576
+ this.#var ??= /* @__PURE__ */ new Map;
577
+ this.#var.set(key, value);
578
+ };
579
+ get = (key) => {
580
+ return this.#var ? this.#var.get(key) : undefined;
581
+ };
582
+ get var() {
583
+ if (!this.#var) {
584
+ return {};
585
+ }
586
+ return Object.fromEntries(this.#var);
587
+ }
588
+ #newResponse(data, arg, headers) {
589
+ const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers;
590
+ if (typeof arg === "object" && "headers" in arg) {
591
+ const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
592
+ for (const [key, value] of argHeaders) {
593
+ if (key.toLowerCase() === "set-cookie") {
594
+ responseHeaders.append(key, value);
595
+ } else {
596
+ responseHeaders.set(key, value);
597
+ }
598
+ }
599
+ }
600
+ if (headers) {
601
+ for (const [k, v] of Object.entries(headers)) {
602
+ if (typeof v === "string") {
603
+ responseHeaders.set(k, v);
604
+ } else {
605
+ responseHeaders.delete(k);
606
+ for (const v2 of v) {
607
+ responseHeaders.append(k, v2);
608
+ }
609
+ }
610
+ }
611
+ }
612
+ const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
613
+ return createResponseInstance(data, { status, headers: responseHeaders });
614
+ }
615
+ newResponse = (...args) => this.#newResponse(...args);
616
+ body = (data, arg, headers) => this.#newResponse(data, arg, headers);
617
+ text = (text, arg, headers) => {
618
+ return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(text, arg, setDefaultContentType(TEXT_PLAIN, headers));
619
+ };
620
+ json = (object, arg, headers) => {
621
+ return this.#newResponse(JSON.stringify(object), arg, setDefaultContentType("application/json", headers));
622
+ };
623
+ html = (html, arg, headers) => {
624
+ const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
625
+ return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
626
+ };
627
+ redirect = (location, status) => {
628
+ const locationString = String(location);
629
+ this.header("Location", !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString));
630
+ return this.newResponse(null, status ?? 302);
631
+ };
632
+ notFound = () => {
633
+ this.#notFoundHandler ??= () => createResponseInstance();
634
+ return this.#notFoundHandler(this);
635
+ };
636
+ };
637
+
638
+ // node_modules/hono/dist/router.js
639
+ var METHOD_NAME_ALL = "ALL";
640
+ var METHOD_NAME_ALL_LOWERCASE = "all";
641
+ var METHODS = ["get", "post", "put", "delete", "options", "patch"];
642
+ var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
643
+ var UnsupportedPathError = class extends Error {
644
+ };
645
+
646
+ // node_modules/hono/dist/utils/constants.js
647
+ var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
648
+
649
+ // node_modules/hono/dist/hono-base.js
650
+ var notFoundHandler = (c) => {
651
+ return c.text("404 Not Found", 404);
652
+ };
653
+ var errorHandler = (err, c) => {
654
+ if ("getResponse" in err) {
655
+ const res = err.getResponse();
656
+ return c.newResponse(res.body, res);
657
+ }
658
+ console.error(err);
659
+ return c.text("Internal Server Error", 500);
660
+ };
661
+ var Hono = class _Hono {
662
+ get;
663
+ post;
664
+ put;
665
+ delete;
666
+ options;
667
+ patch;
668
+ all;
669
+ on;
670
+ use;
671
+ router;
672
+ getPath;
673
+ _basePath = "/";
674
+ #path = "/";
675
+ routes = [];
676
+ constructor(options = {}) {
677
+ const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
678
+ allMethods.forEach((method) => {
679
+ this[method] = (args1, ...args) => {
680
+ if (typeof args1 === "string") {
681
+ this.#path = args1;
682
+ } else {
683
+ this.#addRoute(method, this.#path, args1);
684
+ }
685
+ args.forEach((handler) => {
686
+ this.#addRoute(method, this.#path, handler);
687
+ });
688
+ return this;
689
+ };
690
+ });
691
+ this.on = (method, path, ...handlers) => {
692
+ for (const p of [path].flat()) {
693
+ this.#path = p;
694
+ for (const m of [method].flat()) {
695
+ handlers.map((handler) => {
696
+ this.#addRoute(m.toUpperCase(), this.#path, handler);
697
+ });
698
+ }
699
+ }
700
+ return this;
701
+ };
702
+ this.use = (arg1, ...handlers) => {
703
+ if (typeof arg1 === "string") {
704
+ this.#path = arg1;
705
+ } else {
706
+ this.#path = "*";
707
+ handlers.unshift(arg1);
708
+ }
709
+ handlers.forEach((handler) => {
710
+ this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
711
+ });
712
+ return this;
713
+ };
714
+ const { strict, ...optionsWithoutStrict } = options;
715
+ Object.assign(this, optionsWithoutStrict);
716
+ this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
717
+ }
718
+ #clone() {
719
+ const clone = new _Hono({
720
+ router: this.router,
721
+ getPath: this.getPath
722
+ });
723
+ clone.errorHandler = this.errorHandler;
724
+ clone.#notFoundHandler = this.#notFoundHandler;
725
+ clone.routes = this.routes;
726
+ return clone;
727
+ }
728
+ #notFoundHandler = notFoundHandler;
729
+ errorHandler = errorHandler;
730
+ route(path, app) {
731
+ const subApp = this.basePath(path);
732
+ app.routes.map((r) => {
733
+ let handler;
734
+ if (app.errorHandler === errorHandler) {
735
+ handler = r.handler;
736
+ } else {
737
+ handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
738
+ handler[COMPOSED_HANDLER] = r.handler;
739
+ }
740
+ subApp.#addRoute(r.method, r.path, handler);
741
+ });
742
+ return this;
743
+ }
744
+ basePath(path) {
745
+ const subApp = this.#clone();
746
+ subApp._basePath = mergePath(this._basePath, path);
747
+ return subApp;
748
+ }
749
+ onError = (handler) => {
750
+ this.errorHandler = handler;
751
+ return this;
752
+ };
753
+ notFound = (handler) => {
754
+ this.#notFoundHandler = handler;
755
+ return this;
756
+ };
757
+ mount(path, applicationHandler, options) {
758
+ let replaceRequest;
759
+ let optionHandler;
760
+ if (options) {
761
+ if (typeof options === "function") {
762
+ optionHandler = options;
763
+ } else {
764
+ optionHandler = options.optionHandler;
765
+ if (options.replaceRequest === false) {
766
+ replaceRequest = (request) => request;
767
+ } else {
768
+ replaceRequest = options.replaceRequest;
769
+ }
770
+ }
771
+ }
772
+ const getOptions = optionHandler ? (c) => {
773
+ const options2 = optionHandler(c);
774
+ return Array.isArray(options2) ? options2 : [options2];
775
+ } : (c) => {
776
+ let executionContext = undefined;
777
+ try {
778
+ executionContext = c.executionCtx;
779
+ } catch {}
780
+ return [c.env, executionContext];
781
+ };
782
+ replaceRequest ||= (() => {
783
+ const mergedPath = mergePath(this._basePath, path);
784
+ const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
785
+ return (request) => {
786
+ const url = new URL(request.url);
787
+ url.pathname = url.pathname.slice(pathPrefixLength) || "/";
788
+ return new Request(url, request);
789
+ };
790
+ })();
791
+ const handler = async (c, next) => {
792
+ const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
793
+ if (res) {
794
+ return res;
795
+ }
796
+ await next();
797
+ };
798
+ this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
799
+ return this;
800
+ }
801
+ #addRoute(method, path, handler) {
802
+ method = method.toUpperCase();
803
+ path = mergePath(this._basePath, path);
804
+ const r = { basePath: this._basePath, path, method, handler };
805
+ this.router.add(method, path, [handler, r]);
806
+ this.routes.push(r);
807
+ }
808
+ #handleError(err, c) {
809
+ if (err instanceof Error) {
810
+ return this.errorHandler(err, c);
811
+ }
812
+ throw err;
813
+ }
814
+ #dispatch(request, executionCtx, env, method) {
815
+ if (method === "HEAD") {
816
+ return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
817
+ }
818
+ const path = this.getPath(request, { env });
819
+ const matchResult = this.router.match(method, path);
820
+ const c = new Context(request, {
821
+ path,
822
+ matchResult,
823
+ env,
824
+ executionCtx,
825
+ notFoundHandler: this.#notFoundHandler
826
+ });
827
+ if (matchResult[0].length === 1) {
828
+ let res;
829
+ try {
830
+ res = matchResult[0][0][0][0](c, async () => {
831
+ c.res = await this.#notFoundHandler(c);
832
+ });
833
+ } catch (err) {
834
+ return this.#handleError(err, c);
835
+ }
836
+ return res instanceof Promise ? res.then((resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
837
+ }
838
+ const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
839
+ return (async () => {
840
+ try {
841
+ const context = await composed(c);
842
+ if (!context.finalized) {
843
+ throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");
844
+ }
845
+ return context.res;
846
+ } catch (err) {
847
+ return this.#handleError(err, c);
848
+ }
849
+ })();
850
+ }
851
+ fetch = (request, ...rest) => {
852
+ return this.#dispatch(request, rest[1], rest[0], request.method);
853
+ };
854
+ request = (input, requestInit, Env, executionCtx) => {
855
+ if (input instanceof Request) {
856
+ return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
857
+ }
858
+ input = input.toString();
859
+ return this.fetch(new Request(/^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`, requestInit), Env, executionCtx);
860
+ };
861
+ fire = () => {
862
+ addEventListener("fetch", (event) => {
863
+ event.respondWith(this.#dispatch(event.request, event, undefined, event.request.method));
864
+ });
865
+ };
866
+ };
867
+
868
+ // node_modules/hono/dist/router/reg-exp-router/matcher.js
869
+ var emptyParam = [];
870
+ function match(method, path) {
871
+ const matchers = this.buildAllMatchers();
872
+ const match2 = (method2, path2) => {
873
+ const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
874
+ const staticMatch = matcher[2][path2];
875
+ if (staticMatch) {
876
+ return staticMatch;
877
+ }
878
+ const match3 = path2.match(matcher[0]);
879
+ if (!match3) {
880
+ return [[], emptyParam];
881
+ }
882
+ const index = match3.indexOf("", 1);
883
+ return [matcher[1][index], match3];
884
+ };
885
+ this.match = match2;
886
+ return match2(method, path);
887
+ }
888
+
889
+ // node_modules/hono/dist/router/reg-exp-router/node.js
890
+ var LABEL_REG_EXP_STR = "[^/]+";
891
+ var ONLY_WILDCARD_REG_EXP_STR = ".*";
892
+ var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
893
+ var PATH_ERROR = /* @__PURE__ */ Symbol();
894
+ var regExpMetaChars = new Set(".\\+*[^]$()");
895
+ function compareKey(a, b) {
896
+ if (a.length === 1) {
897
+ return b.length === 1 ? a < b ? -1 : 1 : -1;
898
+ }
899
+ if (b.length === 1) {
900
+ return 1;
901
+ }
902
+ if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
903
+ return 1;
904
+ } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
905
+ return -1;
906
+ }
907
+ if (a === LABEL_REG_EXP_STR) {
908
+ return 1;
909
+ } else if (b === LABEL_REG_EXP_STR) {
910
+ return -1;
911
+ }
912
+ return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
913
+ }
914
+ var Node = class _Node {
915
+ #index;
916
+ #varIndex;
917
+ #children = /* @__PURE__ */ Object.create(null);
918
+ insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
919
+ if (tokens.length === 0) {
920
+ if (this.#index !== undefined) {
921
+ throw PATH_ERROR;
922
+ }
923
+ if (pathErrorCheckOnly) {
924
+ return;
925
+ }
926
+ this.#index = index;
927
+ return;
928
+ }
929
+ const [token, ...restTokens] = tokens;
930
+ const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
931
+ let node;
932
+ if (pattern) {
933
+ const name = pattern[1];
934
+ let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
935
+ if (name && pattern[2]) {
936
+ if (regexpStr === ".*") {
937
+ throw PATH_ERROR;
938
+ }
939
+ regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
940
+ if (/\((?!\?:)/.test(regexpStr)) {
941
+ throw PATH_ERROR;
942
+ }
943
+ }
944
+ node = this.#children[regexpStr];
945
+ if (!node) {
946
+ if (Object.keys(this.#children).some((k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) {
947
+ throw PATH_ERROR;
948
+ }
949
+ if (pathErrorCheckOnly) {
950
+ return;
951
+ }
952
+ node = this.#children[regexpStr] = new _Node;
953
+ if (name !== "") {
954
+ node.#varIndex = context.varIndex++;
955
+ }
956
+ }
957
+ if (!pathErrorCheckOnly && name !== "") {
958
+ paramMap.push([name, node.#varIndex]);
959
+ }
960
+ } else {
961
+ node = this.#children[token];
962
+ if (!node) {
963
+ if (Object.keys(this.#children).some((k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) {
964
+ throw PATH_ERROR;
965
+ }
966
+ if (pathErrorCheckOnly) {
967
+ return;
968
+ }
969
+ node = this.#children[token] = new _Node;
970
+ }
971
+ }
972
+ node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
973
+ }
974
+ buildRegExpStr() {
975
+ const childKeys = Object.keys(this.#children).sort(compareKey);
976
+ const strList = childKeys.map((k) => {
977
+ const c = this.#children[k];
978
+ return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
979
+ });
980
+ if (typeof this.#index === "number") {
981
+ strList.unshift(`#${this.#index}`);
982
+ }
983
+ if (strList.length === 0) {
984
+ return "";
985
+ }
986
+ if (strList.length === 1) {
987
+ return strList[0];
988
+ }
989
+ return "(?:" + strList.join("|") + ")";
990
+ }
991
+ };
992
+
993
+ // node_modules/hono/dist/router/reg-exp-router/trie.js
994
+ var Trie = class {
995
+ #context = { varIndex: 0 };
996
+ #root = new Node;
997
+ insert(path, index, pathErrorCheckOnly) {
998
+ const paramAssoc = [];
999
+ const groups = [];
1000
+ for (let i = 0;; ) {
1001
+ let replaced = false;
1002
+ path = path.replace(/\{[^}]+\}/g, (m) => {
1003
+ const mark = `@\\${i}`;
1004
+ groups[i] = [mark, m];
1005
+ i++;
1006
+ replaced = true;
1007
+ return mark;
1008
+ });
1009
+ if (!replaced) {
1010
+ break;
1011
+ }
1012
+ }
1013
+ const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
1014
+ for (let i = groups.length - 1;i >= 0; i--) {
1015
+ const [mark] = groups[i];
1016
+ for (let j = tokens.length - 1;j >= 0; j--) {
1017
+ if (tokens[j].indexOf(mark) !== -1) {
1018
+ tokens[j] = tokens[j].replace(mark, groups[i][1]);
1019
+ break;
1020
+ }
1021
+ }
1022
+ }
1023
+ this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
1024
+ return paramAssoc;
1025
+ }
1026
+ buildRegExp() {
1027
+ let regexp = this.#root.buildRegExpStr();
1028
+ if (regexp === "") {
1029
+ return [/^$/, [], []];
1030
+ }
1031
+ let captureIndex = 0;
1032
+ const indexReplacementMap = [];
1033
+ const paramReplacementMap = [];
1034
+ regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
1035
+ if (handlerIndex !== undefined) {
1036
+ indexReplacementMap[++captureIndex] = Number(handlerIndex);
1037
+ return "$()";
1038
+ }
1039
+ if (paramIndex !== undefined) {
1040
+ paramReplacementMap[Number(paramIndex)] = ++captureIndex;
1041
+ return "";
1042
+ }
1043
+ return "";
1044
+ });
1045
+ return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
1046
+ }
1047
+ };
1048
+
1049
+ // node_modules/hono/dist/router/reg-exp-router/router.js
1050
+ var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
1051
+ var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
1052
+ function buildWildcardRegExp(path) {
1053
+ return wildcardRegExpCache[path] ??= new RegExp(path === "*" ? "" : `^${path.replace(/\/\*$|([.\\+*[^\]$()])/g, (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)")}$`);
1054
+ }
1055
+ function clearWildcardRegExpCache() {
1056
+ wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
1057
+ }
1058
+ function buildMatcherFromPreprocessedRoutes(routes) {
1059
+ const trie = new Trie;
1060
+ const handlerData = [];
1061
+ if (routes.length === 0) {
1062
+ return nullMatcher;
1063
+ }
1064
+ const routesWithStaticPathFlag = routes.map((route) => [!/\*|\/:/.test(route[0]), ...route]).sort(([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length);
1065
+ const staticMap = /* @__PURE__ */ Object.create(null);
1066
+ for (let i = 0, j = -1, len = routesWithStaticPathFlag.length;i < len; i++) {
1067
+ const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
1068
+ if (pathErrorCheckOnly) {
1069
+ staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
1070
+ } else {
1071
+ j++;
1072
+ }
1073
+ let paramAssoc;
1074
+ try {
1075
+ paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
1076
+ } catch (e) {
1077
+ throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
1078
+ }
1079
+ if (pathErrorCheckOnly) {
1080
+ continue;
1081
+ }
1082
+ handlerData[j] = handlers.map(([h, paramCount]) => {
1083
+ const paramIndexMap = /* @__PURE__ */ Object.create(null);
1084
+ paramCount -= 1;
1085
+ for (;paramCount >= 0; paramCount--) {
1086
+ const [key, value] = paramAssoc[paramCount];
1087
+ paramIndexMap[key] = value;
1088
+ }
1089
+ return [h, paramIndexMap];
1090
+ });
1091
+ }
1092
+ const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
1093
+ for (let i = 0, len = handlerData.length;i < len; i++) {
1094
+ for (let j = 0, len2 = handlerData[i].length;j < len2; j++) {
1095
+ const map = handlerData[i][j]?.[1];
1096
+ if (!map) {
1097
+ continue;
1098
+ }
1099
+ const keys = Object.keys(map);
1100
+ for (let k = 0, len3 = keys.length;k < len3; k++) {
1101
+ map[keys[k]] = paramReplacementMap[map[keys[k]]];
1102
+ }
1103
+ }
1104
+ }
1105
+ const handlerMap = [];
1106
+ for (const i in indexReplacementMap) {
1107
+ handlerMap[i] = handlerData[indexReplacementMap[i]];
1108
+ }
1109
+ return [regexp, handlerMap, staticMap];
1110
+ }
1111
+ function findMiddleware(middleware, path) {
1112
+ if (!middleware) {
1113
+ return;
1114
+ }
1115
+ for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
1116
+ if (buildWildcardRegExp(k).test(path)) {
1117
+ return [...middleware[k]];
1118
+ }
1119
+ }
1120
+ return;
1121
+ }
1122
+ var RegExpRouter = class {
1123
+ name = "RegExpRouter";
1124
+ #middleware;
1125
+ #routes;
1126
+ constructor() {
1127
+ this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
1128
+ this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
1129
+ }
1130
+ add(method, path, handler) {
1131
+ const middleware = this.#middleware;
1132
+ const routes = this.#routes;
1133
+ if (!middleware || !routes) {
1134
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
1135
+ }
1136
+ if (!middleware[method]) {
1137
+ [middleware, routes].forEach((handlerMap) => {
1138
+ handlerMap[method] = /* @__PURE__ */ Object.create(null);
1139
+ Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
1140
+ handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
1141
+ });
1142
+ });
1143
+ }
1144
+ if (path === "/*") {
1145
+ path = "*";
1146
+ }
1147
+ const paramCount = (path.match(/\/:/g) || []).length;
1148
+ if (/\*$/.test(path)) {
1149
+ const re = buildWildcardRegExp(path);
1150
+ if (method === METHOD_NAME_ALL) {
1151
+ Object.keys(middleware).forEach((m) => {
1152
+ middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
1153
+ });
1154
+ } else {
1155
+ middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
1156
+ }
1157
+ Object.keys(middleware).forEach((m) => {
1158
+ if (method === METHOD_NAME_ALL || method === m) {
1159
+ Object.keys(middleware[m]).forEach((p) => {
1160
+ re.test(p) && middleware[m][p].push([handler, paramCount]);
1161
+ });
1162
+ }
1163
+ });
1164
+ Object.keys(routes).forEach((m) => {
1165
+ if (method === METHOD_NAME_ALL || method === m) {
1166
+ Object.keys(routes[m]).forEach((p) => re.test(p) && routes[m][p].push([handler, paramCount]));
1167
+ }
1168
+ });
1169
+ return;
1170
+ }
1171
+ const paths = checkOptionalParameter(path) || [path];
1172
+ for (let i = 0, len = paths.length;i < len; i++) {
1173
+ const path2 = paths[i];
1174
+ Object.keys(routes).forEach((m) => {
1175
+ if (method === METHOD_NAME_ALL || method === m) {
1176
+ routes[m][path2] ||= [
1177
+ ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
1178
+ ];
1179
+ routes[m][path2].push([handler, paramCount - len + i + 1]);
1180
+ }
1181
+ });
1182
+ }
1183
+ }
1184
+ match = match;
1185
+ buildAllMatchers() {
1186
+ const matchers = /* @__PURE__ */ Object.create(null);
1187
+ Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
1188
+ matchers[method] ||= this.#buildMatcher(method);
1189
+ });
1190
+ this.#middleware = this.#routes = undefined;
1191
+ clearWildcardRegExpCache();
1192
+ return matchers;
1193
+ }
1194
+ #buildMatcher(method) {
1195
+ const routes = [];
1196
+ let hasOwnRoute = method === METHOD_NAME_ALL;
1197
+ [this.#middleware, this.#routes].forEach((r) => {
1198
+ const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
1199
+ if (ownRoute.length !== 0) {
1200
+ hasOwnRoute ||= true;
1201
+ routes.push(...ownRoute);
1202
+ } else if (method !== METHOD_NAME_ALL) {
1203
+ routes.push(...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]]));
1204
+ }
1205
+ });
1206
+ if (!hasOwnRoute) {
1207
+ return null;
1208
+ } else {
1209
+ return buildMatcherFromPreprocessedRoutes(routes);
1210
+ }
1211
+ }
1212
+ };
1213
+
1214
+ // node_modules/hono/dist/router/reg-exp-router/prepared-router.js
1215
+ var PreparedRegExpRouter = class {
1216
+ name = "PreparedRegExpRouter";
1217
+ #matchers;
1218
+ #relocateMap;
1219
+ constructor(matchers, relocateMap) {
1220
+ this.#matchers = matchers;
1221
+ this.#relocateMap = relocateMap;
1222
+ }
1223
+ #addWildcard(method, handlerData) {
1224
+ const matcher = this.#matchers[method];
1225
+ matcher[1].forEach((list) => list && list.push(handlerData));
1226
+ Object.values(matcher[2]).forEach((list) => list[0].push(handlerData));
1227
+ }
1228
+ #addPath(method, path, handler, indexes, map) {
1229
+ const matcher = this.#matchers[method];
1230
+ if (!map) {
1231
+ matcher[2][path][0].push([handler, {}]);
1232
+ } else {
1233
+ indexes.forEach((index) => {
1234
+ if (typeof index === "number") {
1235
+ matcher[1][index].push([handler, map]);
1236
+ } else {
1237
+ matcher[2][index || path][0].push([handler, map]);
1238
+ }
1239
+ });
1240
+ }
1241
+ }
1242
+ add(method, path, handler) {
1243
+ if (!this.#matchers[method]) {
1244
+ const all = this.#matchers[METHOD_NAME_ALL];
1245
+ const staticMap = {};
1246
+ for (const key in all[2]) {
1247
+ staticMap[key] = [all[2][key][0].slice(), emptyParam];
1248
+ }
1249
+ this.#matchers[method] = [
1250
+ all[0],
1251
+ all[1].map((list) => Array.isArray(list) ? list.slice() : 0),
1252
+ staticMap
1253
+ ];
1254
+ }
1255
+ if (path === "/*" || path === "*") {
1256
+ const handlerData = [handler, {}];
1257
+ if (method === METHOD_NAME_ALL) {
1258
+ for (const m in this.#matchers) {
1259
+ this.#addWildcard(m, handlerData);
1260
+ }
1261
+ } else {
1262
+ this.#addWildcard(method, handlerData);
1263
+ }
1264
+ return;
1265
+ }
1266
+ const data = this.#relocateMap[path];
1267
+ if (!data) {
1268
+ throw new Error(`Path ${path} is not registered`);
1269
+ }
1270
+ for (const [indexes, map] of data) {
1271
+ if (method === METHOD_NAME_ALL) {
1272
+ for (const m in this.#matchers) {
1273
+ this.#addPath(m, path, handler, indexes, map);
1274
+ }
1275
+ } else {
1276
+ this.#addPath(method, path, handler, indexes, map);
1277
+ }
1278
+ }
1279
+ }
1280
+ buildAllMatchers() {
1281
+ return this.#matchers;
1282
+ }
1283
+ match = match;
1284
+ };
1285
+
1286
+ // node_modules/hono/dist/router/smart-router/router.js
1287
+ var SmartRouter = class {
1288
+ name = "SmartRouter";
1289
+ #routers = [];
1290
+ #routes = [];
1291
+ constructor(init) {
1292
+ this.#routers = init.routers;
1293
+ }
1294
+ add(method, path, handler) {
1295
+ if (!this.#routes) {
1296
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
1297
+ }
1298
+ this.#routes.push([method, path, handler]);
1299
+ }
1300
+ match(method, path) {
1301
+ if (!this.#routes) {
1302
+ throw new Error("Fatal error");
1303
+ }
1304
+ const routers = this.#routers;
1305
+ const routes = this.#routes;
1306
+ const len = routers.length;
1307
+ let i = 0;
1308
+ let res;
1309
+ for (;i < len; i++) {
1310
+ const router = routers[i];
1311
+ try {
1312
+ for (let i2 = 0, len2 = routes.length;i2 < len2; i2++) {
1313
+ router.add(...routes[i2]);
1314
+ }
1315
+ res = router.match(method, path);
1316
+ } catch (e) {
1317
+ if (e instanceof UnsupportedPathError) {
1318
+ continue;
1319
+ }
1320
+ throw e;
1321
+ }
1322
+ this.match = router.match.bind(router);
1323
+ this.#routers = [router];
1324
+ this.#routes = undefined;
1325
+ break;
1326
+ }
1327
+ if (i === len) {
1328
+ throw new Error("Fatal error");
1329
+ }
1330
+ this.name = `SmartRouter + ${this.activeRouter.name}`;
1331
+ return res;
1332
+ }
1333
+ get activeRouter() {
1334
+ if (this.#routes || this.#routers.length !== 1) {
1335
+ throw new Error("No active router has been determined yet.");
1336
+ }
1337
+ return this.#routers[0];
1338
+ }
1339
+ };
1340
+
1341
+ // node_modules/hono/dist/router/trie-router/node.js
1342
+ var emptyParams = /* @__PURE__ */ Object.create(null);
1343
+ var hasChildren = (children) => {
1344
+ for (const _ in children) {
1345
+ return true;
1346
+ }
1347
+ return false;
1348
+ };
1349
+ var Node2 = class _Node2 {
1350
+ #methods;
1351
+ #children;
1352
+ #patterns;
1353
+ #order = 0;
1354
+ #params = emptyParams;
1355
+ constructor(method, handler, children) {
1356
+ this.#children = children || /* @__PURE__ */ Object.create(null);
1357
+ this.#methods = [];
1358
+ if (method && handler) {
1359
+ const m = /* @__PURE__ */ Object.create(null);
1360
+ m[method] = { handler, possibleKeys: [], score: 0 };
1361
+ this.#methods = [m];
1362
+ }
1363
+ this.#patterns = [];
1364
+ }
1365
+ insert(method, path, handler) {
1366
+ this.#order = ++this.#order;
1367
+ let curNode = this;
1368
+ const parts = splitRoutingPath(path);
1369
+ const possibleKeys = [];
1370
+ for (let i = 0, len = parts.length;i < len; i++) {
1371
+ const p = parts[i];
1372
+ const nextP = parts[i + 1];
1373
+ const pattern = getPattern(p, nextP);
1374
+ const key = Array.isArray(pattern) ? pattern[0] : p;
1375
+ if (key in curNode.#children) {
1376
+ curNode = curNode.#children[key];
1377
+ if (pattern) {
1378
+ possibleKeys.push(pattern[1]);
1379
+ }
1380
+ continue;
1381
+ }
1382
+ curNode.#children[key] = new _Node2;
1383
+ if (pattern) {
1384
+ curNode.#patterns.push(pattern);
1385
+ possibleKeys.push(pattern[1]);
1386
+ }
1387
+ curNode = curNode.#children[key];
1388
+ }
1389
+ curNode.#methods.push({
1390
+ [method]: {
1391
+ handler,
1392
+ possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
1393
+ score: this.#order
1394
+ }
1395
+ });
1396
+ return curNode;
1397
+ }
1398
+ #pushHandlerSets(handlerSets, node, method, nodeParams, params) {
1399
+ for (let i = 0, len = node.#methods.length;i < len; i++) {
1400
+ const m = node.#methods[i];
1401
+ const handlerSet = m[method] || m[METHOD_NAME_ALL];
1402
+ const processedSet = {};
1403
+ if (handlerSet !== undefined) {
1404
+ handlerSet.params = /* @__PURE__ */ Object.create(null);
1405
+ handlerSets.push(handlerSet);
1406
+ if (nodeParams !== emptyParams || params && params !== emptyParams) {
1407
+ for (let i2 = 0, len2 = handlerSet.possibleKeys.length;i2 < len2; i2++) {
1408
+ const key = handlerSet.possibleKeys[i2];
1409
+ const processed = processedSet[handlerSet.score];
1410
+ handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
1411
+ processedSet[handlerSet.score] = true;
1412
+ }
1413
+ }
1414
+ }
1415
+ }
1416
+ }
1417
+ search(method, path) {
1418
+ const handlerSets = [];
1419
+ this.#params = emptyParams;
1420
+ const curNode = this;
1421
+ let curNodes = [curNode];
1422
+ const parts = splitPath(path);
1423
+ const curNodesQueue = [];
1424
+ const len = parts.length;
1425
+ let partOffsets = null;
1426
+ for (let i = 0;i < len; i++) {
1427
+ const part = parts[i];
1428
+ const isLast = i === len - 1;
1429
+ const tempNodes = [];
1430
+ for (let j = 0, len2 = curNodes.length;j < len2; j++) {
1431
+ const node = curNodes[j];
1432
+ const nextNode = node.#children[part];
1433
+ if (nextNode) {
1434
+ nextNode.#params = node.#params;
1435
+ if (isLast) {
1436
+ if (nextNode.#children["*"]) {
1437
+ this.#pushHandlerSets(handlerSets, nextNode.#children["*"], method, node.#params);
1438
+ }
1439
+ this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);
1440
+ } else {
1441
+ tempNodes.push(nextNode);
1442
+ }
1443
+ }
1444
+ for (let k = 0, len3 = node.#patterns.length;k < len3; k++) {
1445
+ const pattern = node.#patterns[k];
1446
+ const params = node.#params === emptyParams ? {} : { ...node.#params };
1447
+ if (pattern === "*") {
1448
+ const astNode = node.#children["*"];
1449
+ if (astNode) {
1450
+ this.#pushHandlerSets(handlerSets, astNode, method, node.#params);
1451
+ astNode.#params = params;
1452
+ tempNodes.push(astNode);
1453
+ }
1454
+ continue;
1455
+ }
1456
+ const [key, name, matcher] = pattern;
1457
+ if (!part && !(matcher instanceof RegExp)) {
1458
+ continue;
1459
+ }
1460
+ const child = node.#children[key];
1461
+ if (matcher instanceof RegExp) {
1462
+ if (partOffsets === null) {
1463
+ partOffsets = new Array(len);
1464
+ let offset = path[0] === "/" ? 1 : 0;
1465
+ for (let p = 0;p < len; p++) {
1466
+ partOffsets[p] = offset;
1467
+ offset += parts[p].length + 1;
1468
+ }
1469
+ }
1470
+ const restPathString = path.substring(partOffsets[i]);
1471
+ const m = matcher.exec(restPathString);
1472
+ if (m) {
1473
+ params[name] = m[0];
1474
+ this.#pushHandlerSets(handlerSets, child, method, node.#params, params);
1475
+ if (hasChildren(child.#children)) {
1476
+ child.#params = params;
1477
+ const componentCount = m[0].match(/\//)?.length ?? 0;
1478
+ const targetCurNodes = curNodesQueue[componentCount] ||= [];
1479
+ targetCurNodes.push(child);
1480
+ }
1481
+ continue;
1482
+ }
1483
+ }
1484
+ if (matcher === true || matcher.test(part)) {
1485
+ params[name] = part;
1486
+ if (isLast) {
1487
+ this.#pushHandlerSets(handlerSets, child, method, params, node.#params);
1488
+ if (child.#children["*"]) {
1489
+ this.#pushHandlerSets(handlerSets, child.#children["*"], method, params, node.#params);
1490
+ }
1491
+ } else {
1492
+ child.#params = params;
1493
+ tempNodes.push(child);
1494
+ }
1495
+ }
1496
+ }
1497
+ }
1498
+ const shifted = curNodesQueue.shift();
1499
+ curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;
1500
+ }
1501
+ if (handlerSets.length > 1) {
1502
+ handlerSets.sort((a, b) => {
1503
+ return a.score - b.score;
1504
+ });
1505
+ }
1506
+ return [handlerSets.map(({ handler, params }) => [handler, params])];
1507
+ }
1508
+ };
1509
+
1510
+ // node_modules/hono/dist/router/trie-router/router.js
1511
+ var TrieRouter = class {
1512
+ name = "TrieRouter";
1513
+ #node;
1514
+ constructor() {
1515
+ this.#node = new Node2;
1516
+ }
1517
+ add(method, path, handler) {
1518
+ const results = checkOptionalParameter(path);
1519
+ if (results) {
1520
+ for (let i = 0, len = results.length;i < len; i++) {
1521
+ this.#node.insert(method, results[i], handler);
1522
+ }
1523
+ return;
1524
+ }
1525
+ this.#node.insert(method, path, handler);
1526
+ }
1527
+ match(method, path) {
1528
+ return this.#node.search(method, path);
1529
+ }
1530
+ };
1531
+
1532
+ // node_modules/hono/dist/hono.js
1533
+ var Hono2 = class extends Hono {
1534
+ constructor(options = {}) {
1535
+ super(options);
1536
+ this.router = options.router ?? new SmartRouter({
1537
+ routers: [new RegExpRouter, new TrieRouter]
1538
+ });
1539
+ }
1540
+ };
1541
+
1542
+ // node_modules/hono/dist/middleware/cors/index.js
1543
+ var cors = (options) => {
1544
+ const defaults = {
1545
+ origin: "*",
1546
+ allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"],
1547
+ allowHeaders: [],
1548
+ exposeHeaders: []
1549
+ };
1550
+ const opts = {
1551
+ ...defaults,
1552
+ ...options
1553
+ };
1554
+ const findAllowOrigin = ((optsOrigin) => {
1555
+ if (typeof optsOrigin === "string") {
1556
+ if (optsOrigin === "*") {
1557
+ return () => optsOrigin;
1558
+ } else {
1559
+ return (origin) => optsOrigin === origin ? origin : null;
1560
+ }
1561
+ } else if (typeof optsOrigin === "function") {
1562
+ return optsOrigin;
1563
+ } else {
1564
+ return (origin) => optsOrigin.includes(origin) ? origin : null;
1565
+ }
1566
+ })(opts.origin);
1567
+ const findAllowMethods = ((optsAllowMethods) => {
1568
+ if (typeof optsAllowMethods === "function") {
1569
+ return optsAllowMethods;
1570
+ } else if (Array.isArray(optsAllowMethods)) {
1571
+ return () => optsAllowMethods;
1572
+ } else {
1573
+ return () => [];
1574
+ }
1575
+ })(opts.allowMethods);
1576
+ return async function cors2(c, next) {
1577
+ function set(key, value) {
1578
+ c.res.headers.set(key, value);
1579
+ }
1580
+ const allowOrigin = await findAllowOrigin(c.req.header("origin") || "", c);
1581
+ if (allowOrigin) {
1582
+ set("Access-Control-Allow-Origin", allowOrigin);
1583
+ }
1584
+ if (opts.credentials) {
1585
+ set("Access-Control-Allow-Credentials", "true");
1586
+ }
1587
+ if (opts.exposeHeaders?.length) {
1588
+ set("Access-Control-Expose-Headers", opts.exposeHeaders.join(","));
1589
+ }
1590
+ if (c.req.method === "OPTIONS") {
1591
+ if (opts.origin !== "*") {
1592
+ set("Vary", "Origin");
1593
+ }
1594
+ if (opts.maxAge != null) {
1595
+ set("Access-Control-Max-Age", opts.maxAge.toString());
1596
+ }
1597
+ const allowMethods = await findAllowMethods(c.req.header("origin") || "", c);
1598
+ if (allowMethods.length) {
1599
+ set("Access-Control-Allow-Methods", allowMethods.join(","));
1600
+ }
1601
+ let headers = opts.allowHeaders;
1602
+ if (!headers?.length) {
1603
+ const requestHeaders = c.req.header("Access-Control-Request-Headers");
1604
+ if (requestHeaders) {
1605
+ headers = requestHeaders.split(/\s*,\s*/);
1606
+ }
1607
+ }
1608
+ if (headers?.length) {
1609
+ set("Access-Control-Allow-Headers", headers.join(","));
1610
+ c.res.headers.append("Vary", "Access-Control-Request-Headers");
1611
+ }
1612
+ c.res.headers.delete("Content-Length");
1613
+ c.res.headers.delete("Content-Type");
1614
+ return new Response(null, {
1615
+ headers: c.res.headers,
1616
+ status: 204,
1617
+ statusText: "No Content"
1618
+ });
1619
+ }
1620
+ await next();
1621
+ if (opts.origin !== "*") {
1622
+ c.header("Vary", "Origin", { append: true });
1623
+ }
1624
+ };
1625
+ };
1626
+
1627
+ // src/types/index.ts
1628
+ class ConfigNotFoundError extends Error {
1629
+ constructor(id) {
1630
+ super(`Config not found: ${id}`);
1631
+ this.name = "ConfigNotFoundError";
1632
+ }
1633
+ }
1634
+
1635
+ class ProfileNotFoundError extends Error {
1636
+ constructor(id) {
1637
+ super(`Profile not found: ${id}`);
1638
+ this.name = "ProfileNotFoundError";
1639
+ }
1640
+ }
1641
+
1642
+ class ConfigApplyError extends Error {
1643
+ constructor(message) {
1644
+ super(message);
1645
+ this.name = "ConfigApplyError";
1646
+ }
1647
+ }
1648
+
1649
+ // src/db/database.ts
1650
+ import { Database } from "bun:sqlite";
1651
+ import { existsSync, mkdirSync } from "fs";
1652
+ import { dirname, join, resolve } from "path";
1653
+ import { randomUUID } from "crypto";
1654
+ function getDbPath() {
1655
+ if (process.env["CONFIGS_DB_PATH"]) {
1656
+ return process.env["CONFIGS_DB_PATH"];
1657
+ }
1658
+ const home = process.env["HOME"] || process.env["USERPROFILE"] || "~";
1659
+ return join(home, ".configs", "configs.db");
1660
+ }
1661
+ function ensureDir(filePath) {
1662
+ if (filePath === ":memory:" || filePath.startsWith("file::memory:"))
1663
+ return;
1664
+ const dir = dirname(resolve(filePath));
1665
+ if (!existsSync(dir)) {
1666
+ mkdirSync(dir, { recursive: true });
1667
+ }
1668
+ }
1669
+ function uuid() {
1670
+ return randomUUID();
1671
+ }
1672
+ function now() {
1673
+ return new Date().toISOString();
1674
+ }
1675
+ function slugify(name) {
1676
+ return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
1677
+ }
1678
+ var MIGRATIONS = [
1679
+ `
1680
+ CREATE TABLE IF NOT EXISTS configs (
1681
+ id TEXT PRIMARY KEY,
1682
+ name TEXT NOT NULL,
1683
+ slug TEXT NOT NULL UNIQUE,
1684
+ kind TEXT NOT NULL DEFAULT 'file',
1685
+ category TEXT NOT NULL,
1686
+ agent TEXT NOT NULL DEFAULT 'global',
1687
+ target_path TEXT,
1688
+ format TEXT NOT NULL DEFAULT 'text',
1689
+ content TEXT NOT NULL DEFAULT '',
1690
+ description TEXT,
1691
+ tags TEXT NOT NULL DEFAULT '[]',
1692
+ is_template INTEGER NOT NULL DEFAULT 0,
1693
+ version INTEGER NOT NULL DEFAULT 1,
1694
+ created_at TEXT NOT NULL,
1695
+ updated_at TEXT NOT NULL,
1696
+ synced_at TEXT
1697
+ );
1698
+
1699
+ CREATE TABLE IF NOT EXISTS config_snapshots (
1700
+ id TEXT PRIMARY KEY,
1701
+ config_id TEXT NOT NULL REFERENCES configs(id) ON DELETE CASCADE,
1702
+ content TEXT NOT NULL,
1703
+ version INTEGER NOT NULL,
1704
+ created_at TEXT NOT NULL
1705
+ );
1706
+
1707
+ CREATE TABLE IF NOT EXISTS profiles (
1708
+ id TEXT PRIMARY KEY,
1709
+ name TEXT NOT NULL,
1710
+ slug TEXT NOT NULL UNIQUE,
1711
+ description TEXT,
1712
+ created_at TEXT NOT NULL,
1713
+ updated_at TEXT NOT NULL
1714
+ );
1715
+
1716
+ CREATE TABLE IF NOT EXISTS profile_configs (
1717
+ profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
1718
+ config_id TEXT NOT NULL REFERENCES configs(id) ON DELETE CASCADE,
1719
+ sort_order INTEGER NOT NULL DEFAULT 0,
1720
+ PRIMARY KEY (profile_id, config_id)
1721
+ );
1722
+
1723
+ CREATE TABLE IF NOT EXISTS machines (
1724
+ id TEXT PRIMARY KEY,
1725
+ hostname TEXT NOT NULL UNIQUE,
1726
+ os TEXT,
1727
+ last_applied_at TEXT,
1728
+ created_at TEXT NOT NULL
1729
+ );
1730
+
1731
+ CREATE TABLE IF NOT EXISTS schema_version (
1732
+ version INTEGER PRIMARY KEY
1733
+ );
1734
+
1735
+ INSERT OR IGNORE INTO schema_version (version) VALUES (1);
1736
+ `
1737
+ ];
1738
+ var _db = null;
1739
+ function getDatabase(path) {
1740
+ if (_db)
1741
+ return _db;
1742
+ const dbPath = path || getDbPath();
1743
+ ensureDir(dbPath);
1744
+ const db = new Database(dbPath);
1745
+ db.run("PRAGMA journal_mode = WAL");
1746
+ db.run("PRAGMA foreign_keys = ON");
1747
+ applyMigrations(db);
1748
+ _db = db;
1749
+ return db;
1750
+ }
1751
+ function applyMigrations(db) {
1752
+ let currentVersion = 0;
1753
+ try {
1754
+ const row = db.query("SELECT version FROM schema_version ORDER BY version DESC LIMIT 1").get();
1755
+ currentVersion = row?.version ?? 0;
1756
+ } catch {
1757
+ currentVersion = 0;
1758
+ }
1759
+ for (let i = currentVersion;i < MIGRATIONS.length; i++) {
1760
+ db.run(MIGRATIONS[i]);
1761
+ db.run(`INSERT OR REPLACE INTO schema_version (version) VALUES (${i + 1})`);
1762
+ }
1763
+ }
1764
+
1765
+ // src/db/configs.ts
1766
+ function rowToConfig(row) {
1767
+ return {
1768
+ ...row,
1769
+ tags: JSON.parse(row.tags || "[]"),
1770
+ is_template: !!row.is_template,
1771
+ kind: row.kind,
1772
+ category: row.category,
1773
+ agent: row.agent,
1774
+ format: row.format
1775
+ };
1776
+ }
1777
+ function uniqueSlug(name, db, excludeId) {
1778
+ const base = slugify(name);
1779
+ let slug = base;
1780
+ let i = 1;
1781
+ while (true) {
1782
+ const existing = db.query("SELECT id FROM configs WHERE slug = ?").get(slug);
1783
+ if (!existing || existing.id === excludeId)
1784
+ return slug;
1785
+ slug = `${base}-${i++}`;
1786
+ }
1787
+ }
1788
+ function createConfig(input, db) {
1789
+ const d = db || getDatabase();
1790
+ const id = uuid();
1791
+ const ts = now();
1792
+ const slug = uniqueSlug(input.name, d);
1793
+ const tags = JSON.stringify(input.tags || []);
1794
+ d.run(`INSERT INTO configs (id, name, slug, kind, category, agent, target_path, format, content, description, tags, is_template, version, created_at, updated_at, synced_at)
1795
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, NULL)`, [
1796
+ id,
1797
+ input.name,
1798
+ slug,
1799
+ input.kind ?? "file",
1800
+ input.category,
1801
+ input.agent ?? "global",
1802
+ input.target_path ?? null,
1803
+ input.format ?? "text",
1804
+ input.content,
1805
+ input.description ?? null,
1806
+ tags,
1807
+ input.is_template ? 1 : 0,
1808
+ ts,
1809
+ ts
1810
+ ]);
1811
+ return getConfig(id, d);
1812
+ }
1813
+ function getConfig(idOrSlug, db) {
1814
+ const d = db || getDatabase();
1815
+ const row = d.query("SELECT * FROM configs WHERE id = ? OR slug = ?").get(idOrSlug, idOrSlug);
1816
+ if (!row)
1817
+ throw new ConfigNotFoundError(idOrSlug);
1818
+ return rowToConfig(row);
1819
+ }
1820
+ function getConfigById(id, db) {
1821
+ const d = db || getDatabase();
1822
+ const row = d.query("SELECT * FROM configs WHERE id = ?").get(id);
1823
+ if (!row)
1824
+ throw new ConfigNotFoundError(id);
1825
+ return rowToConfig(row);
1826
+ }
1827
+ function listConfigs(filter, db) {
1828
+ const d = db || getDatabase();
1829
+ const conditions = [];
1830
+ const params = [];
1831
+ if (filter?.category) {
1832
+ conditions.push("category = ?");
1833
+ params.push(filter.category);
1834
+ }
1835
+ if (filter?.agent) {
1836
+ conditions.push("agent = ?");
1837
+ params.push(filter.agent);
1838
+ }
1839
+ if (filter?.kind) {
1840
+ conditions.push("kind = ?");
1841
+ params.push(filter.kind);
1842
+ }
1843
+ if (filter?.is_template !== undefined) {
1844
+ conditions.push("is_template = ?");
1845
+ params.push(filter.is_template ? 1 : 0);
1846
+ }
1847
+ if (filter?.search) {
1848
+ conditions.push("(name LIKE ? OR description LIKE ? OR content LIKE ?)");
1849
+ const q = `%${filter.search}%`;
1850
+ params.push(q, q, q);
1851
+ }
1852
+ if (filter?.tags && filter.tags.length > 0) {
1853
+ const tagConditions = filter.tags.map(() => "tags LIKE ?").join(" OR ");
1854
+ conditions.push(`(${tagConditions})`);
1855
+ for (const tag of filter.tags)
1856
+ params.push(`%"${tag}"%`);
1857
+ }
1858
+ const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1859
+ const rows = d.query(`SELECT * FROM configs ${where} ORDER BY category, name`).all(...params);
1860
+ return rows.map(rowToConfig);
1861
+ }
1862
+ function updateConfig(idOrSlug, input, db) {
1863
+ const d = db || getDatabase();
1864
+ const existing = getConfig(idOrSlug, d);
1865
+ const ts = now();
1866
+ const updates = ["updated_at = ?", "version = version + 1"];
1867
+ const params = [ts];
1868
+ if (input.name !== undefined) {
1869
+ updates.push("name = ?", "slug = ?");
1870
+ params.push(input.name, uniqueSlug(input.name, d, existing.id));
1871
+ }
1872
+ if (input.kind !== undefined) {
1873
+ updates.push("kind = ?");
1874
+ params.push(input.kind);
1875
+ }
1876
+ if (input.category !== undefined) {
1877
+ updates.push("category = ?");
1878
+ params.push(input.category);
1879
+ }
1880
+ if (input.agent !== undefined) {
1881
+ updates.push("agent = ?");
1882
+ params.push(input.agent);
1883
+ }
1884
+ if (input.target_path !== undefined) {
1885
+ updates.push("target_path = ?");
1886
+ params.push(input.target_path);
1887
+ }
1888
+ if (input.format !== undefined) {
1889
+ updates.push("format = ?");
1890
+ params.push(input.format);
1891
+ }
1892
+ if (input.content !== undefined) {
1893
+ updates.push("content = ?");
1894
+ params.push(input.content);
1895
+ }
1896
+ if (input.description !== undefined) {
1897
+ updates.push("description = ?");
1898
+ params.push(input.description);
1899
+ }
1900
+ if (input.tags !== undefined) {
1901
+ updates.push("tags = ?");
1902
+ params.push(JSON.stringify(input.tags));
1903
+ }
1904
+ if (input.is_template !== undefined) {
1905
+ updates.push("is_template = ?");
1906
+ params.push(input.is_template ? 1 : 0);
1907
+ }
1908
+ if (input.synced_at !== undefined) {
1909
+ updates.push("synced_at = ?");
1910
+ params.push(input.synced_at);
1911
+ }
1912
+ params.push(existing.id);
1913
+ d.run(`UPDATE configs SET ${updates.join(", ")} WHERE id = ?`, params);
1914
+ return getConfigById(existing.id, d);
1915
+ }
1916
+ function deleteConfig(idOrSlug, db) {
1917
+ const d = db || getDatabase();
1918
+ const existing = getConfig(idOrSlug, d);
1919
+ d.run("DELETE FROM configs WHERE id = ?", [existing.id]);
1920
+ }
1921
+ function getConfigStats(db) {
1922
+ const d = db || getDatabase();
1923
+ const rows = d.query("SELECT category, COUNT(*) as count FROM configs GROUP BY category").all();
1924
+ const stats = { total: 0 };
1925
+ for (const row of rows) {
1926
+ stats[row.category] = row.count;
1927
+ stats["total"] = (stats["total"] || 0) + row.count;
1928
+ }
1929
+ return stats;
1930
+ }
1931
+
1932
+ // src/db/profiles.ts
1933
+ function rowToProfile(row) {
1934
+ return { ...row };
1935
+ }
1936
+ function uniqueProfileSlug(name, db, excludeId) {
1937
+ const base = slugify(name);
1938
+ let slug = base;
1939
+ let i = 1;
1940
+ while (true) {
1941
+ const existing = db.query("SELECT id FROM profiles WHERE slug = ?").get(slug);
1942
+ if (!existing || existing.id === excludeId)
1943
+ return slug;
1944
+ slug = `${base}-${i++}`;
1945
+ }
1946
+ }
1947
+ function createProfile(input, db) {
1948
+ const d = db || getDatabase();
1949
+ const id = uuid();
1950
+ const ts = now();
1951
+ const slug = uniqueProfileSlug(input.name, d);
1952
+ d.run("INSERT INTO profiles (id, name, slug, description, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)", [id, input.name, slug, input.description ?? null, ts, ts]);
1953
+ return getProfile(id, d);
1954
+ }
1955
+ function getProfile(idOrSlug, db) {
1956
+ const d = db || getDatabase();
1957
+ const row = d.query("SELECT * FROM profiles WHERE id = ? OR slug = ?").get(idOrSlug, idOrSlug);
1958
+ if (!row)
1959
+ throw new ProfileNotFoundError(idOrSlug);
1960
+ return rowToProfile(row);
1961
+ }
1962
+ function listProfiles(db) {
1963
+ const d = db || getDatabase();
1964
+ return d.query("SELECT * FROM profiles ORDER BY name").all().map(rowToProfile);
1965
+ }
1966
+ function updateProfile(idOrSlug, input, db) {
1967
+ const d = db || getDatabase();
1968
+ const existing = getProfile(idOrSlug, d);
1969
+ const ts = now();
1970
+ const updates = ["updated_at = ?"];
1971
+ const params = [ts];
1972
+ if (input.name !== undefined) {
1973
+ updates.push("name = ?", "slug = ?");
1974
+ params.push(input.name, uniqueProfileSlug(input.name, d, existing.id));
1975
+ }
1976
+ if (input.description !== undefined) {
1977
+ updates.push("description = ?");
1978
+ params.push(input.description);
1979
+ }
1980
+ params.push(existing.id);
1981
+ d.run(`UPDATE profiles SET ${updates.join(", ")} WHERE id = ?`, params);
1982
+ return getProfile(existing.id, d);
1983
+ }
1984
+ function deleteProfile(idOrSlug, db) {
1985
+ const d = db || getDatabase();
1986
+ const existing = getProfile(idOrSlug, d);
1987
+ d.run("DELETE FROM profiles WHERE id = ?", [existing.id]);
1988
+ }
1989
+ function getProfileConfigs(profileIdOrSlug, db) {
1990
+ const d = db || getDatabase();
1991
+ const profile = getProfile(profileIdOrSlug, d);
1992
+ const rows = d.query("SELECT config_id FROM profile_configs WHERE profile_id = ? ORDER BY sort_order").all(profile.id);
1993
+ if (rows.length === 0)
1994
+ return [];
1995
+ const ids = rows.map((r) => r.config_id);
1996
+ return listConfigs(undefined, d).filter((c) => ids.includes(c.id));
1997
+ }
1998
+
1999
+ // src/db/snapshots.ts
2000
+ function createSnapshot(configId, content, version, db) {
2001
+ const d = db || getDatabase();
2002
+ const id = uuid();
2003
+ const ts = now();
2004
+ d.run("INSERT INTO config_snapshots (id, config_id, content, version, created_at) VALUES (?, ?, ?, ?, ?)", [id, configId, content, version, ts]);
2005
+ return { id, config_id: configId, content, version, created_at: ts };
2006
+ }
2007
+ function listSnapshots(configId, db) {
2008
+ const d = db || getDatabase();
2009
+ return d.query("SELECT * FROM config_snapshots WHERE config_id = ? ORDER BY version DESC").all(configId);
2010
+ }
2011
+
2012
+ // src/db/machines.ts
2013
+ import { hostname, type } from "os";
2014
+ function currentHostname() {
2015
+ return hostname();
2016
+ }
2017
+ function currentOs() {
2018
+ return type();
2019
+ }
2020
+ function registerMachine(hostnameStr, os, db) {
2021
+ const d = db || getDatabase();
2022
+ const h = hostnameStr ?? currentHostname();
2023
+ const o = os ?? currentOs();
2024
+ const existing = d.query("SELECT * FROM machines WHERE hostname = ?").get(h);
2025
+ if (existing)
2026
+ return existing;
2027
+ const id = uuid();
2028
+ const ts = now();
2029
+ d.run("INSERT INTO machines (id, hostname, os, last_applied_at, created_at) VALUES (?, ?, ?, NULL, ?)", [id, h, o, ts]);
2030
+ return d.query("SELECT * FROM machines WHERE id = ?").get(id);
2031
+ }
2032
+ function listMachines(db) {
2033
+ const d = db || getDatabase();
2034
+ return d.query("SELECT * FROM machines ORDER BY last_applied_at DESC NULLS LAST").all();
2035
+ }
2036
+
2037
+ // src/lib/apply.ts
2038
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync, writeFileSync } from "fs";
2039
+ import { dirname as dirname2, resolve as resolve2 } from "path";
2040
+ import { homedir } from "os";
2041
+ function expandPath(p) {
2042
+ if (p.startsWith("~/")) {
2043
+ return resolve2(homedir(), p.slice(2));
2044
+ }
2045
+ return resolve2(p);
2046
+ }
2047
+ async function applyConfig(config, opts = {}) {
2048
+ if (!config.target_path) {
2049
+ throw new ConfigApplyError(`Config "${config.name}" is a reference (kind=reference) and has no target_path \u2014 cannot apply to disk.`);
2050
+ }
2051
+ const path = expandPath(config.target_path);
2052
+ const previousContent = existsSync2(path) ? readFileSync(path, "utf-8") : null;
2053
+ const changed = previousContent !== config.content;
2054
+ if (!opts.dryRun) {
2055
+ const dir = dirname2(path);
2056
+ if (!existsSync2(dir)) {
2057
+ mkdirSync2(dir, { recursive: true });
2058
+ }
2059
+ if (previousContent !== null && changed) {
2060
+ const db2 = opts.db || getDatabase();
2061
+ createSnapshot(config.id, previousContent, config.version, db2);
2062
+ }
2063
+ writeFileSync(path, config.content, "utf-8");
2064
+ const db = opts.db || getDatabase();
2065
+ updateConfig(config.id, { synced_at: now() }, db);
2066
+ }
2067
+ return {
2068
+ config_id: config.id,
2069
+ path,
2070
+ previous_content: previousContent,
2071
+ new_content: config.content,
2072
+ dry_run: opts.dryRun ?? false,
2073
+ changed
2074
+ };
2075
+ }
2076
+ async function applyConfigs(configs, opts = {}) {
2077
+ const results = [];
2078
+ for (const config of configs) {
2079
+ if (config.kind === "reference")
2080
+ continue;
2081
+ results.push(await applyConfig(config, opts));
2082
+ }
2083
+ return results;
2084
+ }
2085
+
2086
+ // src/lib/sync.ts
2087
+ import { existsSync as existsSync3, readdirSync, readFileSync as readFileSync2, statSync } from "fs";
2088
+ import { extname, join as join2, relative } from "path";
2089
+ import { homedir as homedir2 } from "os";
2090
+ function detectCategory(filePath) {
2091
+ const p = filePath.toLowerCase().replace(homedir2(), "~");
2092
+ if (p.includes("/.claude/rules/") || p.endsWith("claude.md") || p.endsWith("agents.md") || p.endsWith("gemini.md"))
2093
+ return "rules";
2094
+ if (p.includes("/.claude/") || p.includes("/.codex/") || p.includes("/.gemini/") || p.includes("/.cursor/"))
2095
+ return "agent";
2096
+ if (p.includes(".mcp.json") || p.includes("mcp"))
2097
+ return "mcp";
2098
+ if (p.includes(".zshrc") || p.includes(".zprofile") || p.includes(".bashrc") || p.includes(".bash_profile"))
2099
+ return "shell";
2100
+ if (p.includes(".gitconfig") || p.includes(".gitignore"))
2101
+ return "git";
2102
+ if (p.includes(".npmrc") || p.includes("tsconfig") || p.includes("bunfig"))
2103
+ return "tools";
2104
+ if (p.includes(".secrets"))
2105
+ return "secrets_schema";
2106
+ return "tools";
2107
+ }
2108
+ function detectAgent(filePath) {
2109
+ const p = filePath.toLowerCase().replace(homedir2(), "~");
2110
+ if (p.includes("/.claude/") || p.endsWith("claude.md"))
2111
+ return "claude";
2112
+ if (p.includes("/.codex/") || p.endsWith("agents.md"))
2113
+ return "codex";
2114
+ if (p.includes("/.gemini/") || p.endsWith("gemini.md"))
2115
+ return "gemini";
2116
+ if (p.includes(".zshrc") || p.includes(".zprofile") || p.includes(".bashrc"))
2117
+ return "zsh";
2118
+ if (p.includes(".gitconfig") || p.includes(".gitignore"))
2119
+ return "git";
2120
+ if (p.includes(".npmrc"))
2121
+ return "npm";
2122
+ return "global";
2123
+ }
2124
+ function detectFormat(filePath) {
2125
+ const ext = extname(filePath).toLowerCase();
2126
+ if (ext === ".json")
2127
+ return "json";
2128
+ if (ext === ".toml")
2129
+ return "toml";
2130
+ if (ext === ".yaml" || ext === ".yml")
2131
+ return "yaml";
2132
+ if (ext === ".md" || ext === ".markdown")
2133
+ return "markdown";
2134
+ if (ext === ".ini" || ext === ".cfg")
2135
+ return "ini";
2136
+ return "text";
2137
+ }
2138
+ var SKIP_PATTERNS = [".db", ".db-shm", ".db-wal", ".log", ".lock", ".DS_Store", "node_modules", ".git"];
2139
+ function shouldSkip(p) {
2140
+ return SKIP_PATTERNS.some((pat) => p.includes(pat));
2141
+ }
2142
+ function walkDir(dir, files = []) {
2143
+ const entries = readdirSync(dir, { withFileTypes: true });
2144
+ for (const entry of entries) {
2145
+ const full = join2(dir, entry.name);
2146
+ if (shouldSkip(full))
2147
+ continue;
2148
+ if (entry.isDirectory()) {
2149
+ walkDir(full, files);
2150
+ } else if (entry.isFile()) {
2151
+ files.push(full);
2152
+ }
2153
+ }
2154
+ return files;
2155
+ }
2156
+ async function syncFromDir(dir, opts = {}) {
2157
+ const d = opts.db || getDatabase();
2158
+ const absDir = expandPath(dir);
2159
+ if (!existsSync3(absDir)) {
2160
+ return { added: 0, updated: 0, unchanged: 0, skipped: [`Directory not found: ${absDir}`] };
2161
+ }
2162
+ const files = opts.recursive !== false ? walkDir(absDir) : readdirSync(absDir).map((f) => join2(absDir, f)).filter((f) => statSync(f).isFile());
2163
+ const result = { added: 0, updated: 0, unchanged: 0, skipped: [] };
2164
+ const allConfigs = listConfigs(undefined, d);
2165
+ for (const file of files) {
2166
+ if (shouldSkip(file)) {
2167
+ result.skipped.push(file);
2168
+ continue;
2169
+ }
2170
+ try {
2171
+ const content = readFileSync2(file, "utf-8");
2172
+ const targetPath = file.startsWith(homedir2()) ? file.replace(homedir2(), "~") : file;
2173
+ const existing = allConfigs.find((c) => c.target_path === targetPath);
2174
+ if (!existing) {
2175
+ if (!opts.dryRun) {
2176
+ const name = relative(absDir, file);
2177
+ createConfig({
2178
+ name,
2179
+ category: detectCategory(file),
2180
+ agent: detectAgent(file),
2181
+ target_path: targetPath,
2182
+ format: detectFormat(file),
2183
+ content
2184
+ }, d);
2185
+ }
2186
+ result.added++;
2187
+ } else if (existing.content !== content) {
2188
+ if (!opts.dryRun) {
2189
+ updateConfig(existing.id, { content }, d);
2190
+ }
2191
+ result.updated++;
2192
+ } else {
2193
+ result.unchanged++;
2194
+ }
2195
+ } catch {
2196
+ result.skipped.push(file);
2197
+ }
2198
+ }
2199
+ return result;
2200
+ }
2201
+ async function syncToDir(dir, opts = {}) {
2202
+ const d = opts.db || getDatabase();
2203
+ const absDir = expandPath(dir);
2204
+ const normalizedDir = dir.startsWith("~/") ? dir : absDir.replace(homedir2(), "~");
2205
+ const configs = listConfigs(undefined, d).filter((c) => c.target_path && (c.target_path.startsWith(normalizedDir) || c.target_path.startsWith(absDir)));
2206
+ const result = { added: 0, updated: 0, unchanged: 0, skipped: [] };
2207
+ for (const config of configs) {
2208
+ if (config.kind === "reference")
2209
+ continue;
2210
+ try {
2211
+ const r = await applyConfig(config, { dryRun: opts.dryRun, db: d });
2212
+ if (r.changed) {
2213
+ existsSync3(expandPath(config.target_path)) ? result.updated++ : result.added++;
2214
+ } else {
2215
+ result.unchanged++;
2216
+ }
2217
+ } catch {
2218
+ result.skipped.push(config.target_path || config.id);
2219
+ }
2220
+ }
2221
+ return result;
2222
+ }
2223
+
2224
+ // src/server/index.ts
2225
+ var PORT = Number(process.env["CONFIGS_PORT"] ?? 3457);
2226
+ function pickFields(obj, fields) {
2227
+ if (!fields)
2228
+ return obj;
2229
+ const keys = fields.split(",").map((f) => f.trim());
2230
+ return Object.fromEntries(keys.filter((k) => (k in obj)).map((k) => [k, obj[k]]));
2231
+ }
2232
+ var app = new Hono2;
2233
+ app.use("*", cors());
2234
+ app.get("/api/stats", (c) => c.json(getConfigStats()));
2235
+ app.get("/api/configs", (c) => {
2236
+ const { category, agent, kind, search, fields } = c.req.query();
2237
+ const configs = listConfigs({
2238
+ category: category || undefined,
2239
+ agent: agent || undefined,
2240
+ kind: kind || undefined,
2241
+ search: search || undefined
2242
+ });
2243
+ return c.json(fields ? configs.map((cfg) => pickFields(cfg, fields)) : configs);
2244
+ });
2245
+ app.post("/api/configs", async (c) => {
2246
+ try {
2247
+ const body = await c.req.json();
2248
+ const config = createConfig({
2249
+ name: body.name,
2250
+ content: body.content ?? "",
2251
+ category: body.category,
2252
+ agent: body.agent,
2253
+ kind: body.kind,
2254
+ target_path: body.target_path,
2255
+ format: body.format,
2256
+ tags: body.tags,
2257
+ description: body.description,
2258
+ is_template: body.is_template
2259
+ });
2260
+ return c.json(config, 201);
2261
+ } catch (e) {
2262
+ return c.json({ error: e instanceof Error ? e.message : String(e) }, 422);
2263
+ }
2264
+ });
2265
+ app.get("/api/configs/:id", (c) => {
2266
+ try {
2267
+ const { fields } = c.req.query();
2268
+ const config = getConfig(c.req.param("id"));
2269
+ return c.json(pickFields(config, fields));
2270
+ } catch {
2271
+ return c.json({ error: "Not found" }, 404);
2272
+ }
2273
+ });
2274
+ app.put("/api/configs/:id", async (c) => {
2275
+ try {
2276
+ const body = await c.req.json();
2277
+ const config = updateConfig(c.req.param("id"), body);
2278
+ return c.json(config);
2279
+ } catch (e) {
2280
+ return c.json({ error: e instanceof Error ? e.message : String(e) }, 422);
2281
+ }
2282
+ });
2283
+ app.delete("/api/configs/:id", (c) => {
2284
+ try {
2285
+ deleteConfig(c.req.param("id"));
2286
+ return c.json({ ok: true });
2287
+ } catch {
2288
+ return c.json({ error: "Not found" }, 404);
2289
+ }
2290
+ });
2291
+ app.post("/api/configs/:id/apply", async (c) => {
2292
+ try {
2293
+ const body = await c.req.json().catch(() => ({}));
2294
+ const config = getConfig(c.req.param("id"));
2295
+ const result = await applyConfig(config, { dryRun: body.dry_run });
2296
+ return c.json(result);
2297
+ } catch (e) {
2298
+ return c.json({ error: e instanceof Error ? e.message : String(e) }, 422);
2299
+ }
2300
+ });
2301
+ app.post("/api/configs/:id/snapshot", async (c) => {
2302
+ try {
2303
+ const config = getConfig(c.req.param("id"));
2304
+ const snap = createSnapshot(config.id, config.content, config.version);
2305
+ return c.json(snap, 201);
2306
+ } catch (e) {
2307
+ return c.json({ error: e instanceof Error ? e.message : String(e) }, 422);
2308
+ }
2309
+ });
2310
+ app.get("/api/configs/:id/snapshots", (c) => {
2311
+ try {
2312
+ const config = getConfig(c.req.param("id"));
2313
+ return c.json(listSnapshots(config.id));
2314
+ } catch {
2315
+ return c.json({ error: "Not found" }, 404);
2316
+ }
2317
+ });
2318
+ app.post("/api/sync", async (c) => {
2319
+ try {
2320
+ const body = await c.req.json();
2321
+ const dir = body.dir || "~/.claude";
2322
+ const direction = body.direction || "from_disk";
2323
+ const result = direction === "to_disk" ? await syncToDir(dir, { dryRun: body.dry_run }) : await syncFromDir(dir, { dryRun: body.dry_run });
2324
+ return c.json(result);
2325
+ } catch (e) {
2326
+ return c.json({ error: e instanceof Error ? e.message : String(e) }, 422);
2327
+ }
2328
+ });
2329
+ app.get("/api/profiles", (c) => c.json(listProfiles()));
2330
+ app.post("/api/profiles", async (c) => {
2331
+ try {
2332
+ const body = await c.req.json();
2333
+ const profile = createProfile({ name: body.name, description: body.description });
2334
+ return c.json(profile, 201);
2335
+ } catch (e) {
2336
+ return c.json({ error: e instanceof Error ? e.message : String(e) }, 422);
2337
+ }
2338
+ });
2339
+ app.get("/api/profiles/:id", (c) => {
2340
+ try {
2341
+ const profile = getProfile(c.req.param("id"));
2342
+ const configs = getProfileConfigs(c.req.param("id"));
2343
+ return c.json({ ...profile, configs });
2344
+ } catch {
2345
+ return c.json({ error: "Not found" }, 404);
2346
+ }
2347
+ });
2348
+ app.put("/api/profiles/:id", async (c) => {
2349
+ try {
2350
+ const body = await c.req.json();
2351
+ const profile = updateProfile(c.req.param("id"), body);
2352
+ return c.json(profile);
2353
+ } catch (e) {
2354
+ return c.json({ error: e instanceof Error ? e.message : String(e) }, 422);
2355
+ }
2356
+ });
2357
+ app.delete("/api/profiles/:id", (c) => {
2358
+ try {
2359
+ deleteProfile(c.req.param("id"));
2360
+ return c.json({ ok: true });
2361
+ } catch {
2362
+ return c.json({ error: "Not found" }, 404);
2363
+ }
2364
+ });
2365
+ app.post("/api/profiles/:id/apply", async (c) => {
2366
+ try {
2367
+ const body = await c.req.json().catch(() => ({}));
2368
+ const configs = getProfileConfigs(c.req.param("id"));
2369
+ const results = await applyConfigs(configs, { dryRun: body.dry_run });
2370
+ return c.json(results);
2371
+ } catch (e) {
2372
+ return c.json({ error: e instanceof Error ? e.message : String(e) }, 422);
2373
+ }
2374
+ });
2375
+ app.get("/api/machines", (c) => c.json(listMachines()));
2376
+ app.post("/api/machines", async (c) => {
2377
+ try {
2378
+ const body = await c.req.json().catch(() => ({}));
2379
+ const machine = registerMachine(body.hostname, body.os);
2380
+ return c.json(machine, 201);
2381
+ } catch (e) {
2382
+ return c.json({ error: e instanceof Error ? e.message : String(e) }, 422);
2383
+ }
2384
+ });
2385
+ app.get("/health", (c) => c.json({ ok: true, version: "0.1.0" }));
2386
+ console.log(`configs-serve listening on http://localhost:${PORT}`);
2387
+ var server_default = { port: PORT, fetch: app.fetch };
2388
+ export {
2389
+ server_default as default
2390
+ };